Skip to content
Merged
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
31 changes: 30 additions & 1 deletion src/core/project/backends/cdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,10 @@ describe("CdkBackend.build", () => {
...(build === "CodeZip" && { runtimeVersion: "PYTHON_3_14" }),
entrypoint: "main.py",
codeLocation: "app/agent",
...(projectType && { box: { version: BOX_RELEASE.version } }),
...(projectType && {
box: { version: BOX_RELEASE.version },
platformVersion: "V2" as const,
}),
...(!otel && { instrumentation: { enableOtel: false } }),
},
],
Expand Down Expand Up @@ -423,6 +426,7 @@ describe("CdkBackend.build", () => {
codeLocation: "app/agent",
envVars: [{ name: "DISABLE_ADOT_OBSERVABILITY", value: "true" }],
box: { version: BOX_RELEASE.version },
platformVersion: "V2" as const,
},
],
agentCoreGateways: [boxGatewaySpec("agent")],
Expand All @@ -443,6 +447,7 @@ describe("CdkBackend.build", () => {
entrypoint: "main.py",
codeLocation: "app/agent",
box: { version: BOX_RELEASE.version },
platformVersion: "V2" as const,
},
],
agentCoreGateways: [boxGatewaySpec("agent")],
Expand All @@ -464,6 +469,7 @@ describe("CdkBackend.build", () => {
entrypoint: "main.py",
codeLocation: "app/agent",
box: { version: BOX_RELEASE.version },
platformVersion: "V2" as const,
},
],
agentCoreGateways: [boxGatewaySpec("agent")],
Expand Down Expand Up @@ -616,6 +622,29 @@ describe("CdkBackend.deploy", () => {
expect(subject.templateLoads()).toBe(0);
});

// An old @aws/agentcore-cdk drops platformVersion without an error, so deploy checks the
// synthesized template before it runs anything.
test("refuses a runtime whose platformVersion the synthesized stack does not set, before deploying", async () => {
Comment thread
mquang-amazon marked this conversation as resolved.
Resolved
const input = await project();
input.spec.runtimes.push(
ProjectRuntimeSchema.parse({
name: "agent",
build: "CodeZip",
codeLocation: "app/agent",
entrypoint: "start.py",
runtimeVersion: "PYTHON_3_14",
platformVersion: "V2",
}),
);
await writeAssembly(input, [TARGET.name]);
const subject = harness({ outputs: { RuntimeArn: "arn:runtime" } });

await expect(collectDeploy(subject.backend.deploy(input, deployInput()))).rejects.toThrow(
"Could not find runtime 'agent' in the synthesized stack",
);
expect(subject.runs).toEqual([]);
});

