# Trace schema & JSON-path rules (query-accuracy contract)

Supports Stage 2 (`athena-cloudwatch-connector.md`). The connector hands you the
record as one STRING in `message`; query accuracy is almost entirely a matter of
addressing the right JSON path inside it. Both the selector that decides which
rows to keep AND any field you extract are JSON paths — get them wrong and the
query silently returns NULL or zero rows rather than erroring. The rules below are
grounded in the actual record shapes; treat them as the contract, not the
pretty-printed field order a sample happens to show.

## Rule 1 — dotted keys need BRACKET notation, not dot notation

The gen_ai / OpenTelemetry convention puts dots INSIDE key names
(`gen_ai.usage.input_tokens`, `http.status_code`, `gen_ai.response.finish_reasons`).
In a Trino/Presto JSON path a dot is the child-nav operator, so
`$.gen_ai.usage.input_tokens` is read as `obj → "gen_ai" → "usage" → "input_tokens"`
(three nested objects) and returns NULL against a record whose key is the single
literal string `"gen_ai.usage.input_tokens"`. This is a common cause
of a query that "runs but every column is NULL".

```sql
-- WRONG: dot-path splits the key into non-existent nesting → NULL
json_extract_scalar(message, '$.attributes.gen_ai.usage.input_tokens')
-- RIGHT: bracket + quotes treats the dotted name as one literal key
json_extract_scalar(message, '$.attributes["gen_ai.usage.input_tokens"]')
```

Use bracket notation for EVERY dotted key. Reserve dot notation for genuinely
nested objects whose own key names contain no dots (e.g. `$.body`, `$.resource`).

The engine permits any path and errors on none: a wrong or misspelled JSON path
returns NULL, not an error, and that is indistinguishable from "no such data". So
**an all-NULL column from a query that ran is a signal to verify the field name
before concluding the data is absent** — almost always a dotted-key path that
needs the bracket fix above. Confirm the path on a 1-row probe (Rule 5), never
read NULL as "the field isn't there".

## Rule 2 — the same field lives at more than one depth; pick the stable one

An inference-span record duplicates the scalar fields. For
`http_status_code` / `finish_reasons` / token counts they appear BOTH at
top-level `attributes.*` (dotted keys) AND inside `body.*`:

- `$.attributes["gen_ai.usage.input_tokens"]`  ← flattened top-level (bracket key)
- `$.body["gen_ai.usage.input_tokens"]`        ← also here

Prefer the **top-level `attributes.*`** copy for scalar filters/projections: it is
the flattened EMF/attribute view and is generally the more stable across emitter versions
(keep the chosen path in a mapping — Rule 5).

**Extracted scalars come out string-typed — cast before you compare.**
`json_extract_scalar` returns VARCHAR, and the ingested values keep their original
type, so a numeric filter on token counts, `duration_ms`, or a status code must
wrap the path in a cast or the comparison is lexical (`'900' > '1000'` is true as
strings) or silently fails. Use `TRY_CAST` (returns NULL on an unparseable value)
rather than `CAST` (errors the whole query on one bad row):

```sql
-- numeric filter on a string-typed scalar
WHERE TRY_CAST(json_extract_scalar(message, '$.attributes["gen_ai.usage.output_tokens"]') AS BIGINT) > 64
```

The cast rule applies to the Trino standard-SQL fallback and any post-UNLOAD SQL;
in the Logs Insights passthrough the dotted field is already numeric-comparable
when backtick-quoted (see the Worked selectors below).

## Rule 3 — prompt/response content is a nested ARRAY of polymorphic objects

The actual prompt and completion are NOT scalar strings. On an inference span they
live at:

```
$.events[0].attributes["gen_ai.input.messages"]        -- array of {role, parts:[{type, content}]}
$.events[0].attributes["gen_ai.output.messages"]       -- array of {role, parts:[{type, content}], finish_reason}
```

`events` is a top-level key in the record as the endpoint's trace stream holds it;
a source that wraps the record under `body` carries the same paths under
`$.body.events[0]`, so probe which of the two the source carries (Rule 5).

Two traps:

