# Resolve the CloudWatch log group

Stage 1 of `overview.md`. Turn the user's intent into a concrete, existing log
group and a query window. Fail closed: if no candidate group exists, say so —
never query a fabricated name.

## Bedrock model-invocation logs

The log group is **customer-chosen**: Bedrock invocation logging is enabled per
account/region to a destination the customer names, so there is no fixed path to
assume. (`aws/bedrock/modelinvocations` is the log STREAM name, not the group.)
Resolve it in this order:

1. If the user named a group, use it.
2. Otherwise read the configured destination:
   `aws bedrock get-model-invocation-logging-configuration --region <r>` and take
   `loggingConfig.cloudWatchConfig.logGroupName`.
3. If logging is disabled or has no CloudWatch destination, there is no existing
   log for model invocation — report that invocation logging was not enabled and
   STOP. There is nothing to extract: logging has no backfill, so only calls made
   after it is enabled are ever captured. AWS has no default/fixed group name —
   the group is customer-created (the fixed `aws/bedrock/modelinvocations` STREAM
   is written inside whatever group the customer names). So do not invent or query
   a group name here. If the user wants data, they enable logging to a group of
   their choosing and generate traffic first; a later run then resolves it via
   step 1 or 2.

Only `bedrock-runtime` calls are logged (InvokeModel, InvokeModelWithResponseStream,
Converse, ConverseStream). Each record carries invocation metadata plus
`operation`, `modelId`, `input` (body + inputTokenCount) and `output` (body +
outputTokenCount); large/binary payloads are S3-only. The authoritative field
shape is the Bedrock docs' "Log entry format" section — keep field paths behind
the query's mapping, not hard-coded.

## SageMaker endpoint OpenTelemetry traces

The group is a **deterministic function of the endpoint name** — resolve it, do
not ask the user for a path. Spans are written as `<variant>/<instance-id>/traces`
STREAMS, either inside the endpoint's own group
`/aws/sagemaker/Endpoints/{endpoint_name}` or in its dedicated group
`/aws/sagemaker/Endpoints/{endpoint_name}/traces`:

```
# config constants
ENDPOINT_OTEL_LOG_GROUP = "/aws/sagemaker/Endpoints/{endpoint_name}"
ENDPOINT_OTEL_TRACES_GROUP = "/aws/sagemaker/Endpoints/{endpoint_name}/traces"
```

Probe with `aws logs describe-log-groups --log-group-name-prefix
<ENDPOINT_OTEL_LOG_GROUP> --region <r>`, which lists both names when they exist
(keep exact matches only), then on each `aws logs describe-log-streams --log-group-name <group> --order-by
LastEventTime --descending --query "logStreams[?ends_with(logStreamName,
'/traces')].[logStreamName,lastEventTimestamp]" --region <r>` (the CLI pages
through every stream): use the group whose newest `.../traces` stream was
written last, and run the extraction again for the other group when it also has
span streams inside the query window. If neither exists, or neither holds one,
there is nothing to extract — report that and stop. Whether the endpoint
captures traces at all is its `TracingConfig`, not a question these groups
answer.

> **Casing note (ties into the connector).** `Endpoints` is a mixed-case group
> name. On the Athena connector's **standard-SQL** path the group becomes a SQL
> database name, which the connector does not support uppercase for — a reason
> the **passthrough** query path is preferred (it passes the group as a string
> argument, not a database identifier). See `athena-cloudwatch-connector.md`.

> **Scope to the `.../traces` stream, not the whole group.** Both groups hold
> streams other than the OTel inference spans (the inference container's own
> console logs in `/aws/sagemaker/Endpoints/<name>`, and the `sm-eval-results`
> judge records covered below in either), so a query over
> `all_log_streams` or an unscoped `LOGGROUPNAMES` sweep returns non-trace rows.
> When extracting traces, scope to the `.../traces`-suffixed stream (the connector
> maps each LogStream to its own table — query that table directly, or add a
> `log_stream like '%/traces'` predicate on `all_log_streams`) rather than
> querying the whole group.