test("skips Transaction Search when the config disables it", async () => {
const input = await project();
await writeAssembly(input, [TARGET.name]);
Expand Down
8 changes: 8 additions & 0 deletions src/core/project/backends/cdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ import {
type DeployedCredentials,
} from "./cdk/credentials";
import {
assertPlatformVersions,
runtimePlatformVersions,
assertPrivateVpcs,
countDeployableResources,
stackArtifactForTarget,
Expand Down Expand Up @@ -375,6 +377,12 @@ export class CdkBackend implements ProjectBackend {
.filter((runtime) => runtime.containment === "PRIVATE_VPC")
.map((runtime) => runtime.name),
);
await assertPlatformVersions(
Comment thread
mquang-amazon marked this conversation as resolved.
Resolved
this.json,
assemblyDirectory,
artifact,
runtimePlatformVersions(project.spec.runtimes),
);

// Only after a real deploy is confirmed: a teardown (empty assembly) returns
// above, so a destroy is never blocked by Transaction Search. Never fail the
Expand Down
107 changes: 106 additions & 1 deletion src/core/project/backends/cdk/assembly.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@ import { join } from "node:path";
import { tmpdir } from "node:os";
import { FsReadWriteJson } from "../../../../io";
import { createSilentLogger } from "../../../../testing";
import { assertPrivateVpcs, countDeployableResources, stackArtifactForTarget } from "./assembly";
import {
assertPlatformVersions,
assertPrivateVpcs,
countDeployableResources,
runtimePlatformVersions,
stackArtifactForTarget,
} from "./assembly";

const temporaryDirectories: string[] = [];
const json = new FsReadWriteJson({ logger: createSilentLogger() });
Expand Down Expand Up @@ -137,6 +143,105 @@ describe("assertPrivateVpcs", () => {
});
});

describe("runtimePlatformVersions", () => {
// Not only a Box project's runtimes: any runtime that names a version is checked, V1 too.
test("takes each runtime that names a platformVersion, V1 or V2, and skips one with none", () => {
expect(
runtimePlatformVersions([
{ name: "box_agent", platformVersion: "V2" },
{ name: "plain_v2", platformVersion: "V2" },
{ name: "plain_v1", platformVersion: "V1" },
{ name: "unset" },
]),
).toEqual([
{ name: "box_agent", platformVersion: "V2" },
{ name: "plain_v2", platformVersion: "V2" },
{ name: "plain_v1", platformVersion: "V1" },
]);
});
});

describe("assertPlatformVersions", () => {
const artifact = { id: "Stack", stackName: "AgentCore-App-default", templateFile: TEMPLATE_FILE };
/** A runtime resource, and the RuntimeId export the CDK library writes for runtime `name`. */
const runtime = (name: string, logicalId: string, properties: Record<string, unknown>) => ({
Resources: { [logicalId]: { Type: "AWS::BedrockAgentCore::Runtime", Properties: properties } },
Outputs: {
[`${logicalId}Id`]: {
Value: { "Fn::GetAtt": [logicalId, "AgentRuntimeId"] },
Export: { Name: `AgentCore-App-default-${name.replaceAll("_", "-")}-RuntimeId` },
},
},
});
/** One template with each runtime of `templates`. */
const merged = (...templates: ReturnType<typeof runtime>[]) => ({
Resources: Object.assign({}, ...templates.map(({ Resources }) => Resources)),
Outputs: Object.assign({}, ...templates.map(({ Outputs }) => Outputs)),
});
async function check(
template: Record<string, unknown>,
runtimes: { name: string; platformVersion: string }[],
) {
const directory = await assembly({ Stack: stackArtifact("prod") });
await writeFile(join(directory, TEMPLATE_FILE), JSON.stringify(template));
return assertPlatformVersions(json, directory, artifact, runtimes);
}
const notSet = (name: string, version: string) =>
`Runtime '${name}' has "platformVersion": "${version}", but the synthesized stack does not ` +
"set it: the @aws/agentcore-cdk in agentcore/cdk does not support platformVersion, and no " +
"released @aws/agentcore-cdk does yet. Deploy again once agentcore/cdk has a release that does.";

test.each(["V1", "V2"])("accepts a runtime that runs on its own %s", async (version) => {
await expect(
check(runtime("my_agent", "RuntimeMyAgent", { PlatformVersion: version }), [
{ name: "my_agent", platformVersion: version },
]),
).resolves.toBeUndefined();
});

test("accepts a stack with no runtime to check", async () => {
await expect(check({ Resources: {} }, [])).resolves.toBeUndefined();
});

test.each([
["no PlatformVersion, as a CDK library from before platformVersion synthesizes", {}, "V2"],
["another PlatformVersion", { PlatformVersion: "V1" }, "V2"],
["no PlatformVersion for an explicit V1", {}, "V1"],
])("refuses %s", async (_name, properties, version) => {
await expect(
check(runtime("agent", "RuntimeAgent", properties), [
{ name: "agent", platformVersion: version },
]),
).rejects.toThrow(notSet("agent", version));
});

test("names only the runtime that does not run on its version", async () => {
const template = merged(
runtime("good", "RuntimeGood", { PlatformVersion: "V2" }),
runtime("bad", "RuntimeBad", {}),
);

const refused = check(template, [
{ name: "good", platformVersion: "V2" },
{ name: "bad", platformVersion: "V2" },
]);

await expect(refused).rejects.toThrow(notSet("bad", "V2"));
await expect(refused).rejects.not.toThrow("'good'");
});

test("refuses a runtime the stack exports no RuntimeId for, and says it is not found", async () => {
await expect(
check(runtime("other", "RuntimeOther", { PlatformVersion: "V2" }), [
{ name: "agent", platformVersion: "V2" },
]),
).rejects.toThrow(
"Could not find runtime 'agent' in the synthesized stack 'AgentCore-App-default', so " +
'deploy cannot check that it runs on "platformVersion": "V2".',
);
});
});

describe("countDeployableResources", () => {
const artifact = { id: "Stack", stackName: "Stack", templateFile: TEMPLATE_FILE };

Expand Down
67 changes: 67 additions & 0 deletions src/core/project/backends/cdk/assembly.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ const AssemblyManifestSchema = z.object({
.default({}),
});

/** A stack output that exports `Fn::GetAtt` of a resource, as each runtime's `RuntimeId` does. */
const GetAttOutputSchema = z.object({
Value: z.object({ "Fn::GetAtt": z.tuple([z.string(), z.string()]) }),
Export: z.object({ Name: z.string() }),
});
const PlatformVersionPropertiesSchema = z.object({ PlatformVersion: z.string() });

const StackTemplateSchema = z
.object({
Resources: z
Expand All @@ -42,6 +49,7 @@ const StackTemplateSchema = z
z.object({ Type: z.string().optional() }).passthrough(),
)
.default({}),
Outputs: z.record(z.string(), z.unknown()).default({}),
})
.passthrough();

Expand Down Expand Up @@ -164,6 +172,65 @@ export async function assertPrivateVpcs(
}
}

/**
* The runtimes whose platform deploy checks after synth: each one that names a `platformVersion`,
* in a Box project or not, `"V1"` included, since a CDK library from before the field drops it.
*/
export function runtimePlatformVersions(
runtimes: readonly { readonly name: string; readonly platformVersion?: string }[],
): { name: string; platformVersion: string }[] {
return runtimes.flatMap(({ name, platformVersion }) =>
platformVersion === undefined ? [] : [{ name, platformVersion }],
);
}

/**
* Refuses a stack in which a runtime of `runtimes` does not run on its own `platformVersion`. A
* CDK library from before `platformVersion` drops the field without an error, and the service
* would pick the platform. The CDK library exports each runtime's ID as
* `<stack>-<runtime>-RuntimeId` (`_` as `-`), from `Fn::GetAtt` of its
* `AWS::BedrockAgentCore::Runtime`; a runtime with no such export is refused too, as one whose
* platform deploy cannot check.
*/
export async function assertPlatformVersions(
json: ReadWriteJson,
assemblyDirectory: string,
artifact: StackArtifact,
runtimes: readonly { readonly name: string; readonly platformVersion: string }[],
): Promise<void> {
if (runtimes.length === 0) return;
const template = await readStackTemplate(json, assemblyDirectory, artifact);
const logicalIdByExport = new Map(
Object.values(template.Outputs).flatMap((output) => {
const parsed = GetAttOutputSchema.safeParse(output).data;
return parsed ? [[parsed.Export.Name, parsed.Value["Fn::GetAtt"][0]] as const] : [];
}),
);
// The CDK library's exportName: each part with `_` as `-` and every other character but
// letters, digits, `:` and `-` removed, joined with `-`.
const exportName = (...parts: string[]) =>
parts.map((part) => part.replace(/_/g, "-").replace(/[^a-zA-Z0-9:-]/g, "")).join("-");
const problems = runtimes.flatMap(({ name, platformVersion }) => {
const logicalId = logicalIdByExport.get(exportName(artifact.stackName, name, "RuntimeId"));
const resource = logicalId === undefined ? undefined : template.Resources[logicalId];
if (resource === undefined) {
return [
`Could not find runtime '${name}' in the synthesized stack '${artifact.stackName}', so ` +
`deploy cannot check that it runs on "platformVersion": "${platformVersion}".`,
];
}
const synthesized = PlatformVersionPropertiesSchema.safeParse(resource.Properties).data;
if (synthesized?.PlatformVersion === platformVersion) return [];
return [
`Runtime '${name}' has "platformVersion": "${platformVersion}", but the synthesized stack ` +
"does not set it: the @aws/agentcore-cdk in agentcore/cdk does not support platformVersion, " +
"and no released @aws/agentcore-cdk does yet. Deploy again once agentcore/cdk has a " +
"release that does.",
];
});
if (problems.length > 0) throw new ProjectStateError(problems.join("\n"));
}

async function readStackTemplate(
json: ReadWriteJson,
assemblyDirectory: string,
Expand Down
30 changes: 20 additions & 10 deletions src/core/project/boxValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import { ProjectStateError, RegionUnsupportedFeatureError } from "../../errors/errors";
import { isBoxProject, type ProjectSpec } from "../../projectSchemas/project";
import { supportsRuntimeV2 } from "../partition";
import type { ProjectRuntime } from "../../projectSchemas/runtime";
import { BOX_PLATFORM_VERSION, type ProjectRuntime } from "../../projectSchemas/runtime";
import { BOX_RELEASE } from "./backends/boxRelease";
import { BOX_CODEZIP_ENTRYPOINT, runsInBox } from "./templates/boxProfile";

Expand Down Expand Up @@ -103,13 +103,15 @@ export function validateBoxRuntimes(spec: ProjectSpec): void {
}

/**
* Throws for a Box project deployed to a region where AgentCore Runtime has no platformVersion V2,
* when one of its runtimes runs in a box: Box runs only on V2, so that runtime could not be created
* there. A Box project with no runtime is let through, as deploying it is how its stack is removed.
* `target` is a configured target, or, with `provisioning`, the default target deploy is about to
* create in that region; `otherTargets` says whether aws-targets.json has targets to deploy to.
* Throws for a deploy to a region where AgentCore Runtime has no platformVersion V2 when a runtime
* asks for V2 (`"platformVersion": "V2"`): CloudFormation could not create it there, and would fail
* only partway through the deploy. Every runtime of a Box project asks for V2, as the project schema
* requires, so this covers Box runtimes too. A project with no such runtime is let through, an
* empty one included, as deploying it is how its stack is removed. `target` is a configured
* target, or, with `provisioning`, the default target deploy is about to create in that region;
* `otherTargets` says whether aws-targets.json has targets to deploy to.
*/
export function assertBoxRegionSupported(
export function assertRuntimeV2RegionSupported(
spec: ProjectSpec,
target: { name: string; region: string },
{
Expand All @@ -118,7 +120,10 @@ export function assertBoxRegionSupported(
}: { provisioning?: boolean; otherTargets?: boolean } = {},
): void {
if (supportsRuntimeV2(target.region)) return;
if (!spec.runtimes.some((runtime) => runsInBox(isBoxProject(spec), runtime))) return;
const onV2 = spec.runtimes
.filter((runtime) => runtime.platformVersion === BOX_PLATFORM_VERSION)
.map((runtime) => `'${runtime.name}'`);
if (onV2.length === 0) return;
const wayOut = provisioning
? otherTargets
? "Deploy with --region set to a region that has it, or with --target set to a target in " +
Expand All @@ -127,8 +132,13 @@ export function assertBoxRegionSupported(
"agentcore/aws-targets.json, then retry."
: `Change the region of target '${target.name}' in agentcore/aws-targets.json, or deploy ` +
"with --target to a target in another region, then retry.";
const asks = onV2.length === 1 ? "it asks" : "they ask";
const why = isBoxProject(spec)
? "Box runs on AgentCore Runtime V2"
: `${asks} for AgentCore Runtime V2`;
throw new RegionUnsupportedFeatureError(
`Cannot deploy Box project '${spec.name}' to target '${target.name}' in ${target.region}: ` +
`Box runs on AgentCore Runtime V2, which is not available in ${target.region}. ${wayOut}`,
`Cannot deploy runtime ${onV2.join(", ")} of project '${spec.name}' to target ` +
Comment thread
mquang-amazon marked this conversation as resolved.
Resolved
`'${target.name}' in ${target.region}: ${why} ("platformVersion": ` +
`"${BOX_PLATFORM_VERSION}"), which is not available in ${target.region}. ${wayOut}`,
);
}
5 changes: 5 additions & 0 deletions src/core/project/manager.box.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ async function createdProject(
runtimeVersion: "PYTHON_3_14",
protocol: "HTTP",
box: { version: BOX_RELEASE.version },
platformVersion: "V2" as const,
}));
for (const name of runtimes)
await mkdir(join(created.rootPath, "app", name), { recursive: true });
Expand Down Expand Up @@ -233,6 +234,9 @@ describe("agentcore create", () => {
expect((spec.agentCoreGateways ?? []).map(({ name }) => name)).toEqual(
projectType ? ["agent-box-egress"] : [],
);
// Box runs only on AgentCore Runtime V2, so only a box runtime pins it.
const [runtime] = spec.runtimes as { platformVersion?: string }[];
expect(runtime?.platformVersion).toBe(projectType ? "V2" : undefined);
expect(warnings.includes(boxGatewayLogsNotice("agent-box-egress"))).toBe(projectType === "box");
});

Expand Down Expand Up @@ -388,6 +392,7 @@ describe("gateway targets in a Box project", () => {
const spec = await parsedSpec(project);
const search = spec.runtimes.find(({ name }) => name === "search")!;
expect(search.box).toEqual({ version: BOX_RELEASE.version });
expect(search.platformVersion).toBe("V2");
expect(search.entrypoint).toBe("start.py");
expect(spec.agentCoreGateways.find(({ boundRuntime }) => boundRuntime === "search")).toEqual(
expect.objectContaining(boxGatewaySpec("search")),
Expand Down
Loading
Loading