The Open Framework for Building Agents
perf(eve): overlap title attribute persistence (#4452)
Casey Gowrie90972b6f5782
diff --git a/.changeset/fast-title-metadata.md b/.changeset/fast-title-metadata.mdnew file mode 100644index 000000000..504a65b9d--- /dev/null+++ b/.changeset/fast-title-metadata.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Start the first model call without waiting for session-title metadata persistence, while still completing the title write before the durable turn step finishes.diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex a3bdf729d..0bad10795 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -77,6 +77,7 @@ interface CreateExecutionNodeStepInput {readonly historyProjector?: HistoryViewProjector;readonly historyView?: PreparedHistoryView;readonly instrumentation: ExecutionInstrumentation | undefined;+ readonly titleAttributeWrite?: ToolLoopHarnessConfig["titleAttributeWrite"];readonly modelResolutionScope: RuntimeModelResolutionScope;readonly node: ResolvedRuntimeAgentNode;}@@ -119,6 +120,7 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): StresolveModel,runtimeIdentity: buildRuntimeIdentity(input.node),tools,+ titleAttributeWrite: input.titleAttributeWrite,});if (instrumentation === undefined) return step;return async (session, stepInput) => {diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex 637ea8e91..f0429d18c 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -21,6 +21,7 @@ import {SessionDynamicToolRuntimeRevisionKey,ParentSessionKey,SessionIdKey,+ SessionTitleKey,SessionTraceSeedKey,TraceRootKey,TurnDynamicToolMetadataKey,@@ -69,6 +70,7 @@ import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.import type { TurnStepInput, TurnStepPayload } from "#execution/session/turn-step-types.js";import type { DeliverHookPayload } from "#channel/types.js";import type { RuntimeActionResult } from "#shared/action-types.js";+import { setEveAttributes } from "#runtime/attributes/emit.js";type LegacyStepPayload =| DeliverHookPayload@@ -819,6 +821,81 @@ describe("dispatchCoordinationStep", () => {});describe("turnStep", () => {+ it("starts model work before the title attribute write settles and joins it before returning", async () => {+ let finishTitle!: () => void;+ vi.mocked(setEveAttributes)+ .mockReset()+ .mockReturnValue(+ new Promise<void>((resolve) => {+ finishTitle = resolve;+ }),+ );+ installSessionStoreMocks([createStubSession()]);+ const execute = vi.fn(async (session: HarnessSession): Promise<StepResult> => {+ expect(loadContext().get(SessionTitleKey)).toBe("Start the quarterly report");+ return { next: { done: true, output: "complete" }, session };+ });+ vi.mocked(createExecutionNodeStep).mockImplementation((input) => {+ expect(input.titleAttributeWrite).toBeDefined();+ return execute;+ });++ let settled = false;+ const result = turnStep({+ input: { kind: "deliver", payloads: [{ message: "Start the quarterly report" }] },+ sessionWritable: createTestWritable(),+ serializedContext: createSerializedContext(),+ sessionState: createStubSessionState(),+ }).then((value) => {+ settled = true;+ return value;+ });++ await vi.waitFor(() => expect(execute).toHaveBeenCalledOnce());+ expect(setEveAttributes).toHaveBeenCalledWith({+ "$eve.title": "Start the quarterly report",+ });+ expect(settled).toBe(false);+ finishTitle();++ await expect(result).resolves.toMatchObject({ action: "done", output: "complete" });+ });++ it("joins the title attribute write before propagating a harness failure", async () => {+ let finishTitle!: () => void;+ vi.mocked(setEveAttributes)+ .mockReset()+ .mockReturnValue(+ new Promise<void>((resolve) => {+ finishTitle = resolve;+ }),+ );+ installSessionStoreMocks([createStubSession()]);+ const failure = new Error("model failed");+ const execute = vi.fn(async (): Promise<StepResult> => {+ throw failure;+ });+ vi.mocked(createExecutionNodeStep).mockImplementation(() => execute);++ let rejected = false;+ const result = turnStep({+ input: { kind: "deliver", payloads: [{ message: "Start the quarterly report" }] },+ sessionWritable: createTestWritable(),+ serializedContext: createSerializedContext(),+ sessionState: createStubSessionState(),+ }).catch((error: unknown) => {+ rejected = true;+ throw error;+ });++ await vi.waitFor(() => expect(execute).toHaveBeenCalledOnce());+ await Promise.resolve();+ expect(rejected).toBe(false);+ finishTitle();++ await expect(result).rejects.toBe(failure);+ });+it("resumes an interrupted turn when the channel ignores the correction", async () => {const originalAuth: SessionAuthContext = {attributes: {},diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.tsindex 34b4d229c..427c6afc6 100644--- a/packages/eve/src/execution/session/turn-step.ts+++ b/packages/eve/src/execution/session/turn-step.ts@@ -92,6 +92,10 @@ function channelDeliveryErrorCode(error: unknown): string {export type { TurnStepInput };+interface PendingStepAttributes {+ title?: Promise<void>;+}+/** Runs a bounded batch of harness model steps inside one durable `"use step"` boundary. */export async function turnStep(input: TurnStepInput): Promise<TurnStepResult> {"use step";@@ -104,6 +108,18 @@ export async function turnStep(input: TurnStepInput): Promise<TurnStepResult> {}async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult> {+ const pendingAttributes: PendingStepAttributes = {};+ try {+ return await runSessionStepBody(input, pendingAttributes);+ } finally {+ await pendingAttributes.title;+ }+}++async function runSessionStepBody(+ input: TurnStepInput,+ pendingAttributes: PendingStepAttributes,+): Promise<DurableStepResult> {// The delivery as accepted, before authorization callbacks are matched out of it.const rawDelivery = input.input?.delivery;let delivery = rawDelivery;@@ -199,7 +215,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>const title = deriveSessionTitle(rawDelivery?.title ?? message);if (title !== undefined) {ctx.set(SessionTitleKey, title);- await setEveAttributes({ "$eve.title": title });+ pendingAttributes.title = setEveAttributes({ "$eve.title": title });}}@@ -467,6 +483,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>nodeId: bundle.nodeId,},node: effectiveNode,+ titleAttributeWrite: pendingAttributes.title,});return step(modelSession, stepInput);};diff --git a/packages/eve/src/harness/model-call/usage.ts b/packages/eve/src/harness/model-call/usage.tsindex 4f5b47188..1888e6f32 100644--- a/packages/eve/src/harness/model-call/usage.ts+++ b/packages/eve/src/harness/model-call/usage.ts@@ -80,7 +80,7 @@ export async function recordModelUsage(}),});step.session = setTurnUsageState(step.session, usage);- await setEveAttributes({+ const attributes = {"$eve.model": gatewayModelId(input.model),"$eve.input_tokens": usage.inputTokens,"$eve.output_tokens": usage.outputTokens,@@ -88,5 +88,7 @@ export async function recordModelUsage("$eve.cache_write_tokens": usage.cacheWriteTokens,"$eve.cost_usd": usage.sawCost ? usage.costUsd : undefined,"$eve.tool_count": step.config.tools.size,- });+ };+ await step.config.titleAttributeWrite;+ await setEveAttributes(attributes);}diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex 63f514c52..d55b52c23 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -304,6 +304,8 @@ export interface ToolLoopHarnessConfig {* Omitted in production until an instrumentation runtime opts in.*/readonly instrumentation?: SessionInstrumentation;+ /** Attribute work that must finish before cumulative model usage is persisted. */+ readonly titleAttributeWrite?: Promise<void>;/*** Sign-in callbacks the step's delivery carried. Each completes before anything else runs, and* a connection's sign-in resumes the turn that asked for it.