Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 26 additions & 6 deletions docs/box-local-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,9 +313,9 @@ profile that names a pack `box/<name>` 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=<runtime>`. 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.<gateway>]`, to the host that `@box/agentcore`
reads from `AGENTCORE_GATEWAY_<NAME>_HOST`, through its `egress-gateway-<name>` target. The agent
Expand Down Expand Up @@ -353,6 +353,23 @@ profile that names a pack `box/<name>` 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 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.<region of the Runtime>.<DNS suffix>/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-<runtime>.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
Expand Down Expand Up @@ -576,7 +593,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
Expand Down Expand Up @@ -647,8 +666,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-<runtime>.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:

Expand Down
20 changes: 14 additions & 6 deletions src/core/project/boxNetwork/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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[];
/**
Expand Down Expand Up @@ -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,
Expand Down
8 changes: 8 additions & 0 deletions src/core/project/boxNetwork/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
194 changes: 190 additions & 4 deletions src/core/project/boxNetworkSource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Awaited<ReturnType<typeof readBoxNetworks>>[number]>) =>
Expand All @@ -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<string, unknown>;
expect(telemetry.agentcore_traces).toEqual({
kind: "cloudwatch_traces",
Expand All @@ -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 }]);
});

Expand Down Expand Up @@ -721,10 +742,175 @@ 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 with a key", 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"],
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(spec, root, box);

expect(network?.thirdPartyTelemetry?.map(({ name }) => name)).toEqual(["mine"]);
expect(network?.runtimeProfile?.telemetry).not.toHaveProperty("agentcore_metrics");
expect(network?.telemetry).toEqual([TRACES]);
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 });
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 });
});
});

Expand Down
29 changes: 29 additions & 0 deletions src/core/project/boxTelemetry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand All @@ -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" };
Expand Down
Loading