From 0e7c953615c9acd93e2e85a8d50005a09ed47840 Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Mon, 30 Nov 2026 11:48:21 -0800 Subject: [PATCH 1/2] feat(box): Send the metrics of the agent in a box to CloudWatch on AgentCore Runtime ## Problem On AgentCore Runtime, an agent in a box sends no metric to CloudWatch. The @box/agentcore pack sets `OTEL_METRICS_EXPORTER` to `none`, and no default target of the Runtime profile receives metrics. An agent that is not in a box sends these metrics by default: the number of tokens, the time of each model call, and the metrics of the Strands event loop. Thus an agent that moves into a box does not send them, and nothing tells the user. ## Solution - The @box/agentcore pack sets `OTEL_METRICS_EXPORTER` to `otlp`. The agent then sends its metrics to the receiver of box, because box sets `OTEL_EXPORTER_OTLP_ENDPOINT`. - With OTEL on, the `additions` rule adds `[telemetry.agentcore_metrics]` to the Runtime profile. It is an `otlp` target with `accepts = ["metrics"]` and `include = ["metrics"]`. - Its destination is `https://monitoring.${{ inputs.aws.region }}`, then the DNS suffix of the partition of the region of `agentcore build`. Box adds `/v1/metrics`, so the destination has no path. - A bare `aws://` signs the target with the execution role. The name is `agentcore_metrics_default` when a target has the name `agentcore_metrics`. - The rule adds no target with `enableOtel` set to `false`, or with `DISABLE_ADOT_OBSERVABILITY` set to `"true"`. It also adds no target when a target of the profile sends to the CloudWatch metrics endpoint. - `CloudWatchTelemetry` gets the value `cloudwatch_metrics` for its `kind`. `defaultMetricsTelemetry` gives the default target to the network model. - `boxTelemetryPolicy` then grants `cloudwatch:PutMetricData` on `"*"` in `agentcore/box-telemetry-policy-.json`. `PutMetricData` has no resource type. - The comment at the top of the Runtime profile names the target. With OTEL on, the notice of `agentcore create` and `agentcore add runtime` names the metrics and their cost. `docs/box-local-testing.md` gives the rules. - No change in the CLI is necessary for a PRIVATE_VPC runtime. With OTEL on, the private VPC of the L3 adds the `monitoring` interface endpoint and its DNS name. The metrics go to CloudWatch as OpenTelemetry metrics, which PromQL reads in Query Studio. They do not go to the `bedrock-agentcore` namespace. That namespace gets the EMF records that the ADOT SDK writes for an agent that is not in a box. An EMF path is possible only with a change in box. Without that change, the agent can write records into the log group that holds the records of box. ## Tests - `additions.test.ts`: the target for CodeZip and for a container. No target with OTEL off or with `DISABLE_ADOT_OBSERVABILITY`. The DNS suffix of four partitions, China too. - `additions.test.ts`: no default target with a user target to the metrics endpoint, for four destinations. The default target with three other destinations. The name clash, the comment, the notice, and the value that the pack sets. - `boxNetworkSource.test.ts`: the grant with the X-Ray grant, and no grant with OTEL off. The user target to the metrics endpoint. The default target with a Langfuse target. PRIVATE_VPC. Two runtimes, one with OTEL off. - `boxTelemetry.test.ts`: the statement, its position, and no statement without the target. - `manager.boxNetwork.test.ts`: `agentcore build` writes the target and the grant. A subsequent `agentcore build` with `enableOtel` set to `false` removes the target, the policy file, and its entry. - Three mutations caused errors in the tests, and then each mutation was removed: no OTEL check (161 tests with an error), no check for a user target (5), and no grant (5). - `bun test`, `tsc`, `oxlint`, and `prettier` show no error. - A local run of box 0.3.2 sent the metrics of an agent to the CloudWatch metrics endpoint, with a SigV4 signature for the service `monitoring`. This test did not read the metrics from CloudWatch. That check and the live tests on AgentCore Runtime are not completed. --- docs/box-local-testing.md | 30 ++- src/core/project/boxNetwork/network.ts | 20 +- src/core/project/boxNetwork/telemetry.ts | 8 + src/core/project/boxNetworkSource.test.ts | 129 ++++++++++- src/core/project/boxTelemetry.test.ts | 29 +++ src/core/project/boxTelemetry.ts | 14 +- src/core/project/manager.box.test.ts | 2 +- src/core/project/manager.boxNetwork.test.ts | 37 +++- src/core/project/manager.test.ts | 6 +- src/core/project/manager.tsx | 7 +- .../runtimeProfile/rules/additions.test.ts | 207 +++++++++++++++++- .../project/runtimeProfile/rules/additions.ts | 97 +++++++- src/core/project/templates/boxProfile.test.ts | 2 +- src/core/project/templates/boxProfile.ts | 12 +- 14 files changed, 559 insertions(+), 41 deletions(-) diff --git a/docs/box-local-testing.md b/docs/box-local-testing.md index b2349acd2..3d3d858dc 100644 --- a/docs/box-local-testing.md +++ b/docs/box-local-testing.md @@ -313,9 +313,9 @@ profile that names a pack `box/` fails: box refuses it and names the `@box `OTEL_RESOURCE_ATTRIBUTES`. Where a variable is not set, for example in a local run, the agent gets the default, which is the value that the Runtime sets: `aws_distro`, `aws_configurator`, `true`, `/ping`, and `service.name=`. The - pack sets fixed values for `OTEL_TRACES_EXPORTER` and `OTEL_LOGS_EXPORTER` (`otlp`), and for - `OTEL_METRICS_EXPORTER` (`none`), because the receiver of box takes only spans and logs. When - your `[agent.env]` sets one of these variables, box uses your value. The pack sets no + pack sets fixed values for `OTEL_TRACES_EXPORTER`, `OTEL_LOGS_EXPORTER`, and + `OTEL_METRICS_EXPORTER` (`otlp`), so the agent sends its spans, logs, and metrics to the receiver + of box. When your `[agent.env]` sets one of these variables, box uses your value. The pack sets no `OTEL_EXPORTER_OTLP_*` variable, because box sets each one; - each other gateway of the project gets `[mcp.]`, to the host that `@box/agentcore` reads from `AGENTCORE_GATEWAY__HOST`, through its `egress-gateway-` target. The agent @@ -353,6 +353,21 @@ profile that names a pack `box/` fails: box refuses it and names the `@box send no spans, set `instrumentation.enableOtel` to `false` in `agentcore.json`. When `enableOtel` is on and the agent does not start with `opentelemetry-instrument`, build gives a warning. + **The default metrics target.** With `enableOtel` on and no target that sends to the CloudWatch + metrics endpoint, the Runtime profile gets `[telemetry.agentcore_metrics]`, or + `[telemetry.agentcore_metrics_default]` when a target has the name `agentcore_metrics`. It is an + `otlp` target with `accepts = ["metrics"]`: box sends the metrics of the agent, such as token use, + model call time, and the Strands event loop, to + `https://monitoring../v1/metrics`, and signs them with the + execution role. Box adds `/v1/metrics` itself. CloudWatch keeps them as OpenTelemetry metrics, which + you query with PromQL in CloudWatch Query Studio. They are not in the `bedrock-agentcore` + namespace, where an agent outside a box writes its metrics as EMF records. CloudWatch charges for + the metrics. Build gives the execution role `cloudwatch:PutMetricData` in + `agentcore/box-telemetry-policy-.json`. A PRIVATE_VPC runtime reaches the endpoint + through the `monitoring` interface endpoint of its VPC. To send no metrics, set + `instrumentation.enableOtel` to `false`, or set `DISABLE_ADOT_OBSERVABILITY` to `"true"`. A + failed send shows no error unless `STRANDS_BOX_TELEMETRY_DEBUG` is `"1"`. + Build stops, and names the key and its line, for a value that cannot work on the Runtime: a required grant or a command path in the project outside the code folder, in the venv, or in a home folder (`${{ home }}`, `~`, `/Users`, `/home`); a CodeZip program that `PATH` finds, such as @@ -576,7 +591,9 @@ With `instrumentation.enableOtel` on, box also sends the spans of the agent and X-Ray, through the target `[telemetry.agentcore_traces]`. Build gives the execution role the X-Ray grant for it. "The default X-Ray target" in step 4 gives the rules. With box 0.3.2 or later, the spans go to the stream `spans` of the runtime's own log group. With an older box, CloudWatch -Transaction Search keeps them in the log group `aws/spans`. +Transaction Search keeps them in the log group `aws/spans`. Box also sends the metrics of the agent +to the CloudWatch metrics endpoint, through the target `[telemetry.agentcore_metrics]`. "The default +metrics target" in step 4 gives the rules. The CLI and the L3 constructs make no log group for box. The role that the CDK makes for the runtime can write to the log group of the Runtime, thus build adds no grant for it. A runtime that names an @@ -647,8 +664,9 @@ To replace the default target with a log group that you make: AgentCore Runtime, box signs this target with the execution role. Build also writes one policy file for each box runtime, `agentcore/box-telemetry-policy-.json`, here `box-telemetry-policy-agent.json`. It adds the file to the `additionalPolicies` of that runtime. - The file gives the role `logs:PutLogEvents` on the stream of each `cloudwatch_logs` target, and - `xray:PutSpans` and `xray:PutTraceSegments` for a `cloudwatch_traces` target. + The file gives the role `logs:PutLogEvents` on the stream of each `cloudwatch_logs` target, + `xray:PutSpans` and `xray:PutTraceSegments` for a `cloudwatch_traces` target, and + `cloudwatch:PutMetricData` for the default metrics target. 4. Invoke the agent, then read the records: diff --git a/src/core/project/boxNetwork/network.ts b/src/core/project/boxNetwork/network.ts index 5968f8613..59edc6c2c 100644 --- a/src/core/project/boxNetwork/network.ts +++ b/src/core/project/boxNetwork/network.ts @@ -37,7 +37,11 @@ import { describeEntry, describeRule, ruleOrigin } from "./places"; import { placeOf, type ParsedPolicy } from "./policyParser"; import { runtimeProfileContext } from "../runtimeProfile/context"; import { deriveRuntimeProfile } from "../runtimeProfile/derive"; -import { defaultTracesTelemetry, runtimeProfileHeader } from "../runtimeProfile/rules/additions"; +import { + defaultMetricsTelemetry, + defaultTracesTelemetry, + runtimeProfileHeader, +} from "../runtimeProfile/rules/additions"; import type { TomlTable } from "../runtimeProfile/types"; import type { ParsedProfile } from "./profileParser"; import { withDeployRegion, type CloudWatchTelemetry, type ThirdPartyTelemetry } from "./telemetry"; @@ -149,7 +153,8 @@ export interface BoxNetwork { readonly policyFiles: readonly string[]; /** * The CloudWatch targets of the profile's `[telemetry]`, then the default X-Ray target of - * {@link runtimeProfile} (`DEFAULT_TRACES_TARGET`); absent means none. + * {@link runtimeProfile} (`DEFAULT_TRACES_TARGET`), then its default CloudWatch metrics target + * (`runtimeMetricsTarget`); absent means none. */ readonly telemetry?: readonly CloudWatchTelemetry[]; /** @@ -278,11 +283,14 @@ export function buildBoxNetwork( failures.push( ...(derived?.problems ?? []).map(({ code, reason, place }) => ({ code, reason, place })), ); - const defaultTraces = derived ? defaultTracesTelemetry(derived.profile, project.region) : []; + const defaults = derived + ? [ + ...defaultTracesTelemetry(derived.profile, project.region), + ...defaultMetricsTelemetry(derived.profile, project.region), + ] + : []; const sent = - telemetry || defaultTraces.length > 0 - ? [...(telemetry?.telemetry ?? []), ...defaultTraces] - : undefined; + telemetry || defaults.length > 0 ? [...(telemetry?.telemetry ?? []), ...defaults] : undefined; return { runtime: project.runtime.name, gateway: project.gateway, diff --git a/src/core/project/boxNetwork/telemetry.ts b/src/core/project/boxNetwork/telemetry.ts index e913ec0ed..21f353a4a 100644 --- a/src/core/project/boxNetwork/telemetry.ts +++ b/src/core/project/boxNetwork/telemetry.ts @@ -35,6 +35,14 @@ type CloudWatchTarget = { /** Spans, to X-Ray's OTLP endpoint. */ readonly kind: "cloudwatch_traces"; } + | { + /** + * The agent's metrics, to the CloudWatch metrics OTLP endpoint: the default metrics target of + * the AgentCore Runtime profile, an `otlp` target that box signs with a bare `aws://`. A box + * profile has no such kind, so only build gives it. + */ + readonly kind: "cloudwatch_metrics"; + } ); /** The longest log group or log stream name CloudWatch Logs accepts, as Box checks it. */ diff --git a/src/core/project/boxNetworkSource.test.ts b/src/core/project/boxNetworkSource.test.ts index 03553b29f..1eae48a62 100644 --- a/src/core/project/boxNetworkSource.test.ts +++ b/src/core/project/boxNetworkSource.test.ts @@ -650,6 +650,25 @@ describe("the default X-Ray target of a runtime with OTEL on", () => { Action: ["xray:PutSpans", "xray:PutTraceSegments"], Resource: "*", }; + const METRICS = { + name: "agentcore_metrics", + kind: "cloudwatch_metrics" as const, + region: "us-west-2", + include: ["metrics"], + }; + const PUT_METRIC_DATA = { + Sid: "BoxTelemetryToCloudWatchMetrics", + Effect: "Allow", + Action: ["cloudwatch:PutMetricData"], + Resource: "*", + }; + const METRICS_TARGET = { + kind: "otlp", + destination: "https://monitoring.${{ inputs.aws.region }}.amazonaws.com", + accepts: ["metrics"], + include: ["metrics"], + secret: { ref: "aws://" }, + }; /** The telemetry policy file that build writes for the model `network`. */ const policyOf = (network: NonNullable>[number]>) => @@ -660,14 +679,14 @@ describe("the default X-Ray target of a runtime with OTEL on", () => { envLocal: {}, }).files ?? []; - test("gets the grant of the execution role for X-Ray, and with OTEL off gets none", async () => { + test("gets the grants of the execution role for X-Ray and for CloudWatch metrics, and with OTEL off gets none", async () => { const root = await project([]); const box = new FakeBoxProfileResolver(boxShowOf({ egress: API_ROUTE })); const [on] = await readBoxNetworks(OTEL_SPEC, root, box); const [off] = await readBoxNetworks(SPEC, root, box); - expect(on?.telemetry).toEqual([TRACES]); + expect(on?.telemetry).toEqual([TRACES, METRICS]); const telemetry = on?.runtimeProfile?.telemetry as Record; expect(telemetry.agentcore_traces).toEqual({ kind: "cloudwatch_traces", @@ -679,12 +698,14 @@ describe("the default X-Ray target of a runtime with OTEL on", () => { log_stream: "${{ inputs.runtime.traces_log_stream }}", }), }); + expect(telemetry.agentcore_metrics).toEqual(METRICS_TARGET); const [file] = policyOf(on!); expect(JSON.parse((file as { text: string }).text)).toEqual({ Version: "2012-10-17", - Statement: [X_RAY], + Statement: [X_RAY, PUT_METRIC_DATA], }); expect(off?.telemetry).toBeUndefined(); + expect(off?.runtimeProfile?.telemetry).not.toHaveProperty("agentcore_metrics"); expect(policyOf(off!)).toEqual([{ path: boxTelemetryPolicyFile("agent"), remove: true }]); }); @@ -721,10 +742,110 @@ describe("the default X-Ray target of a runtime with OTEL on", () => { expect(network?.telemetry).toEqual([ { name: "mine", kind: "cloudwatch_traces", region: "eu-west-1" }, + METRICS, ]); expect(network?.runtimeProfile?.telemetry).not.toHaveProperty("agentcore_traces"); const [file] = policyOf(network!); - expect(JSON.parse((file as { text: string }).text).Statement).toEqual([X_RAY]); + expect(JSON.parse((file as { text: string }).text).Statement).toEqual([X_RAY, PUT_METRIC_DATA]); + }); + + test("adds no default metrics target, and no metrics grant, when the profile has its own target of the CloudWatch metrics endpoint", async () => { + const root = await project([]); + const shown = boxShowOf({ egress: API_ROUTE }); + // No key: a CodeZip runtime carries a third-party target only without one. + const own = { + kind: "otlp", + destination: "https://monitoring.eu-west-1.amazonaws.com", + accepts: ["metrics"], + }; + const box = new FakeBoxProfileResolver({ + ...shown, + boxToml: { ...shown.boxToml, telemetry: { mine: own } }, + }); + + const [network] = await readBoxNetworks(OTEL_SPEC, root, box); + + expect(network?.thirdPartyTelemetry?.map(({ name }) => name)).toEqual(["mine"]); + expect(network?.runtimeProfile?.telemetry).not.toHaveProperty("agentcore_metrics"); + expect(network?.telemetry).toEqual([TRACES]); + const [file] = policyOf(network!); + expect(JSON.parse((file as { text: string }).text).Statement).not.toContainEqual( + PUT_METRIC_DATA, + ); + }); + + test("adds the default metrics target beside a third-party target that sends spans", async () => { + const root = await project([]); + const shown = boxShowOf({ egress: API_ROUTE }); + const langfuse = { + kind: "langfuse", + destination: "https://cloud.langfuse.com", + secret: { ref: "env://LANGFUSE_AUTH" }, + }; + const box = new FakeBoxProfileResolver({ + ...shown, + boxToml: { ...shown.boxToml, telemetry: { langfuse } }, + }); + + const [network] = await readBoxNetworks(OTEL_SPEC, root, box); + + expect(network?.runtimeProfile?.telemetry).toHaveProperty("agentcore_metrics", METRICS_TARGET); + expect(network?.telemetry).toEqual([TRACES, METRICS]); + }); + + test("gives a PRIVATE_VPC runtime the default metrics target and its grant, as for a public runtime", async () => { + const root = await project([]); + const box = new FakeBoxProfileResolver(boxShowOf({ egress: API_ROUTE })); + const spec = { + ...OTEL_SPEC, + runtimes: [{ ...OTEL_SPEC.runtimes[0]!, containment: "PRIVATE_VPC" }], + } as unknown as ProjectSpec; + + const [network] = await readBoxNetworks(spec, root, box); + + expect(network?.runtimeProfile?.telemetry).toHaveProperty("agentcore_metrics", METRICS_TARGET); + expect(network?.telemetry).toEqual([TRACES, METRICS]); + }); + + test("gives each runtime of two the grant of its own metrics target, and none with OTEL off", async () => { + const root = await project([]); + await writeProfile(root, "second", []); + await writeFile(join(root, ".box", "second", "local", "policy.dw"), "// no rule\n"); + const box = new FakeBoxProfileResolver(boxShowOf({ egress: API_ROUTE })); + const spec = { + ...OTEL_SPEC, + runtimes: [ + OTEL_SPEC.runtimes[0]!, + { + ...OTEL_SPEC.runtimes[0]!, + name: "second", + codeLocation: "app/second", + instrumentation: { enableOtel: false }, + }, + ], + agentCoreGateways: [ + boxGatewaySpec("agent", "strands-box"), + boxGatewaySpec("second", "strands-box"), + ], + } as unknown as ProjectSpec; + + const networks = await readBoxNetworks(spec, root, box); + const byName = new Map(networks.map((network) => [network.runtime, network])); + const files = telemetryPolicyWriter.edits(networks, { + spec, + projectRoot: root, + env: {}, + envLocal: {}, + }).files; + + expect(byName.get("agent")?.telemetry).toEqual([TRACES, METRICS]); + expect(byName.get("second")?.telemetry).toBeUndefined(); + expect(byName.get("second")?.runtimeProfile?.telemetry).not.toHaveProperty("agentcore_metrics"); + const agentFile = files?.find(({ path }) => path === boxTelemetryPolicyFile("agent")); + expect(JSON.parse((agentFile as { text: string }).text).Statement).toContainEqual( + PUT_METRIC_DATA, + ); + expect(files).toContainEqual({ path: boxTelemetryPolicyFile("second"), remove: true }); }); }); diff --git a/src/core/project/boxTelemetry.test.ts b/src/core/project/boxTelemetry.test.ts index 20d15f480..c2b0e6ea9 100644 --- a/src/core/project/boxTelemetry.test.ts +++ b/src/core/project/boxTelemetry.test.ts @@ -33,6 +33,18 @@ const TRACES_STATEMENT = { Action: ["xray:PutSpans", "xray:PutTraceSegments"], Resource: "*", }; +const METRICS: CloudWatchTelemetry = { + name: "agentcore_metrics", + kind: "cloudwatch_metrics", + region: "us-west-2", + include: ["metrics"], +}; +const METRICS_STATEMENT = { + Sid: "BoxTelemetryToCloudWatchMetrics", + Effect: "Allow", + Action: ["cloudwatch:PutMetricData"], + Resource: "*", +}; describe("boxTelemetryPolicy", () => { test("lets a cloudwatch_logs target put log events in its own group and stream only", () => { @@ -56,6 +68,23 @@ describe("boxTelemetryPolicy", () => { }); }); + test("lets the default metrics target put metric data, which has no resource type", () => { + expect(boxTelemetryPolicy([METRICS])).toEqual({ + Version: "2012-10-17", + Statement: [METRICS_STATEMENT], + }); + }); + + test("gives the metrics statement once, after the logs and the X-Ray statements", () => { + expect( + boxTelemetryPolicy([METRICS, LOGS, { ...METRICS, name: "second" }, TRACES])?.Statement, + ).toEqual([LOGS_STATEMENT, TRACES_STATEMENT, METRICS_STATEMENT]); + }); + + test("gives no metrics statement without the metrics target", () => { + expect(boxTelemetryPolicy([LOGS, TRACES])?.Statement).not.toContainEqual(METRICS_STATEMENT); + }); + test("lists each log stream once, with the partition of its region", () => { const china = { ...LOGS, region: "cn-north-1" }; const govCloud = { ...LOGS, region: "us-gov-west-1", logStream: "other" }; diff --git a/src/core/project/boxTelemetry.ts b/src/core/project/boxTelemetry.ts index dd721319c..a32f12f55 100644 --- a/src/core/project/boxTelemetry.ts +++ b/src/core/project/boxTelemetry.ts @@ -18,7 +18,8 @@ export function boxTelemetryPolicyFile(runtimeName: string): string { * The IAM policy document for {@link boxTelemetryPolicyFile}, or undefined when no target sends * to CloudWatch. Build has no account, so each log stream ARN matches any account. CloudWatch Logs * takes OTLP records only into a group and a stream that exist. X-Ray's OTLP traces endpoint is - * authorized as `PutTraceSegments`, beside `PutSpans`, and neither has a resource type. + * authorized as `PutTraceSegments`, beside `PutSpans`, and neither has a resource type. The + * CloudWatch metrics OTLP endpoint is authorized as `PutMetricData`, which has no resource type. */ export function boxTelemetryPolicy( telemetry: readonly CloudWatchTelemetry[], @@ -36,6 +37,7 @@ export function boxTelemetryPolicy( ), ]; const traces = telemetry.some(({ kind }) => kind === "cloudwatch_traces"); + const metrics = telemetry.some(({ kind }) => kind === "cloudwatch_metrics"); const statements = [ ...(streams.length > 0 ? [ @@ -57,6 +59,16 @@ export function boxTelemetryPolicy( }, ] : []), + ...(metrics + ? [ + { + Sid: "BoxTelemetryToCloudWatchMetrics", + Effect: "Allow", + Action: ["cloudwatch:PutMetricData"], + Resource: "*", + }, + ] + : []), ]; return statements.length > 0 ? { Version: "2012-10-17", Statement: statements } : undefined; } diff --git a/src/core/project/manager.box.test.ts b/src/core/project/manager.box.test.ts index ac42cd299..b96e4c9ac 100644 --- a/src/core/project/manager.box.test.ts +++ b/src/core/project/manager.box.test.ts @@ -607,7 +607,7 @@ describe("gateway targets in a Box project", () => { // The notice of the default log target comes after agentcore.json is written. const notice = { type: "warning", - message: defaultLogTargetNotice("search", ".box/search/local/profile.toml"), + message: defaultLogTargetNotice("search", ".box/search/local/profile.toml", true), }; const written = events.findIndex((event) => (event as { message?: string }).message?.startsWith("updating project spec file"), diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 85c6db47f..e5218a890 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -1666,6 +1666,12 @@ describe("build with OTEL on, as create writes a box runtime", () => { Action: ["xray:PutSpans", "xray:PutTraceSegments"], Resource: "*", }; + const PUT_METRIC_DATA = { + Sid: "BoxTelemetryToCloudWatchMetrics", + Effect: "Allow", + Action: ["cloudwatch:PutMetricData"], + Resource: "*", + }; // The pinned box names the log group and stream of its spans (strands-agents/box#629, 0.3.2). const DEFAULT_TRACES = { kind: "cloudwatch_traces", @@ -1696,7 +1702,7 @@ describe("build with OTEL on, as create writes a box runtime", () => { }, ); - test("starts the agent under opentelemetry-instrument, sets up its ADOT SDK, and sends its spans to X-Ray with the grant", async () => { + test("starts the agent under opentelemetry-instrument, sets up its ADOT SDK, and sends its spans to X-Ray and its metrics to CloudWatch with the grants", async () => { const { manager, root } = await strandsProject(); expect(JSON.parse(await text(root, SPEC)).runtimes[0].instrumentation).toBeUndefined(); @@ -1713,9 +1719,20 @@ describe("build with OTEL on, as create writes a box runtime", () => { expect(pack.agent.env).toMatchObject({ OTEL_PYTHON_DISTRO: "${{ inputs.otel.python_distro }}", OTEL_TRACES_EXPORTER: "otlp", + OTEL_METRICS_EXPORTER: "otlp", OTEL_RESOURCE_ATTRIBUTES: "${{ inputs.runtime.resource_attributes }}", }); - expect(JSON.parse(await text(root, TELEMETRY_POLICY)).Statement).toEqual([X_RAY]); + expect((profile.telemetry as Record).agentcore_metrics).toEqual({ + kind: "otlp", + destination: "https://monitoring.${{ inputs.aws.region }}.amazonaws.com", + accepts: ["metrics"], + include: ["metrics"], + secret: { ref: "aws://" }, + }); + expect(JSON.parse(await text(root, TELEMETRY_POLICY)).Statement).toEqual([ + X_RAY, + PUT_METRIC_DATA, + ]); expect(JSON.parse(await text(root, SPEC)).runtimes[0].additionalPolicies).toEqual([ "../../agentcore/box-telemetry-policy-agent_python_strands.json", ]); @@ -1734,6 +1751,7 @@ describe("build with OTEL on, as create writes a box runtime", () => { const profile = await runtimeProfile(root); expect(JSON.stringify(profile.agent)).not.toContain("opentelemetry-instrument"); expect(profile.telemetry).not.toHaveProperty("agentcore_traces"); + expect(profile.telemetry).not.toHaveProperty("agentcore_metrics"); const pack = parse(await text(root, PACK)) as { agent: { env: Record } }; expect(Object.keys(pack.agent.env)).toEqual([ "AWS_EXECUTION_ENV", @@ -1743,6 +1761,21 @@ describe("build with OTEL on, as create writes a box runtime", () => { expect(existsSync(path(root, TELEMETRY_POLICY))).toBe(false); }); + test("removes the metrics target and its grant on the next build when enableOtel turns false", async () => { + const { manager, root } = await strandsProject(); + await build(manager, root); + expect(JSON.parse(await text(root, TELEMETRY_POLICY)).Statement).toContainEqual( + PUT_METRIC_DATA, + ); + + await setOtel(root, false); + await build(manager, root); + + expect((await runtimeProfile(root)).telemetry).not.toHaveProperty("agentcore_metrics"); + expect(existsSync(path(root, TELEMETRY_POLICY))).toBe(false); + expect(JSON.parse(await text(root, SPEC)).runtimes[0].additionalPolicies).toBeUndefined(); + }); + test("changes nothing on a second build", async () => { const { manager, root, counter } = await strandsProject(); await build(manager, root); diff --git a/src/core/project/manager.test.ts b/src/core/project/manager.test.ts index 558972bb9..8915c8ba4 100644 --- a/src/core/project/manager.test.ts +++ b/src/core/project/manager.test.ts @@ -863,7 +863,11 @@ describe("FsProjectManager.create box profile", () => { ); expect(events).toContainEqual({ type: "warning", - message: defaultLogTargetNotice(AGENT_PYTHON_STRANDS_BOX.runtimeName, BOX_PROFILE_FILE), + message: defaultLogTargetNotice( + AGENT_PYTHON_STRANDS_BOX.runtimeName, + BOX_PROFILE_FILE, + true, + ), }); }, ); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 3f2a29c29..065d7b2ce 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -89,6 +89,7 @@ import { boxUvSyncEnv, hasBoxProfile, observabilityOff, + otelOn, renderAwsMetadataPolicy, renderBoxProfile, runsInBox, @@ -2679,7 +2680,11 @@ function defaultLogTargetNotices( .filter((runtime) => runsInBox(isBoxProject(spec), runtime) && !observabilityOff(runtime)) .map((runtime) => ({ type: "warning", - message: defaultLogTargetNotice(runtime.name, boxLocalProfileFile(runtime.name)), + message: defaultLogTargetNotice( + runtime.name, + boxLocalProfileFile(runtime.name), + otelOn(runtime), + ), })); } diff --git a/src/core/project/runtimeProfile/rules/additions.test.ts b/src/core/project/runtimeProfile/rules/additions.test.ts index e64b44827..b955d9ed7 100644 --- a/src/core/project/runtimeProfile/rules/additions.test.ts +++ b/src/core/project/runtimeProfile/rules/additions.test.ts @@ -38,8 +38,11 @@ import { agentStartsUnderOtel, apply, DEFAULT_TELEMETRY_TARGET, + defaultLogTargetNotice, + defaultMetricsTelemetry, defaultTracesTelemetry, MEMORY_ROUTE, + runtimeMetricsTarget, runtimeProfileHeader, runtimeTracesTarget, } from "./additions"; @@ -226,6 +229,18 @@ const DEFAULT_TRACES = { log_stream: "${{ inputs.runtime.traces_log_stream }}", }; +/** + * The default CloudWatch metrics target of a Runtime profile with OTEL on: the agent's own metrics, + * to the metrics endpoint of the Runtime's region, in the partition of {@link BUILD_REGION}. + */ +const DEFAULT_METRICS = { + kind: "otlp", + destination: "https://monitoring.${{ inputs.aws.region }}.amazonaws.com", + accepts: ["metrics"], + include: ["metrics"], + secret: { ref: "aws://" }, +}; + /** The words that start the agent under opentelemetry-instrument on the Runtime. */ const OTEL_START: Record = { CodeZip: ["${{ inputs.python.path }}", "${{ inputs.code.dir }}/bin/opentelemetry-instrument"], @@ -257,8 +272,8 @@ function withApiKeySignIn(profile: TomlTable): TomlTable { /** * `profile`, a Runtime profile with OTEL off, as OTEL on gives it: the agent starts under - * opentelemetry-instrument, and the default X-Ray target comes last when no target is - * `cloudwatch_traces`. Nothing else changes. + * opentelemetry-instrument, the default X-Ray target comes next when no target is + * `cloudwatch_traces`, and the default metrics target comes last. Nothing else changes. */ function withOtel(profile: TomlTable, build: Build): TomlTable { const result = structuredClone(profile); @@ -268,6 +283,7 @@ function withOtel(profile: TomlTable, build: Build): TomlTable { if (!Object.values(telemetry).some(({ kind }) => kind === "cloudwatch_traces")) { telemetry.agentcore_traces = DEFAULT_TRACES; } + telemetry.agentcore_metrics = DEFAULT_METRICS; return result; } @@ -1677,6 +1693,7 @@ describe("the additions rule", () => { expect(tableOf(apply({}, contextOf(otelRuntime(build))).table)).toEqual({ agentcore: DEFAULT_TARGET, agentcore_traces: DEFAULT_TRACES, + agentcore_metrics: DEFAULT_METRICS, }); expect(tableOf(apply({}, contextOf(runtimeOf(build))).table)).toEqual({ agentcore: DEFAULT_TARGET, @@ -1759,7 +1776,7 @@ describe("the additions rule", () => { apply(local, contextOf(OTEL_CODEZIP, { telemetry: acceptedTelemetry(local) })).table, ), ), - ).toEqual(["logs", "agentcore_traces"]); + ).toEqual(["logs", "agentcore_traces", "agentcore_metrics"]); }); test("adds no default X-Ray target when the profile has its own cloudwatch_traces target", () => { @@ -1772,6 +1789,7 @@ describe("the additions rule", () => { ).toEqual({ "x-ray": { kind: "cloudwatch_traces", region: BUILD_REGION, secret: { ref: "aws://" } }, agentcore: DEFAULT_TARGET, + agentcore_metrics: DEFAULT_METRICS, }); }); @@ -1781,7 +1799,7 @@ describe("the additions rule", () => { ]; expect(Object.keys(tableOf(apply({}, contextOf(OTEL_CODEZIP, { telemetry })).table))).toEqual( - ["pack-traces", "agentcore"], + ["pack-traces", "agentcore", "agentcore_metrics"], ); }); @@ -1824,7 +1842,11 @@ describe("the additions rule", () => { apply(local, contextOf(OTEL_CODEZIP, { telemetry: acceptedTelemetry(local) })).table, ); - expect(Object.keys(telemetry)).toEqual(["agentcore_traces", "agentcore_traces_default"]); + expect(Object.keys(telemetry)).toEqual([ + "agentcore_traces", + "agentcore_traces_default", + "agentcore_metrics", + ]); expect(telemetry.agentcore_traces_default).toEqual(DEFAULT_TRACES); }); @@ -1841,14 +1863,14 @@ describe("the additions rule", () => { const routed = contextOf(OTEL_CODEZIP); const plain = contextOf(OTEL_CODEZIP, { boxVersion: "0.3.0" }); - expect(runtimeProfileHeader(routed, apply({}, routed).table).at(-1)).toBe( + expect(runtimeProfileHeader(routed, apply({}, routed).table).at(-2)).toBe( "[telemetry.agentcore_traces] is the default X-Ray target: the agent's spans and box's " + "own, in the Runtime's region, to the runtime's own log group and log stream, which " + "box reads from OTEL_EXPORTER_OTLP_TRACES_HEADERS when the run starts. Add a " + `cloudwatch_traces target to ${PROFILE_FILE} to use another, or set ` + "instrumentation.enableOtel to false in agentcore.json to send none.", ); - expect(runtimeProfileHeader(plain, apply({}, plain).table).at(-1)).toBe( + expect(runtimeProfileHeader(plain, apply({}, plain).table).at(-2)).toBe( "[telemetry.agentcore_traces] is the default X-Ray target: the agent's spans and box's " + `own, in the Runtime's region. Add a cloudwatch_traces target to ${PROFILE_FILE} to ` + "use another, or set instrumentation.enableOtel to false in agentcore.json to send none.", @@ -1869,6 +1891,177 @@ describe("the additions rule", () => { expect(defaultTracesTelemetry(apply({}, contextOf(CODEZIP)).table, BUILD_REGION)).toEqual([]); }); + describe("the default CloudWatch metrics target", () => { + /** A third-party `otlp` target that box resolves, with `destination`, which sends metrics. */ + const userMetrics = (destination: string): ThirdPartyTelemetry => ({ + name: "mine", + kind: "otlp", + keys: [ + ["destination", destination], + ["accepts", ["metrics"]], + ], + }); + + test.each(BUILDS)( + "sends the agent's metrics to the CloudWatch metrics endpoint of the Runtime's region, signed with the execution role (%s)", + (build) => { + const { table } = apply({}, contextOf(otelRuntime(build))); + + expect(tableOf(table).agentcore_metrics).toEqual(DEFAULT_METRICS); + expect(runtimeMetricsTarget(BUILD_REGION)).toEqual(DEFAULT_METRICS); + expect(defaultMetricsTelemetry(table, BUILD_REGION)).toEqual([ + { + name: "agentcore_metrics", + kind: "cloudwatch_metrics", + region: BUILD_REGION, + include: ["metrics"], + }, + ]); + }, + ); + + test.each(BUILDS)("adds none with OTEL off (%s)", (build) => { + const { table } = apply({}, contextOf(runtimeOf(build))); + + expect(tableOf(table)).not.toHaveProperty("agentcore_metrics"); + expect(defaultMetricsTelemetry(table, BUILD_REGION)).toEqual([]); + }); + + test.each([ + ["true", false], + [" TRUE ", false], + ["false", true], + ])( + "adds the default metrics target only when the envVars do not set DISABLE_ADOT_OBSERVABILITY to true (%j)", + (value, added) => { + const runtime = { + ...OTEL_CONTAINER, + envVars: [{ name: "DISABLE_ADOT_OBSERVABILITY", value }], + } as ProjectRuntime; + const { table } = apply({}, contextOf(runtime)); + + expect(Object.hasOwn(tableOf(table), "agentcore_metrics")).toBe(added); + expect(defaultMetricsTelemetry(table, BUILD_REGION)).toHaveLength(added ? 1 : 0); + }, + ); + + test.each([ + ["cn-north-1", "amazonaws.com.cn"], + ["cn-northwest-1", "amazonaws.com.cn"], + ["us-gov-west-1", "amazonaws.com"], + ["eu-west-1", "amazonaws.com"], + ])("names the DNS suffix of the partition of the build region (%s)", (region, suffix) => { + const context = { ...contextOf(OTEL_CONTAINER), region }; + const { table } = apply({}, context); + + expect(tableOf(table).agentcore_metrics).toMatchObject({ + destination: `https://monitoring.\${{ inputs.aws.region }}.${suffix}`, + }); + expect(defaultMetricsTelemetry(table, region)).toHaveLength(1); + }); + + test.each([ + "https://monitoring.eu-west-1.amazonaws.com", + "https://monitoring.eu-west-1.amazonaws.com/v1/metrics", + "https://monitoring.${{ inputs.aws.region }}.amazonaws.com", + "https://monitoring.cn-north-1.amazonaws.com.cn:443", + ])("adds no default metrics target beside a target of the user to %s", (destination) => { + const context = contextOf(OTEL_CONTAINER, { + thirdPartyTelemetry: [userMetrics(destination)], + }); + const { table } = apply({}, context); + + expect(Object.keys(tableOf(table))).toEqual(["mine", "agentcore", "agentcore_traces"]); + expect(defaultMetricsTelemetry(table, BUILD_REGION)).toEqual([]); + }); + + test.each([ + "https://otel.example.com", + "https://monitoring.example.com.evil", + "http://monitoring.eu-west-1.amazonaws.com", + ])( + "adds the default metrics target beside a target that does not send to the CloudWatch metrics endpoint (%s)", + (destination) => { + // The last one names no TLS, and box refuses a signed target with no https:// destination. + const context = contextOf(OTEL_CONTAINER, { + thirdPartyTelemetry: [userMetrics(destination)], + }); + + expect(tableOf(apply({}, context).table).agentcore_metrics).toEqual(DEFAULT_METRICS); + }, + ); + + test("names the default metrics target agentcore_metrics_default when a target is agentcore_metrics", () => { + const local = { telemetry: { agentcore_metrics: CLOUDWATCH.logs } }; + const telemetry = tableOf( + apply(local, contextOf(OTEL_CODEZIP, { telemetry: acceptedTelemetry(local) })).table, + ); + + expect(Object.keys(telemetry)).toEqual([ + "agentcore_metrics", + "agentcore_traces", + "agentcore_metrics_default", + ]); + expect(telemetry.agentcore_metrics_default).toEqual(DEFAULT_METRICS); + expect(defaultMetricsTelemetry({ telemetry }, BUILD_REGION)).toEqual([ + { + name: "agentcore_metrics_default", + kind: "cloudwatch_metrics", + region: BUILD_REGION, + include: ["metrics"], + }, + ]); + }); + + test("does not take a target of the user with the same keys in another partition for the default", () => { + const china = runtimeMetricsTarget("cn-north-1"); + + expect(defaultMetricsTelemetry({ telemetry: { mine: china } }, BUILD_REGION)).toEqual([]); + }); + + test("names the default metrics target in the header, last", () => { + const context = contextOf(OTEL_CODEZIP); + + expect(runtimeProfileHeader(context, apply({}, context).table).at(-1)).toBe( + "[telemetry.agentcore_metrics] is the default CloudWatch metrics target: the agent's own " + + "metrics, over OTLP, to the CloudWatch metrics endpoint of the Runtime's region. " + + "CloudWatch charges for them. Set instrumentation.enableOtel to false in " + + "agentcore.json to send none.", + ); + expect( + runtimeProfileHeader(contextOf(CODEZIP), apply({}, contextOf(CODEZIP)).table).join("\n"), + ).not.toContain("metrics target"); + }); + + test("names the metrics and their cost in the notice of create only with OTEL on", () => { + const on = defaultLogTargetNotice("agent", PROFILE_FILE, true); + const off = defaultLogTargetNotice("agent", PROFILE_FILE); + + expect(on.startsWith(off)).toBe(true); + expect(on.slice(off.length)).toBe( + " With instrumentation.enableOtel on, box also sends the agent's metrics to CloudWatch " + + "metrics in the region of the runtime, and CloudWatch charges for them. To send no " + + "metrics, set instrumentation.enableOtel to false.", + ); + expect(off).not.toContain("metrics"); + }); + + test.each(BUILDS)( + "gives the agent OTEL_METRICS_EXPORTER otlp with OTEL on, and no OTEL variable with OTEL off (%s)", + (build) => { + const pack = (runtime: ProjectRuntime) => + parse(renderAgentCorePack(specOf(runtime), runtime)) as { + agent?: { env?: Record }; + }; + + expect(pack(otelRuntime(build)).agent?.env?.OTEL_METRICS_EXPORTER).toBe("otlp"); + expect(pack(runtimeOf(build)).agent?.env ?? {}).not.toHaveProperty( + "OTEL_METRICS_EXPORTER", + ); + }, + ); + }); + test.each(BUILDS)( "keeps each OTEL variable that the user sets in [agent.env], so it wins over the pack (%s)", (build) => { diff --git a/src/core/project/runtimeProfile/rules/additions.ts b/src/core/project/runtimeProfile/rules/additions.ts index 37b66d80a..80cf1de74 100644 --- a/src/core/project/runtimeProfile/rules/additions.ts +++ b/src/core/project/runtimeProfile/rules/additions.ts @@ -18,12 +18,14 @@ * | `plugins` | the user's plugins, then @box/aws-secrets-manager when a carried target has a key | * | `[telemetry.agentcore]` | added when no target is `cloudwatch_logs`: the runtime's own log group and log stream | * | `[telemetry.agentcore_traces]` | added with OTEL on when no target is `cloudwatch_traces`: X-Ray in the Runtime's region, to the runtime's own log group and spans stream when the box takes them | + * | `[telemetry.agentcore_metrics]` | added with OTEL on when no target sends to the CloudWatch metrics endpoint: the agent's own metrics, over OTLP, to that endpoint in the Runtime's region | * | `[egress.agentcore]` | added when the project has a Memory and no route of the profile has the AgentCore host: that host, which box signs with a bare `aws://` and sends to directly, not through the Box gateway | * | a route to the AgentCore host | with a Memory in the project, it goes to the host directly, signed with a bare `aws://`, with its name and other keys | * * It moves no path: the paths rule runs after it and moves each path of the user. */ import { posix } from "node:path"; +import { partition } from "@aws-sdk/util-endpoints"; import { BOX_EGRESS_TARGET_PREFIX, agentCoreDataPlaneHost } from "../../boxNetwork/egress"; import { BOX_MEMORY_ROUTE_NAME, hasProjectMemory } from "../../boxMemory"; import { parseDestination } from "../../boxNetwork/egress"; @@ -137,6 +139,40 @@ export function runtimeTracesTarget(boxVersion?: string): TomlTable { }; } +/** + * The CloudWatch metrics target of a Runtime profile with OTEL on ({@link otelOn}) that has no + * target that sends to the CloudWatch metrics endpoint: the agent's own metrics, over OTLP, to the + * metrics endpoint of the Runtime's region, signed with the execution role. Box sends each batch to + * `/v1/metrics` of the destination, so the destination names only the host. `region`, the region + * that build builds for, gives the DNS suffix of its partition. + */ +export function runtimeMetricsTarget(region: string): TomlTable { + return { + kind: "otlp", + destination: `https://monitoring.${RUNTIME_INPUTS.awsRegion}.${partition(region).dnsSuffix}`, + accepts: ["metrics"], + include: ["metrics"], + secret: { ref: RUNTIME_AWS_SIGNER }, + }; +} + +/** + * The destination of a target that sends to the CloudWatch metrics endpoint: `monitoring.`, a + * region or an input, and the DNS suffix of an AWS partition, with no path or with any path. + */ +const CLOUDWATCH_METRICS_DESTINATION = + /^https:\/\/monitoring\.(?:\$\{\{[^}]*\}\}|[a-z0-9-]+)\.(?:amazonaws\.com(?:\.cn)?|amazonaws\.eu|api\.aws|c2s\.ic\.gov|sc2s\.sgov\.gov|cloud\.adc-e\.uk|csp\.hci\.ic\.gov)(?::443)?(?:\/|$)/i; + +/** Whether `entry`, a `[telemetry.]` table, is an `otlp` target of the CloudWatch metrics endpoint. */ +function sendsToCloudWatchMetrics(entry: unknown): boolean { + return ( + isTable(entry) && + entry.kind === "otlp" && + typeof entry.destination === "string" && + CLOUDWATCH_METRICS_DESTINATION.test(entry.destination.trim()) + ); +} + /** The program that starts a Python command with the OpenTelemetry instrumentation. */ const OTEL_INSTRUMENT = "opentelemetry-instrument"; @@ -161,16 +197,26 @@ function runtimeRegionEnv(bedrock: boolean): Record { /** * The notice that `agentcore create` and `agentcore add runtime` give for a box runtime: what the - * default log target sends, where, what it costs, and how to turn it off. + * default log target sends, where, what it costs, and how to turn it off. With `otel`, it also + * names the default metrics target ({@link runtimeMetricsTarget}). */ -export function defaultLogTargetNotice(runtimeName: string, profileFile: string): string { +export function defaultLogTargetNotice( + runtimeName: string, + profileFile: string, + otel = false, +): string { return ( `runtime "${runtimeName}": when ${profileFile} has no cloudwatch_logs target, box on ` + "AgentCore Runtime sends its deny, permit, and trace records to the log group of the " + "runtime, /aws/bedrock-agentcore/runtimes/-DEFAULT, log stream otel-rt-logs. The " + "Runtime makes that log group, so its retention applies, and the log group stays after the " + "runtime is removed. CloudWatch Logs charges for the records. To send none, set " + - `${OBSERVABILITY_OFF_ENV} to "true" in the envVars of the runtime in agentcore.json.` + `${OBSERVABILITY_OFF_ENV} to "true" in the envVars of the runtime in agentcore.json.` + + (otel + ? " With instrumentation.enableOtel on, box also sends the agent's metrics to CloudWatch " + + "metrics in the region of the runtime, and CloudWatch charges for them. To send no " + + "metrics, set instrumentation.enableOtel to false." + : "") ); } @@ -214,6 +260,12 @@ export function runtimeProfileHeader( `. Add a cloudwatch_traces target to ${context.profileFile} to use ` + "another, or set instrumentation.enableOtel to false in agentcore.json to send none.", ), + ...defaultMetricsTargets(profile, context.region).map( + (name) => + `[telemetry.${name}] is the default CloudWatch metrics target: the agent's own metrics, ` + + "over OTLP, to the CloudWatch metrics endpoint of the Runtime's region. CloudWatch " + + "charges for them. Set instrumentation.enableOtel to false in agentcore.json to send none.", + ), ]; } @@ -244,6 +296,33 @@ export function defaultTracesTelemetry( })); } +/** + * The name of each default CloudWatch metrics target ({@link runtimeMetricsTarget} for `region`) in + * the `[telemetry]` of `profile`. + */ +function defaultMetricsTargets(profile: Readonly, region: string): string[] { + const form = runtimeMetricsTarget(region); + return Object.entries(tableOf(profile.telemetry)) + .filter(([, target]) => sameValue(target, form)) + .map(([name]) => name); +} + +/** + * Each default CloudWatch metrics target of `profile`, a Runtime profile, as a CloudWatch target in + * `region`, the region build builds for: the execution role needs a grant for it. + */ +export function defaultMetricsTelemetry( + profile: Readonly, + region: string, +): CloudWatchTelemetry[] { + return defaultMetricsTargets(profile, region).map((name) => ({ + name, + kind: "cloudwatch_metrics", + region, + include: ["metrics"], + })); +} + /** Whether the `[agent] command` of `profile`, a Runtime profile, starts under opentelemetry-instrument. */ export function agentStartsUnderOtel(profile: Readonly): boolean { return startsUnderOtel(tableOf(profile.agent).command); @@ -807,8 +886,10 @@ function onAllAddresses(entry: unknown): unknown { * stays as it is. With no `cloudwatch_logs` target, {@link DEFAULT_TELEMETRY_TARGET} comes next, as * `agentcore`, or as `agentcore_default` when a target has that name, unless the envVars of the * runtime turn observability off ({@link OBSERVABILITY_OFF_ENV}). With OTEL on and no - * `cloudwatch_traces` target, {@link DEFAULT_TRACES_TARGET} comes last, as `agentcore_traces`, or - * as `agentcore_traces_default` when a target has that name ({@link otelOn}). + * `cloudwatch_traces` target, {@link DEFAULT_TRACES_TARGET} comes next, as `agentcore_traces`, or + * as `agentcore_traces_default` when a target has that name ({@link otelOn}). With OTEL on and no + * target that sends to the CloudWatch metrics endpoint, {@link runtimeMetricsTarget} comes last, as + * `agentcore_metrics`, or as `agentcore_metrics_default` when a target has that name. */ function runtimeTelemetry( telemetry: unknown, @@ -883,6 +964,12 @@ function runtimeTelemetry( : "agentcore_traces"; result[name] = runtimeTracesTarget(context.boxVersion); } + if (otelOn(context.runtime) && !Object.values(result).some(sendsToCloudWatchMetrics)) { + const name = Object.hasOwn(result, "agentcore_metrics") + ? "agentcore_metrics_default" + : "agentcore_metrics"; + result[name] = runtimeMetricsTarget(context.region); + } return result; } diff --git a/src/core/project/templates/boxProfile.test.ts b/src/core/project/templates/boxProfile.test.ts index dff45caf6..8345a7186 100644 --- a/src/core/project/templates/boxProfile.test.ts +++ b/src/core/project/templates/boxProfile.test.ts @@ -669,7 +669,7 @@ describe("renderAgentCorePack", () => { AGENT_OBSERVABILITY_ENABLED: "${{ inputs.otel.agent_observability_enabled }}", OTEL_TRACES_EXPORTER: "otlp", OTEL_LOGS_EXPORTER: "otlp", - OTEL_METRICS_EXPORTER: "none", + OTEL_METRICS_EXPORTER: "otlp", OTEL_PYTHON_EXCLUDED_URLS: "${{ inputs.otel.python_excluded_urls }}", OTEL_RESOURCE_ATTRIBUTES: "${{ inputs.runtime.resource_attributes }}", }); diff --git a/src/core/project/templates/boxProfile.ts b/src/core/project/templates/boxProfile.ts index f9c739ea9..da8d4236b 100644 --- a/src/core/project/templates/boxProfile.ts +++ b/src/core/project/templates/boxProfile.ts @@ -729,11 +729,11 @@ interface ServiceOtelVariable { /** * The variables that set up the ADOT SDK of an agent with OTEL on, in the order that the agent - * gets them. Each string is a fixed value that box needs: spans and logs over OTLP to the box's own - * receiver (box sets each `OTEL_EXPORTER_OTLP_*`), and no metrics, which no default target of box - * takes. Each {@link ServiceOtelVariable} has the value that AgentCore Runtime sets, as for an agent - * outside a box: the AWS distro and its configurator, the agent observability mode, and no span - * for each health check of the Runtime. + * gets them. Each string is a fixed value that box needs: spans, logs, and metrics over OTLP to the + * box's own receiver (box sets each `OTEL_EXPORTER_OTLP_*`). The default metrics target of the + * Runtime profile sends the metrics on to CloudWatch. Each {@link ServiceOtelVariable} has the value + * that AgentCore Runtime sets, as for an agent outside a box: the AWS distro and its configurator, + * the agent observability mode, and no span for each health check of the Runtime. */ const AGENT_OTEL_ENV: Readonly> = { OTEL_PYTHON_DISTRO: { @@ -753,7 +753,7 @@ const AGENT_OTEL_ENV: Readonly> = { }, OTEL_TRACES_EXPORTER: "otlp", OTEL_LOGS_EXPORTER: "otlp", - OTEL_METRICS_EXPORTER: "none", + OTEL_METRICS_EXPORTER: "otlp", OTEL_PYTHON_EXCLUDED_URLS: { input: "python_excluded_urls", description: "The URL paths that Python auto-instrumentation does not trace.", From 0887c3e0184fe018a2c0da171ebbda94bf5e811f Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Mon, 30 Nov 2026 12:19:40 -0800 Subject: [PATCH 2/2] fix(box): Keep the default metrics target with a CloudWatch metrics target that has no key, and tell the user (live test) A target of the user to the CloudWatch metrics endpoint with no key cannot authenticate on AgentCore Runtime, so CloudWatch refuses each send. Before this change, `agentcore build` then left out the default metrics target, and the runtime sent no metric. After this change, only a target with an `env://` or `secret://` key replaces the default target. For a target with no key, `agentcore build` keeps the default target and writes a `Warning:` line with the position of the target. --- docs/box-local-testing.md | 12 +-- src/core/project/boxNetworkSource.test.ts | 73 ++++++++++++++++- .../runtimeProfile/rules/additions.test.ts | 80 +++++++++++++++++-- .../project/runtimeProfile/rules/additions.ts | 34 +++++--- 4 files changed, 173 insertions(+), 26 deletions(-) diff --git a/docs/box-local-testing.md b/docs/box-local-testing.md index 3d3d858dc..9523bb713 100644 --- a/docs/box-local-testing.md +++ b/docs/box-local-testing.md @@ -353,11 +353,13 @@ profile that names a pack `box/` fails: box refuses it and names the `@box send no spans, set `instrumentation.enableOtel` to `false` in `agentcore.json`. When `enableOtel` is on and the agent does not start with `opentelemetry-instrument`, build gives a warning. - **The default metrics target.** With `enableOtel` on and no target that sends to the CloudWatch - metrics endpoint, the Runtime profile gets `[telemetry.agentcore_metrics]`, or - `[telemetry.agentcore_metrics_default]` when a target has the name `agentcore_metrics`. It is an - `otlp` target with `accepts = ["metrics"]`: box sends the metrics of the agent, such as token use, - model call time, and the Strands event loop, to + **The default metrics target.** With `enableOtel` on and no target with a key that sends to the + CloudWatch metrics endpoint, the Runtime profile gets `[telemetry.agentcore_metrics]`, or + `[telemetry.agentcore_metrics_default]` when a target has the name `agentcore_metrics`. A target of + yours to that endpoint replaces it only with an `env://` or `secret://` key, which CloudWatch + accepts as a bearer token. A target with no key cannot authenticate, so build keeps the default + target and warns. The default target is an `otlp` target with `accepts = ["metrics"]`: box sends + the metrics of the agent, such as token use, model call time, and the Strands event loop, to `https://monitoring../v1/metrics`, and signs them with the execution role. Box adds `/v1/metrics` itself. CloudWatch keeps them as OpenTelemetry metrics, which you query with PromQL in CloudWatch Query Studio. They are not in the `bedrock-agentcore` diff --git a/src/core/project/boxNetworkSource.test.ts b/src/core/project/boxNetworkSource.test.ts index 1eae48a62..720dca477 100644 --- a/src/core/project/boxNetworkSource.test.ts +++ b/src/core/project/boxNetworkSource.test.ts @@ -749,31 +749,96 @@ describe("the default X-Ray target of a runtime with OTEL on", () => { expect(JSON.parse((file as { text: string }).text).Statement).toEqual([X_RAY, PUT_METRIC_DATA]); }); - test("adds no default metrics target, and no metrics grant, when the profile has its own target of the CloudWatch metrics endpoint", async () => { + test("adds no default metrics target, and no metrics grant, when the profile has its own target of the CloudWatch metrics endpoint with a key", async () => { const root = await project([]); const shown = boxShowOf({ egress: API_ROUTE }); - // No key: a CodeZip runtime carries a third-party target only without one. const own = { kind: "otlp", destination: "https://monitoring.eu-west-1.amazonaws.com", accepts: ["metrics"], + secret: { ref: "env://CLOUDWATCH_METRICS_KEY" }, }; const box = new FakeBoxProfileResolver({ ...shown, boxToml: { ...shown.boxToml, telemetry: { mine: own } }, }); + // A CodeZip runtime carries no third-party target with a key, so this runtime is a container. + const spec = { + ...OTEL_SPEC, + runtimes: [{ ...OTEL_SPEC.runtimes[0]!, build: "Container", entrypoint: "main.py" }], + } as unknown as ProjectSpec; - const [network] = await readBoxNetworks(OTEL_SPEC, root, box); + const [network] = await readBoxNetworks(spec, root, box); expect(network?.thirdPartyTelemetry?.map(({ name }) => name)).toEqual(["mine"]); expect(network?.runtimeProfile?.telemetry).not.toHaveProperty("agentcore_metrics"); expect(network?.telemetry).toEqual([TRACES]); - const [file] = policyOf(network!); + expect(network?.warnings.filter((warning) => warning.includes("metrics endpoint"))).toEqual([]); + const [file] = telemetryPolicyWriter + .edits([network!], { spec, projectRoot: "/project", env: {}, envLocal: {} }) + .files!.filter(({ path }) => path === boxTelemetryPolicyFile("agent")); expect(JSON.parse((file as { text: string }).text).Statement).not.toContainEqual( PUT_METRIC_DATA, ); }); + test("keeps the default metrics target and its grant beside a target of the CloudWatch metrics endpoint with no key, and warns", async () => { + const root = await project([]); + const shown = boxShowOf({ egress: API_ROUTE }); + const own = { + kind: "otlp", + destination: "https://monitoring.eu-west-1.amazonaws.com", + accepts: ["metrics"], + }; + const box = new FakeBoxProfileResolver({ + ...shown, + boxToml: { ...shown.boxToml, telemetry: { mine: own } }, + }); + + const [network] = await readBoxNetworks(OTEL_SPEC, root, box); + + expect(network?.thirdPartyTelemetry?.map(({ name }) => name)).toEqual(["mine"]); + expect(network?.runtimeProfile?.telemetry).toHaveProperty("agentcore_metrics", METRICS_TARGET); + expect(network?.telemetry).toEqual([TRACES, METRICS]); + expect(network?.warnings.filter((warning) => warning.includes("metrics endpoint"))).toEqual([ + ".box/agent/local/profile.toml: [telemetry.mine] sends to the CloudWatch metrics endpoint " + + "with no secret. CloudWatch refuses a send with no signature and no key, so no metric of " + + "this target gets there. Build adds [telemetry.agentcore_metrics] too, which box signs " + + "with the execution role. To use your target, give it an env:// or secret:// key that " + + "CloudWatch accepts as a bearer token, or remove the target.", + ]); + const [file] = policyOf(network!); + expect(JSON.parse((file as { text: string }).text).Statement).toContainEqual(PUT_METRIC_DATA); + }); + + test("names the line of a target with no key to the CloudWatch metrics endpoint in its warning", async () => { + const root = await project([]); + await writeFile( + join(root, ...LOCAL, "profile.toml"), + 'policies = []\n[egress.api]\ndestinations = ["api.example.com"]\n\n' + + '[telemetry.mine]\nkind = "otlp"\ndestination = "https://monitoring.eu-west-1.amazonaws.com"\n' + + 'accepts = ["metrics"]\n', + ); + const shown = boxShowOf({ egress: API_ROUTE }); + const own = { + kind: "otlp", + destination: "https://monitoring.eu-west-1.amazonaws.com", + accepts: ["metrics"], + }; + const box = new FakeBoxProfileResolver({ + ...shown, + boxToml: { ...shown.boxToml, telemetry: { mine: own } }, + }); + + const [network] = await readBoxNetworks(OTEL_SPEC, root, box); + + const [warning] = network?.warnings.filter((text) => text.includes("metrics endpoint")) ?? []; + expect(warning).toStartWith(".box/agent/local/profile.toml:5:"); + expect(warning).toContain( + "[telemetry.mine] sends to the CloudWatch metrics endpoint with no secret", + ); + }); + test("adds the default metrics target beside a third-party target that sends spans", async () => { const root = await project([]); const shown = boxShowOf({ egress: API_ROUTE }); diff --git a/src/core/project/runtimeProfile/rules/additions.test.ts b/src/core/project/runtimeProfile/rules/additions.test.ts index b955d9ed7..4a7b5c921 100644 --- a/src/core/project/runtimeProfile/rules/additions.test.ts +++ b/src/core/project/runtimeProfile/rules/additions.test.ts @@ -1892,15 +1892,20 @@ describe("the additions rule", () => { }); describe("the default CloudWatch metrics target", () => { - /** A third-party `otlp` target that box resolves, with `destination`, which sends metrics. */ - const userMetrics = (destination: string): ThirdPartyTelemetry => ({ + /** + * A third-party `otlp` target that box resolves, with `destination`, which sends metrics. With + * `keyed`, it has an `env://` key, which CloudWatch accepts as a bearer token. + */ + const userMetrics = (destination: string, keyed = true): ThirdPartyTelemetry => ({ name: "mine", kind: "otlp", keys: [ ["destination", destination], ["accepts", ["metrics"]], ], + ...(keyed && { secret: { variable: "CLOUDWATCH_METRICS_KEY", keys: [] } }), }); + const CONTAINER_OFF = runtimeOf("Container"); test.each(BUILDS)( "sends the agent's metrics to the CloudWatch metrics endpoint of the Runtime's region, signed with the execution role (%s)", @@ -1965,14 +1970,73 @@ describe("the additions rule", () => { "https://monitoring.eu-west-1.amazonaws.com/v1/metrics", "https://monitoring.${{ inputs.aws.region }}.amazonaws.com", "https://monitoring.cn-north-1.amazonaws.com.cn:443", - ])("adds no default metrics target beside a target of the user to %s", (destination) => { - const context = contextOf(OTEL_CONTAINER, { - thirdPartyTelemetry: [userMetrics(destination)], + ])( + "adds no default metrics target, and no warning, beside a target of the user with a key to %s", + (destination) => { + const context = contextOf(OTEL_CONTAINER, { + thirdPartyTelemetry: [userMetrics(destination)], + }); + const { table, warnings } = apply({}, context); + + expect(Object.keys(tableOf(table))).toEqual(["mine", "agentcore", "agentcore_traces"]); + expect(defaultMetricsTelemetry(table, BUILD_REGION)).toEqual([]); + expect(warnings.filter((warning) => warning.includes("metrics endpoint"))).toEqual([]); + }, + ); + + test("keeps the default metrics target beside a target of the user to the metrics endpoint with no key, and warns at its place", () => { + const destination = "https://monitoring.eu-west-1.amazonaws.com"; + const context = { + ...contextOf(OTEL_CONTAINER, { + thirdPartyTelemetry: [userMetrics(destination, false)], + }), + placeOf: (key: readonly string[]) => + key.join(".") === "telemetry.mine" ? `${PROFILE_FILE}:12:1` : PROFILE_FILE, + }; + const { table, warnings } = apply({}, context); + + expect(Object.keys(tableOf(table))).toEqual([ + "mine", + "agentcore", + "agentcore_traces", + "agentcore_metrics", + ]); + expect(tableOf(table).agentcore_metrics).toEqual(DEFAULT_METRICS); + expect(defaultMetricsTelemetry(table, BUILD_REGION)).toHaveLength(1); + expect(warnings).toContain( + `${PROFILE_FILE}:12:1: [telemetry.mine] sends to the CloudWatch metrics endpoint with no ` + + "secret. CloudWatch refuses a send with no signature and no key, so no metric of this " + + "target gets there. Build adds [telemetry.agentcore_metrics] too, which box signs with " + + "the execution role. To use your target, give it an env:// or secret:// key that " + + "CloudWatch accepts as a bearer token, or remove the target.", + ); + }); + + test("adds the default metrics target beside two targets of the metrics endpoint only when neither has a key", () => { + const endpoint = "https://monitoring.eu-west-1.amazonaws.com"; + const keyless = { ...userMetrics(endpoint, false), name: "open" }; + const both = apply( + {}, + contextOf(OTEL_CONTAINER, { thirdPartyTelemetry: [keyless, userMetrics(endpoint)] }), + ); + const only = apply({}, contextOf(OTEL_CONTAINER, { thirdPartyTelemetry: [keyless] })); + const named = (warnings: readonly string[]) => + warnings.filter((warning) => warning.includes("metrics endpoint")); + + expect(tableOf(both.table)).not.toHaveProperty("agentcore_metrics"); + expect(named(both.warnings)).toEqual([]); + expect(tableOf(only.table)).toHaveProperty("agentcore_metrics"); + expect(named(only.warnings)).toHaveLength(1); + }); + + test("gives no metrics warning with OTEL off, where no default target comes", () => { + const context = contextOf(CONTAINER_OFF, { + thirdPartyTelemetry: [userMetrics("https://monitoring.eu-west-1.amazonaws.com", false)], }); - const { table } = apply({}, context); + const { table, warnings } = apply({}, context); - expect(Object.keys(tableOf(table))).toEqual(["mine", "agentcore", "agentcore_traces"]); - expect(defaultMetricsTelemetry(table, BUILD_REGION)).toEqual([]); + expect(tableOf(table)).not.toHaveProperty("agentcore_metrics"); + expect(warnings.filter((warning) => warning.includes("metrics endpoint"))).toEqual([]); }); test.each([ diff --git a/src/core/project/runtimeProfile/rules/additions.ts b/src/core/project/runtimeProfile/rules/additions.ts index 80cf1de74..d0d063e52 100644 --- a/src/core/project/runtimeProfile/rules/additions.ts +++ b/src/core/project/runtimeProfile/rules/additions.ts @@ -18,7 +18,7 @@ * | `plugins` | the user's plugins, then @box/aws-secrets-manager when a carried target has a key | * | `[telemetry.agentcore]` | added when no target is `cloudwatch_logs`: the runtime's own log group and log stream | * | `[telemetry.agentcore_traces]` | added with OTEL on when no target is `cloudwatch_traces`: X-Ray in the Runtime's region, to the runtime's own log group and spans stream when the box takes them | - * | `[telemetry.agentcore_metrics]` | added with OTEL on when no target sends to the CloudWatch metrics endpoint: the agent's own metrics, over OTLP, to that endpoint in the Runtime's region | + * | `[telemetry.agentcore_metrics]` | added with OTEL on when no target with a key sends to the CloudWatch metrics endpoint: the agent's own metrics, over OTLP, to that endpoint in the Runtime's region; a warning for each target of that endpoint with no key | * | `[egress.agentcore]` | added when the project has a Memory and no route of the profile has the AgentCore host: that host, which box signs with a bare `aws://` and sends to directly, not through the Box gateway | * | a route to the AgentCore host | with a Memory in the project, it goes to the host directly, signed with a bare `aws://`, with its name and other keys | * @@ -141,7 +141,7 @@ export function runtimeTracesTarget(boxVersion?: string): TomlTable { /** * The CloudWatch metrics target of a Runtime profile with OTEL on ({@link otelOn}) that has no - * target that sends to the CloudWatch metrics endpoint: the agent's own metrics, over OTLP, to the + * target with a key that sends to the CloudWatch metrics endpoint: the agent's own metrics, over OTLP, to the * metrics endpoint of the Runtime's region, signed with the execution role. Box sends each batch to * `/v1/metrics` of the destination, so the destination names only the host. `region`, the region * that build builds for, gives the DNS suffix of its partition. @@ -888,8 +888,9 @@ function onAllAddresses(entry: unknown): unknown { * runtime turn observability off ({@link OBSERVABILITY_OFF_ENV}). With OTEL on and no * `cloudwatch_traces` target, {@link DEFAULT_TRACES_TARGET} comes next, as `agentcore_traces`, or * as `agentcore_traces_default` when a target has that name ({@link otelOn}). With OTEL on and no - * target that sends to the CloudWatch metrics endpoint, {@link runtimeMetricsTarget} comes last, as - * `agentcore_metrics`, or as `agentcore_metrics_default` when a target has that name. + * target with a key that sends to the CloudWatch metrics endpoint, {@link runtimeMetricsTarget} + * comes last, as `agentcore_metrics`, or as `agentcore_metrics_default` when a target has that + * name, with a warning for each target of that endpoint that has no key. */ function runtimeTelemetry( telemetry: unknown, @@ -964,11 +965,26 @@ function runtimeTelemetry( : "agentcore_traces"; result[name] = runtimeTracesTarget(context.boxVersion); } - if (otelOn(context.runtime) && !Object.values(result).some(sendsToCloudWatchMetrics)) { - const name = Object.hasOwn(result, "agentcore_metrics") - ? "agentcore_metrics_default" - : "agentcore_metrics"; - result[name] = runtimeMetricsTarget(context.region); + if (otelOn(context.runtime)) { + const own = Object.entries(result).filter(([, entry]) => sendsToCloudWatchMetrics(entry)); + // CloudWatch takes metrics with a SigV4 signature or a bearer key. A target of the user has + // no SigV4 signature on the Runtime, so only one with a key replaces the default target. + if (!own.some(([, entry]) => isTable(entry) && entry.secret !== undefined)) { + const name = Object.hasOwn(result, "agentcore_metrics") + ? "agentcore_metrics_default" + : "agentcore_metrics"; + result[name] = runtimeMetricsTarget(context.region); + for (const [unsigned] of own) { + warnings.push( + `${context.placeOf(["telemetry", unsigned])}: [telemetry.${unsigned}] sends to the ` + + "CloudWatch metrics endpoint with no secret. CloudWatch refuses a send with no " + + `signature and no key, so no metric of this target gets there. Build adds ` + + `[telemetry.${name}] too, which box signs with the execution role. To use your ` + + "target, give it an env:// or secret:// key that CloudWatch accepts as a bearer " + + "token, or remove the target.", + ); + } + } } return result; }