Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,20 @@ import {
type DurableContext,
withDurableExecution,
} from "@aws/durable-execution-sdk-js";
import { LocalDurableTestRunner } from "@aws/durable-execution-sdk-js-testing";
import {
LocalDurableTestRunner,
WaitingOperationStatus,
} from "@aws/durable-execution-sdk-js-testing";
import { AccessDeniedException } from "@aws-sdk/client-bedrock-agentcore";
import { agentcoreSession } from "../session";
import { agentcoreSession } from "..";
import type { AgentcoreSessionConfig } from "../types";
import { FakeAgentcoreClient, metadata, RUNTIME_ARN, throwing } from "./fakes";
import {
answer,
FakeAgentcoreClient,
metadata,
RUNTIME_ARN,
throwing,
} from "./fakes";

beforeAll(() =>
LocalDurableTestRunner.setupTestEnvironment({ skipTime: true }),
Expand Down Expand Up @@ -83,6 +92,9 @@ describe("agentcoreSession", () => {

expect(execution.getStatus()).toBe("FAILED");
expect(execution.getError()?.errorMessage).toContain("handler broke");
// A handler error is not an AgentCore error. So it keeps the type that
// runInChildContext gives it without an error mapper.
expect(execution.getError()?.errorType).toBe("ChildContextError");
// Without a qualifier, the stop input has no qualifier key.
expect(client.stopInputs).toStrictEqual([
{
Expand Down Expand Up @@ -207,3 +219,272 @@ describe("agentcoreSession", () => {
expect(execution.getOperations()).toHaveLength(0);
});
});

/** Waits for the request step of `job`, then completes its callback. */
async function completeJob(
runner: Runner,
job: string,
result: unknown,
): Promise<void> {
await runner
.getOperation(`${job}.request`)
.waitForData(WaitingOperationStatus.COMPLETED);
await runner
.getOperation(`${job}.callback`)
.sendCallbackSuccess(JSON.stringify(result));
}

/** What a caller sees of an error. */
function seen(error: unknown): {
className: string;
errorType: string;
message: string;
} {
const e = error as Error & { errorType: string };
return {
className: e.constructor.name,
errorType: e.errorType,
message: e.message,
};
}

/**
* Runs `run`, which must fail, and returns what it saw on the first run and
* on replay. A step records the first view, and a wait makes the next
* invocation replay the failed operations from the checkpoint.
*/
async function bothViews(
run: (context: DurableContext) => Promise<unknown>,
drive: (runner: Runner) => Promise<void> = async () => {},
): Promise<ReturnType<typeof seen>> {
const runner = runnerFor(async (context) => {
const view = await run(context).then(() => {
throw new Error("the operation did not fail");
}, seen);
const firstRun = await context.step("record", async () => view);
await context.wait("replay", { seconds: 1 });
return { firstRun, replay: view };
});
const executionPromise = runner.run({ payload: {} });
await drive(runner);
const execution = await executionPromise;
expect(execution.getStatus()).toBe("SUCCEEDED");
const views = execution.getResult() as {
firstRun: ReturnType<typeof seen>;
replay: ReturnType<typeof seen>;
};
expect(views.replay).toEqual(views.firstRun);
return views.firstRun;
}

const job = { timeout: { minutes: 5 } };

describe("AgentcoreSession.invoke", () => {
it("runs two jobs in the same session, each with its own callback, and stops the session once", async () => {
const client = new FakeAgentcoreClient();
const runner = runnerFor((context) =>
agentcoreSession(
context,
"review",
sessionConfig(client),
async (session, child) => {
const first = await session.invoke(child, "first", { step: 1 }, job);
const second = await session.invoke(child, "second", first, job);
// The session, not a job, stops the session.
expect(client.stopInputs).toHaveLength(0);
return [first, second];
},
),
);

const executionPromise = runner.run({ payload: {} });
await completeJob(runner, "first", { step: 2 });
await completeJob(runner, "second", { step: 3 });
const execution = await executionPromise;

expect(execution.getStatus()).toBe("SUCCEEDED");
expect(execution.getResult()).toEqual([{ step: 2 }, { step: 3 }]);
const sessionId = runner
.getOperation("review.session")
.getStepDetails()?.result;
expect(client.invokeInputs.map((input) => input.runtimeSessionId)).toEqual([
sessionId,
sessionId,
]);
expect(client.document(0)).toMatchObject({
input: { step: 1 },
callbackId: runner.getOperation("first.callback").getCallbackDetails()
?.callbackId,
});
expect(client.document(1)).toMatchObject({
input: { step: 2 },
callbackId: runner.getOperation("second.callback").getCallbackDetails()
?.callbackId,
});
expect(client.document(1).callbackId).not.toBe(
client.document(0).callbackId,
);
expect(client.stopInputs).toHaveLength(1);
// Each job is a child context named after the job.
expect(
runner
.getOperation("review")
.getChildOperations()
?.map((operation) => operation.getName()),
).toEqual(["review.session", "first", "second", "review.stop"]);
expect(
runner
.getOperation("first")
.getChildOperations()
?.map((operation) => operation.getName()),
).toEqual(["first.callback", "first.request"]);
});

it("creates the job in the context passed to invoke", async () => {
const client = new FakeAgentcoreClient();
const runner = runnerFor((context) =>
agentcoreSession(
context,
"review",
sessionConfig(client),
async (session, child) =>
child.runInChildContext("inner", (inner) =>
session.invoke(inner, "job", {}, job),
),
),
);

const executionPromise = runner.run({ payload: {} });
await completeJob(runner, "job", "ok");
const execution = await executionPromise;

expect(execution.getStatus()).toBe("SUCCEEDED");
expect(execution.getResult()).toBe("ok");
expect(
runner
.getOperation("inner")
.getChildOperations()
?.map((operation) => operation.getName()),
).toEqual(["job"]);
});

it("rejects the job, and the handler can continue in the same session", async () => {
const client = new FakeAgentcoreClient();
const runner = runnerFor((context) =>
agentcoreSession(
context,
"review",
sessionConfig(client),
async (session, child) => {
const failure = await session
.invoke(child, "first", {}, job)
.then(() => undefined, seen);
const second = await session.invoke(child, "second", {}, job);
return { failure, second };
},
),
);

const executionPromise = runner.run({ payload: {} });
await runner
.getOperation("first.request")
.waitForData(WaitingOperationStatus.COMPLETED);
await runner.getOperation("first.callback").sendCallbackFailure({
ErrorType: "ReviewFailed",
ErrorMessage: "3 comments",
});
await completeJob(runner, "second", "ok");
const execution = await executionPromise;

expect(execution.getStatus()).toBe("SUCCEEDED");
expect(execution.getResult()).toEqual({
failure: {
className: "AgentcoreJobFailedError",
errorType: "AgentcoreJobFailedError",
message: expect.stringMatching(
/^AgentCore "first": the job failed \(ReviewFailed\): .*3 comments/,
),
},
second: "ok",
});
expect(client.stopInputs).toHaveLength(1);
});

it.each([
{
error: "AgentcoreJobFailedError",
options: job,
drive: async (runner: Runner) => {
await runner
.getOperation("first.request")
.waitForData(WaitingOperationStatus.COMPLETED);
await runner.getOperation("first.callback").sendCallbackFailure({
ErrorType: "ReviewFailed",
ErrorMessage: "3 comments",
});
},
},
{ error: "AgentcoreTimeoutError", options: { timeout: { seconds: 2 } } },
{
error: "AgentcoreDeliveryError",
options: job,
refuse: true,
},
])(
"reports a job failure that leaves the session as $error",
async ({ error, options, drive, refuse }) => {
const client = new FakeAgentcoreClient();
if (refuse) {
client.invokeResponses = [answer('{"accepted":false}')];
}
const view = await bothViews(
(context) =>
agentcoreSession(
context,
"review",
sessionConfig(client),
async (session, child) =>
session.invoke(child, "first", {}, options),
),
drive,
);

expect(view.className).toBe(error);
expect(view.errorType).toBe(error);
expect(view.message).toMatch(/^AgentCore "first": /);
expect(client.stopInputs).toHaveLength(1);
},
);

it("rejects an input that JSON cannot encode before any durable operation of the job", async () => {
const client = new FakeAgentcoreClient();
const runner = runnerFor((context) =>
agentcoreSession(
context,
"review",
sessionConfig(client),
async (session, child) => {
let promise: Promise<unknown> | undefined;
// The input error rejects the returned promise. It is not thrown.
expect(() => {
promise = session.invoke(child, "first", 1n, job);
}).not.toThrow();
return (promise as Promise<unknown>).then(() => undefined, seen);
},
),
);

const execution = await runner.run({ payload: {} });

expect(execution.getResult()).toMatchObject({
className: "TypeError",
message: expect.stringContaining(
'AgentCore "first": the job input must be JSON-serializable',
),
});
expect(
execution.getOperations().map((operation) => operation.getName()),
).toEqual(["review", "review.session", "review.stop"]);
expect(client.invokeInputs).toHaveLength(0);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ const INPUT_MEMBER_PREFIX = '{"input":';
* @returns The input's JSON text, or `undefined` when the input encodes to
* no value, such as `undefined`. The document then has no `input` field.
*/
function encodeInput(name: string, input: unknown): string | undefined {
export function encodeInput(name: string, input: unknown): string | undefined {
let json: string;
try {
json = JSON.stringify({ input });
Expand Down Expand Up @@ -222,7 +222,7 @@ function encodeInput(name: string, input: unknown): string | undefined {
* test without it. The worker rejects a job document without a Region. So
* the operation fails before any durable operation instead.
*/
function functionRegion(name: string): string {
export function functionRegion(name: string): string {
const region = process.env.AWS_REGION;
if (!region) {
throw new TypeError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
DurableOperationError,
} from "@aws/durable-execution-sdk-js";
import { ComputeError } from "../errors";
import { callerErrorMapper } from "../microvm/errors";

/**
* The base class of every error that {@link agentcore} reports for a failed
Expand Down Expand Up @@ -158,14 +159,33 @@ export async function inStage<T>(
export function agentcoreErrorMapper(
name: string,
): (error: DurableOperationError) => DurableOperationError {
return (error) => {
const Class = CLASSES[error.cause?.name ?? ""];
return Class
? new Class(error.message, error.cause, error.errorData)
: new AgentcoreError(
`AgentCore "${name}": ${error.message}`,
error.cause,
error.errorData,
);
};
return (error) =>
rebuildAgentcoreError(error) ??
new AgentcoreError(
`AgentCore "${name}": ${error.message}`,
error.cause,
error.errorData,
);
}

/**
* The error mapper of `agentcoreSession`. The session handler is caller
* code. So an AgentCore error, such as a failed job that the handler does
* not catch, is restored to its class, and any other error follows
* {@link callerErrorMapper}, as in `microvmSession`.
*/
export function agentcoreSessionErrorMapper(
error: DurableOperationError,
): DurableOperationError {
return rebuildAgentcoreError(error) ?? callerErrorMapper(error);
}

/** Restores an AgentCore error from its checkpointed type, `cause.name`. */
function rebuildAgentcoreError(
error: DurableOperationError,
): AgentcoreError | undefined {
const Class = CLASSES[error.cause?.name ?? ""];
return Class
? new Class(error.message, error.cause, error.errorData)
: undefined;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export {
AgentcoreJobFailedError,
AgentcoreTimeoutError,
} from "./errors";
export { agentcoreSession } from "./session";
export { AgentcoreOperationSubType } from "./subtypes";
export type {
AgentcoreConfig,
Expand Down
Loading