- **`events` is an array** — index it (`events[0]`), do not treat it as an object.
- **`parts[].content` is polymorphic** — sometimes a plain string
  (the user/system text) and sometimes a nested JSON OBJECT
  (e.g. a structured-output payload `{"<field>": {...}}`). `json_extract_scalar`
  returns NULL when the node is an object (it only coerces scalars); use
  `json_extract` (returns JSON) for the content node and let the downstream
  `dataset-transformation` reshape it. Do not assume the model's output is a string.

Because of this nesting + polymorphism, the drift-proof default stays: **SELECT the
whole `message` column (the entire record) and leave field extraction to
`dataset-transformation`** — do not pre-flatten here. (`$.body` is a path *into*
`message`, reached with `json_extract(message, '$.body')`, not a column you can
SELECT on its own.) Only pull individual scalars into the SELECT when the
caller needs them for a FILTER (see the selector rules) — not to pre-flatten the
dataset.

## Rule 4 — match the selector to the record shape (there is more than one)

The skill's sources cover several distinct record shapes, each with its own
discriminator and log-group location. The exact
group paths are owned by `log-group-resolution.md` (don't restate them per query);
this table keys off the record's discriminator, not the path:

| Shape | Where it lives | Discriminator | Selector |
|---|---|---|---|
| **SageMaker inference span** | a `.../traces` stream in the endpoint's own group or its `/traces` group | `$.attributes["aws.genai.span_kind"] = "LLM"` (raw OTel span envelope) | `filter @message like /aws.genai.span_kind/` |
| **SageMaker online-eval result** | standalone online-eval group **or** the `sm-eval-results` stream inside either endpoint group | `$.type = "sm_online_eval_result"` | `filter @message like /sm_online_eval_result/` |
| **Bedrock invocation** | customer-chosen group | `operation` / `modelId` present; no span marker | all-rows, or an `operation`/`modelId` predicate |
| **AgentCore runtime span** | agentcore runtime `spans` stream (or shared `aws/spans`) | span `name` + framework `scope` (`strands.telemetry.tracer` for Strands; other frameworks differ — confirm on the probe) | `filter @message like /strands.telemetry.tracer/` (Strands) then narrow to the `chat` span name (see AgentCore note below) |

**Scope endpoint-group queries to the `.../traces` stream.** Both endpoint
groups also hold non-trace streams, so an unscoped `all_log_streams` /
`LOGGROUPNAMES` sweep pulls in content that is not an inference span. Target the `.../traces`-suffixed stream (see
`log-group-resolution.md`). The `sm-eval-results` stream likewise carries rows
other than per-sample verdicts, so filter to `sm_online_eval_result` when you want
the scored, `traceId`-joinable shape.

Verify before relying on a discriminator: the **AgentCore runtime span** row
(for the split `aws/spans` layout), the **Bedrock invocation** row, and the
standalone online-eval group are derived from the record schema, so confirm each
on a 1-row probe (Rule 5) before trusting its discriminator.

The important correctness point: **the inference-span selector matches ZERO rows
against an online-eval group**, because online-eval records carry `type` /
`gen_ai.evaluation.*` and an EMF `_aws.CloudWatchMetrics` block, not an
`aws.genai.span_kind` marker. Resolve the selector from the resolved log group's
shape; never carry the inference-span selector onto an eval group (it would read
as "empty, stop"). The online-eval record also flattens its key fields to the TOP
level (e.g. `$["gen_ai.evaluation.score.value"]` or an evaluator-named key, plus `$["gen_ai.evaluation.name"]`, `$["gen_ai.request.model"]`)
in addition to the nested `$.attributes.*` copies — same top-level-is-stable
guidance as Rule 2; confirm the exact top-level score key on a 1-row probe (Rule 5, see Rule 4a).

The table lists two destinations for eval records because per-endpoint monitoring
(the `model-deployment` turn-on-monitoring path) provisions a `sm-eval-results`
STREAM inside either or both of the endpoint's two groups, while a standalone online-eval job
writes to its own `/aws/sagemaker/online-eval/<job>` group (the shape shown here).
So when you expect eval rows but one location is empty or absent, check the other
before concluding none were written. The two destinations hold different record
shapes: the standalone online-eval group's records are Rule 4a's, the endpoint
monitoring stream's (`sm-eval-results`) are Rule 4c's. Confirm the shape of the
destination you read on a 1-row probe (Rule 5); do not carry one's selectors onto
the other.

### Rule 4a — extracting the online-eval shape (`sm_online_eval_result`)

If eval records are in scope (mining low-scoring answers), two
extraction-side traps matter beyond the selector:

- **The score is string-typed.** `gen_ai.evaluation.score.value` (and any
  flattened top-level copy — the top-level key may be the canonical
  `$["gen_ai.evaluation.score.value"]` or an evaluator-named key `$["<evaluator_name>"]`,
  so confirm which on a 1-row probe per Rule 5) ingests as a string, so a
  threshold filter needs `TRY_CAST(... AS DOUBLE)` — see Rule 2. A lexical compare
  on the raw string silently misorders scores.
- **Gate on job success before trusting a verdict.** An eval row with
  `error.type` present is a judge/job failure, not a real score — filter to
  `error.type IS NULL` (equivalently, require a present `gen_ai.evaluation.score.value`)
  so a failed evaluation is not read as a passing or failing answer.

How to *interpret* a score once extracted — numeric vs categorical evaluators,
and per-evaluator polarity (a high score is bad for safety evaluators like
Toxicity/Bias) — is scoring semantics, not extraction, and belongs to the
`dataset-transformation` / evaluation skill, not here.

Do NOT join spans to eval scores automatically. The two shapes are complementary
— spans carry the prompt/response but no score, eval rows carry the score but no
prompt/response — so a join is only meaningful when BOTH exist for the same
traces. When you find an eval stream alongside the spans, show the user a sample
record from each and PROPOSE the join (keyed on `trace_id` — the eval rows carry
`traceId`/`trace_id`, not `request_id`) so the score travels with the
prompt/response it grades; let the user decide rather than joining unprompted.

### Rule 4b — extracting AgentCore runtime spans (content is in `events[]`, not `attributes`)

AgentCore spans differ from the SageMaker inference span in where the content
lives and which spans carry it. Three facts the selector and extraction depend on:

- **Content is in span `events[]`, only on the framework-scope spans.** One agent
  turn emits a span tree sharing a `traceId` — e.g. `invoke_agent` →
  `execute_event_loop_cycle` → `chat` (`scope = strands.telemetry.tracer`) → `chat
  <model>` (`scope = ...botocore`) → `POST /invocations` (starlette). Only the
  strands-scope spans attach the conversation as `events[]`; the botocore and
  starlette spans carry metadata only and have **no** content events. Filter to the
  strands `chat` span so each model call is counted once with its content (the
  `invoke_agent` span repeats the same content for the whole turn — use it only if
  you want the whole conversation as one row).
- **The message paths.** Inside a strands span's events: the input is in the
  `gen_ai.user.message` / `gen_ai.system.message` events, and the agent's answer is
  in the **`gen_ai.choice`** event (NOT `gen_ai.assistant.message`). Index `events`
  as an array (Rule 3), e.g. the content node at
  `events[].attributes.content` keyed by `events[].name`.
- **Content is double-JSON-encoded.** The `content` value is itself a JSON string,
  so a single `json_extract` yields an escaped string, not an object — pull it with
  `json_extract` then parse the result again (or hand the raw record to
  `dataset-transformation` and let the deterministic reshape own the second
  decode). Do not assume one extract reaches the text.

AgentCore spans are identified by span `scope` and `name`, not by the markers the
other sources use. The `scope` is framework-specific: `strands.telemetry.tracer`
is the Strands Agents SDK's scope, but AgentCore also hosts LangGraph, CrewAI and
custom-OTel agents whose spans use a different `scope` — against those the Strands
selector matches ZERO rows, so confirm the actual `scope` on the Rule 5 1-row
probe and re-resolve per framework rather than assuming Strands. Resolve the selector from the
resolved AgentCore group, same as Rule 4. Selecting
"bad traces" by evaluator score (the eval→span id-join against
`/aws/bedrock-agentcore/evaluations/...`) has **no validated workflow here** —
`overview.md` names it as a non-goal; this reference extracts the runtime spans only.

### Rule 4c — the endpoint monitoring stream (`sm-eval-results`): a verdict, not `passed`

Model-quality monitoring of a SageMaker endpoint (the `model-deployment` monitoring
sub-workflows) writes its results to an `sm-eval-results` stream in the endpoint's
own log groups. Its per-trace records are `sm_online_eval_result` records too, but
their shape differs from the standalone online-eval group's (Rule 4a):

- the verdict is `$.attributes["aws.sagemaker.evaluation.verdict"]`: `passed`,
  `failed`, or `unevaluable`; there is no `gen_ai.evaluation.passed`, so the
  `passed_raw` selector in the worked selectors below does not apply to this stream
- the criteria name is the top-level `$["gen_ai.evaluation.name"]`, also kept at
  `$.attributes["aws.sagemaker.evaluation.criterion_name"]`
- the monitoring configuration name is `$["aws.sagemaker.model_monitor.config_name"]`

## Rule 5 — keep the paths in a mapping, verify them on a 1-row probe

- Put every JSON path behind a named mapping/constant (per shape), not inlined in
  each query, so a schema move is a one-line change — the gen_ai spec is
  Development-status and these keys are expected to drift.
- Before a full extraction, run a **1-row probe** (`LIMIT 1`, or a `GetLogEvents`
  tail) and confirm each path you depend on returns non-NULL on a known-good
  record. A NULL on the probe means a wrong path (usually Rule 1), not missing
  data — fix the path, do not widen the window. This is the cheapest guard against
  shipping a query that extracts an all-NULL dataset.

## Worked selectors (passthrough `QUERYSTRING`)

Inference spans, succeeded and not truncated (a validity gate, not a quality gate
— the right-answer decision is the eval run / HIL label, not `http.status_code`).
**`http.status_code` is a numeric JSON leaf, and Logs Insights' automatic field
discovery does not expose it for direct `filter`/`ispresent` use** (confirmed
live: `ispresent(http.status_code) and http.status_code = 200` silently matches
zero rows against 33 live spans that all carry it) — extract it with `parse`
first, then filter the parsed string:

```text
fields @timestamp, @message
| filter @message like /aws.genai.span_kind/
| parse @message '"http.status_code":*,' as status_raw
| filter status_raw = "200"
```

Online-eval passes for one evaluation in the standalone online-eval group (the
`sm_online_eval_result` selector already excludes the stream's other row kinds,
the run summaries and model verdicts — see Rule 4; the endpoint monitoring stream's
rows carry the verdict of Rule 4c instead of `passed`). **`gen_ai.evaluation.passed` is a JSON
boolean, and Logs Insights' automatic field discovery does not expose
boolean-valued leaf keys for direct `filter` comparison** (confirmed live: a
sibling string field like `gen_ai.evaluation.name` resolves fine, but a direct
`gen_ai.evaluation.passed = 1`/`= true` comparison silently matches zero rows
even when passing records exist) — extract it with `parse` first, then filter the
parsed string:

```text
fields @timestamp, @message
| filter @message like /sm_online_eval_result/
| filter not ispresent(`error.type`)
| filter `gen_ai.evaluation.name` = '<evaluator_name>'
| parse @message '"gen_ai.evaluation.passed": *,' as passed_raw
| filter passed_raw = "true"
```

AgentCore strands `chat` spans (the content-bearing spans — Rule 4b). This is
safe as-is against the per-runtime unified group; against the shared `aws/spans`
group (every runtime's spans in one group — `log-group-resolution.md`) also
filter on the backtick-quoted span field that carries the runtime/agent id
(confirmed on the Rule 5 probe), not a substring over `@message` — a substring
also matches when the id merely appears inside conversation content or a
parent/child trace reference, which defeats the scoping:

```text
fields @timestamp, @message
| filter @message like /strands.telemetry.tracer/ and name = 'chat'
| filter `<runtime-id-field-from-probe>` = '<agent-or-runtime-id>'
```

Logs Insights uses backtick-quoted field names for dotted keys in `filter`/`fields`
(the Insights analogue of Rule 1's bracket notation). The Trino bracket form
(`$["..."]`) is for the standard-SQL fallback path and for any post-UNLOAD SQL.