Endpoint OpenTelemetry spans can carry timestamps far from their ingest time, so a
last-24h window may return zero rows even when the group has data — widen the
window (and clamp its start to the group `creationTime`, below) rather than
concluding the group is empty. The specific reason to widen the **upper** bound:
on a span, `@timestamp` is the span's END time (it is emitted on completion), so a
window whose end brackets the request's START drops exactly the slow or errored
spans you most want — a 7-second call that started inside the window but finished
after it falls outside. Pad the window end past the slowest expected latency.

## SageMaker online-eval results

The group is a **deterministic function of the online-evaluation job name**:
`/aws/sagemaker/online-eval/<job>`. Resolve it directly — do not ask the user for
a path:

1. If the user named the group, use it.
2. Otherwise form `/aws/sagemaker/online-eval/<job>` from the job name and probe
   with `aws logs describe-log-groups --log-group-name-prefix
   /aws/sagemaker/online-eval/<job> --region <r>`; use it if it exists.
3. If no group matches, the job may not emit online-eval results (or the name is
   wrong) — check the endpoint's two groups above for an `sm-eval-results` STREAM
   instead (per-endpoint monitoring writes to either or both rather than to a
   standalone job group). Only if neither location
   matches: report that and stop; do not query a fabricated name.

These records are `sm_online_eval_result` rows (judge verdicts/scores), a
different record shape with its own selector — see
`athena-cloudwatch-connector.md` and `trace-schema-and-json-paths.md` (Rule 4).
Clamp the query window to the group `creationTime` as below.

## Bedrock AgentCore runtime OpenTelemetry spans

AgentCore runtime traces are OTel spans in CloudWatch, in one of **two layouts
that can both appear in a single account** — resolve by probing, do not assume one:

```
# config constant — layouts coexist; resolve in this order
AGENTCORE_SPAN_LOG_GROUP_PATTERNS = [
    "/aws/bedrock-agentcore/runtimes/{agent_id}-{endpoint}",  # unified: spans in the `spans` stream, content on the span
    "aws/spans",                                              # split: shared spans group; content in a separate `otel-rt-logs` record, rejoined by traceId+spanId
]
```

The unified pattern needs the runtime's `{agent_id}` and `{endpoint}`: take them
from the user, or list them with `aws bedrock-agentcore-control list-agent-runtimes
--region <r>` (then the runtime's endpoints) and confirm which agent before
probing. Resolve by probing `aws logs describe-log-groups --log-group-name-prefix
<candidate> --region <r>` in order and keeping the first that exists; prefer the
unified per-runtime group when both are present (its spans carry the conversation
content directly). In the split layout the `spans` records carry span structure
but the message bodies live in the companion `otel-rt-logs` records: pull both
record kinds from the group and join each `spans` record to its `otel-rt-logs`
record on matching `traceId`+`spanId`, so the content reattaches to the span that
produced it. The shared `aws/spans` group holds spans from EVERY runtime in the
account/region, so the scope/name selector alone would pull other agents' spans —
in the split layout you MUST also scope to the target runtime (filter on the
agent/runtime id present on the span, confirmed on the Rule 5 1-row probe). The
per-runtime unified group needs no such filter. If neither group exists, the agent may not emit traces. Report
that and stop; do not query a fabricated name.

**Transaction Search.** Before querying AgentCore spans, run the Transaction Search Check in
`../../../endpoint_tracing_prerequisites.md`: the per-runtime group exists from runtime logs even when Transaction
Search is off. If it is not on, hand the user what that file says, then report and stop.

The split `aws/spans` layout and its `otel-rt-logs` join are derived from the
AgentCore record schema — verify them on a 1-row probe before relying on the join.
Clamp the query window to the group `creationTime` as below.

## Query window — clamp to the group age

A Logs Insights window that ends before the log group's `creationTime` is
rejected (`MalformedQueryException`); a start before it is accepted. Before
querying, call `aws logs describe-log-groups --log-group-name-prefix <resolved
group> --region <r>` to read `creationTime`, make sure the window end is after
it, and cap the window start to it, since nothing was written before it. The OpenTelemetry inference-trace,
online-eval, and AgentCore paths already made this call to resolve/probe their
group (so
`creationTime` is already in hand); the Bedrock path (resolved via
`get-model-invocation-logging-configuration` or user input) must make it here,
since it has not called `describe-log-groups` yet. The clamp applies to the
passthrough `system.query` STARTTIME and to any direct `logs:StartQuery`.

<!-- markdownlint-disable-file MD028 -->
