This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/texera.git
The following commit(s) were added to refs/heads/main by this push:
new af586679fc fix(agent-service): classify error-prefixed tool results as
failed (#9259)
af586679fc is described below
commit af586679fcd5244c16037b1cc86d28db5d79e5f8
Author: oliarmak-web <[email protected]>
AuthorDate: Wed Nov 18 19:00:51 2026 +0000
fix(agent-service): classify error-prefixed tool results as failed (#9259)
### What changes were proposed in this PR?
Tool failures returned as `[ERROR]` strings and SDK-generated
`tool-error` parts must be persisted as failures so subsequent agent
turns receive the correct status. This change builds stored results from
step content, matches results to calls by `toolCallId`, and reuses
normalized failure status to prevent delegate execution after rejected
modifications. A shared `isErrorResult` predicate keeps string
classification beside `createErrorResult`.
Thrown errors are stored as readable messages so they survive JSON
snapshots and appear in subsequent context. Calls without a recorded
result are marked failed. History formatting uses the normalized
`isError` flag.
Regression coverage includes error-prefixed output, SDK-rejected calls,
reordered results, throwing tools (Error, string and null values),
length-limited calls that never execute, and suppression of execution
after rejected modifications.
### Any related issues, documentation, discussions?
Closes #9120
Related: #9244, whose tool-history presentation relies on accurate
persisted failure status.
### How was this PR tested?
From `agent-service`:
- `bun test`: 347 passed, 0 failed
- `bun run typecheck`: passed
- `bun run format:check`: passed
- `git diff --check`: passed
The new behavior assertions reproduced the failures before the
production fix. Validation used Bun 1.3.3 and the repository’s frozen
lockfile. The full test run required local socket access for the server
tests. GitHub CI results remain separate from these local checks.
### Was this PR authored or co-authored using generative AI tooling?
Generated-by: OpenAI Codex
---
agent-service/src/agent/texera-agent.spec.ts | 102 +++++++++++++++++++--
agent-service/src/agent/texera-agent.ts | 32 ++++---
.../src/agent/tools/tools-utility.spec.ts | 12 +++
agent-service/src/agent/tools/tools-utility.ts | 4 +
agent-service/src/agent/util/context-utils.spec.ts | 32 ++-----
agent-service/src/agent/util/context-utils.ts | 11 +--
6 files changed, 141 insertions(+), 52 deletions(-)
diff --git a/agent-service/src/agent/texera-agent.spec.ts
b/agent-service/src/agent/texera-agent.spec.ts
index c7ff415151..a1644921cf 100644
--- a/agent-service/src/agent/texera-agent.spec.ts
+++ b/agent-service/src/agent/texera-agent.spec.ts
@@ -367,7 +367,7 @@ describe("TexeraAgent DAG result formatting", () => {
* LanguageModelV4FinishReason is an object, not a string: a bare
`finishReason: "stop"` runs fine
* under `bun test` but fails `tsc --noEmit`, so the mocks below build it
through here.
*/
-const finish = (unified: "stop" | "tool-calls") => ({ unified, raw: undefined
});
+const finish = (unified: "stop" | "tool-calls" | "length") => ({ unified, raw:
undefined });
/**
* LanguageModelV4Usage is nested. A flat `{ inputTokens: 11 }` is silently
discarded, and every
@@ -537,7 +537,7 @@ describe("sendMessage", () => {
{ toolName: "deleteOperator", toolCallId: "c1", input: { operatorId:
"ghost" } },
]);
expect(steps[1].toolResults).toEqual([
- { toolCallId: "c1", output: "[ERROR] Operator ghost not found", isError:
false },
+ { toolCallId: "c1", output: "[ERROR] Operator ghost not found", isError:
true },
]);
expect(steps[1].content).toBe("");
expect(steps.map(s => [s.stepId, s.isBegin, s.isEnd])).toEqual([
@@ -546,6 +546,7 @@ describe("sendMessage", () => {
[2, false, true],
]);
expect(steps[2].parentId).toBe(steps[1].id);
+ expect(steps[2].inputMessages?.[0]?.content).toContain("- deleteOperator
(failed)");
expect(urls).toEqual([]);
});
@@ -583,14 +584,97 @@ describe("sendMessage", () => {
return { ok: true, json: async () => ({ operatorOutputSchemas: {},
operatorErrors: {} }) } as any;
}) as any);
await agent.sendMessage("del");
- const counts = agent
- .getAllSteps()
- .map(s => [s.role, s.beforeWorkflowContent?.operators.length,
s.afterWorkflowContent?.operators.length]);
+ const steps = agent.getAllSteps();
+ const counts = steps.map(s => [
+ s.role,
+ s.beforeWorkflowContent?.operators.length,
+ s.afterWorkflowContent?.operators.length,
+ ]);
expect(counts).toEqual([
["user", 1, 1],
["agent", 1, 0],
["agent", 0, 0],
]);
+ expect(steps[1].toolResults).toEqual([{ toolCallId: "c1", output: "Deleted
operator: op1", isError: false }]);
+ expect(steps[2].inputMessages?.[0]?.content).toContain("- deleteOperator
(succeeded)");
+ });
+
+ test.each([new Error("The operation was aborted."), "tool failed", null])(
+ "preserves a thrown tool error in stored JSON and subsequent context: %p",
+ async thrown => {
+ let n = 0;
+ const model = new MockLanguageModelV4({
+ doGenerate: async () => {
+ n++;
+ return {
+ content:
+ n === 1
+ ? [
+ {
+ type: "tool-call",
+ toolCallId: "c1",
+ toolName: "deleteOperator",
+ input: JSON.stringify({ operatorId: "ghost" }),
+ },
+ ]
+ : [{ type: "text", text: "done" }],
+ finishReason: finish(n === 1 ? "tool-calls" : "stop"),
+ usage: usage(1, 1),
+ warnings: [],
+ } as any;
+ },
+ });
+ const agent = makeAgentWith(model);
+ const throwingTool = spyOn((agent as any).tools.deleteOperator,
"execute").mockImplementation(async () => {
+ throw thrown;
+ });
+ try {
+ await agent.sendMessage("delete it");
+ const steps = agent.getAllSteps();
+ const expected = thrown instanceof Error ? thrown.message :
String(thrown);
+ expect(steps[1].toolResults).toEqual([{ toolCallId: "c1", output:
expected, isError: true }]);
+
expect(JSON.parse(JSON.stringify(steps))[1].toolResults[0].output).toBe(expected);
+ expect(steps[2].inputMessages?.[0]?.content).toContain(` - Error:\n
${expected}`);
+ } finally {
+ throwingTool.mockRestore();
+ }
+ }
+ );
+
+ test("a length-limited tool call is not executed and appears as failed on
the next turn", async () => {
+ let n = 0;
+ const model = new MockLanguageModelV4({
+ doGenerate: async () => {
+ n++;
+ return {
+ content:
+ n === 1
+ ? [
+ {
+ type: "tool-call",
+ toolCallId: "c1",
+ toolName: "deleteOperator",
+ input: JSON.stringify({ operatorId: "ghost" }),
+ },
+ ]
+ : [{ type: "text", text: "done" }],
+ finishReason: finish(n === 1 ? "length" : "stop"),
+ usage: usage(1, 1),
+ warnings: [],
+ } as any;
+ },
+ });
+ const agent = makeAgentWith(model);
+ const execute = spyOn((agent as any).tools.deleteOperator, "execute");
+ try {
+ await agent.sendMessage("delete it");
+ expect(execute).not.toHaveBeenCalled();
+ expect(agent.getAllSteps()[1].toolResults).toEqual([]);
+ await agent.sendMessage("continue");
+
expect(agent.getAllSteps().at(-1)?.inputMessages?.[0]?.content).toContain("-
deleteOperator (failed)");
+ } finally {
+ execute.mockRestore();
+ }
});
test("leaves disabled tools out of the model call but still lists them",
async () => {
@@ -1127,9 +1211,7 @@ describe("delegate mode", () => {
}
});
- test("a tool call missing operatorId does not trigger a whole-workflow run",
async () => {
- // Without the guard an incomplete tool call falls through to a run of the
entire workflow, which is
- // both expensive and not what was asked for.
+ test("an SDK-rejected modifyOperator is recorded as failed and does not
run", async () => {
dispatch(okExec);
let n = 0;
const model = new MockLanguageModelV4({
@@ -1154,7 +1236,9 @@ describe("delegate mode", () => {
agent.setDelegateConfig({ userToken: "tok", workflowId: 7 });
await agent.sendMessage("bad call");
const step = agent.getAllSteps()[1];
- expect(step.toolResults).toEqual([]);
+ expect(step.toolResults).toHaveLength(1);
+ expect(step.toolResults?.[0]).toMatchObject({ toolCallId: "c1", isError:
true });
+ expect(agent.getAllSteps()[2].inputMessages?.[0]?.content).toContain("-
modifyOperator (failed)");
expect(urls.some(u => u.includes("/api/execution/"))).toBe(false);
});
diff --git a/agent-service/src/agent/texera-agent.ts
b/agent-service/src/agent/texera-agent.ts
index 25a7ea8805..555cc2730f 100644
--- a/agent-service/src/agent/texera-agent.ts
+++ b/agent-service/src/agent/texera-agent.ts
@@ -51,6 +51,7 @@ import { assembleContext } from "./util/context-utils";
import { compileWorkflowAsync, type WorkflowCompilationResponse } from
"../api/compile-api";
import { createLogger } from "../logger";
import type { Logger } from "pino";
+import { isErrorResult } from "./tools/tools-utility";
const PERSIST_DEBOUNCE_MS = 500;
@@ -587,7 +588,7 @@ export class TexeraAgent {
anthropic: { disableParallelToolUse: true },
mistral: { parallelToolCalls: false },
},
- onStepFinish: async ({ text, toolCalls, toolResults, usage }) => {
+ onStepFinish: async ({ text, toolCalls, content, usage }) => {
stepIndex++;
const formattedToolCalls = toolCalls?.map(tc => ({
@@ -596,11 +597,19 @@ export class TexeraAgent {
input: tc.input,
}));
- const formattedToolResults = toolResults?.map(tr => ({
- toolCallId: tr.toolCallId,
- output: tr.output,
- isError: !!(tr.output as any)?.error,
- }));
+ const formattedToolResults = content
+ .filter(part => part.type === "tool-result" || part.type ===
"tool-error")
+ .map(part => ({
+ toolCallId: part.toolCallId,
+ output:
+ part.type === "tool-error"
+ ? part.error instanceof Error
+ ? part.error.message
+ : String(part.error)
+ : part.output,
+ isError: part.type === "tool-error" ||
isErrorResult(part.output),
+ }));
+ const toolResultsByCallId = new Map(formattedToolResults.map(result
=> [result.toolCallId, result]));
const afterStepContent = this.workflowState.getWorkflowContent();
@@ -633,16 +642,13 @@ export class TexeraAgent {
this.head = agentStepId;
const execConfig = this.buildExecutionConfig();
- if (execConfig && toolCalls && toolResults) {
+ if (execConfig && toolCalls) {
const EXECUTE_AFTER_TOOLS = new Set([TOOL_NAME_ADD_OPERATOR,
TOOL_NAME_MODIFY_OPERATOR]);
- for (let i = 0; i < toolCalls.length; i++) {
- const tc = toolCalls[i];
- const tr = toolResults[i];
+ for (const tc of toolCalls) {
+ const tr = toolResultsByCallId.get(tc.toolCallId);
if (!EXECUTE_AFTER_TOOLS.has(tc.toolName)) continue;
-
- const resultText = typeof tr?.output === "string" ? tr.output :
String(tr?.output ?? "");
- if (resultText.startsWith("[ERROR]")) continue;
+ if (!tr || tr.isError) continue;
const operatorId = (tc.input as any)?.operatorId;
if (!operatorId) continue;
diff --git a/agent-service/src/agent/tools/tools-utility.spec.ts
b/agent-service/src/agent/tools/tools-utility.spec.ts
index d0dc43182e..f5a19fcb44 100644
--- a/agent-service/src/agent/tools/tools-utility.spec.ts
+++ b/agent-service/src/agent/tools/tools-utility.spec.ts
@@ -30,6 +30,7 @@ import {
getOperatorErrorText,
tupleColumns,
tupleToRecord,
+ isErrorResult,
} from "./tools-utility";
import {
OperatorState,
@@ -197,6 +198,17 @@ describe("createErrorResult", () => {
});
});
+describe("isErrorResult", () => {
+ test("recognizes output produced by createErrorResult", () => {
+ expect(isErrorResult(createErrorResult("boom"))).toBe(true);
+ });
+
+ test("does not classify ordinary strings or non-string output as errors", ()
=> {
+ expect(isErrorResult("ok")).toBe(false);
+ expect(isErrorResult({ error: "boom" })).toBe(false);
+ });
+});
+
describe("formatExecuteOperatorResult", () => {
test("renders the operator id in the standard executed message", () => {
expect(formatExecuteOperatorResult("op-1")).toBe("Executed operator op-1");
diff --git a/agent-service/src/agent/tools/tools-utility.ts
b/agent-service/src/agent/tools/tools-utility.ts
index 867fa2b11c..4b08adfb10 100644
--- a/agent-service/src/agent/tools/tools-utility.ts
+++ b/agent-service/src/agent/tools/tools-utility.ts
@@ -180,6 +180,10 @@ export function createErrorResult(error: string): string {
return `[ERROR] ${error}`;
}
+export function isErrorResult(output: unknown): boolean {
+ return typeof output === "string" && output.startsWith("[ERROR]");
+}
+
function formatLinkDescription(sourceOperatorId: string, targetOperatorId:
string): string {
return `${sourceOperatorId} --> ${targetOperatorId}`;
}
diff --git a/agent-service/src/agent/util/context-utils.spec.ts
b/agent-service/src/agent/util/context-utils.spec.ts
index 92362ec9a3..83e82d278d 100644
--- a/agent-service/src/agent/util/context-utils.spec.ts
+++ b/agent-service/src/agent/util/context-utils.spec.ts
@@ -112,7 +112,7 @@ describe("assembleContext", () => {
expect(content).toContain("### Turn 2");
});
- test("labels each tool call with the status of the result at the same
index", () => {
+ test("labels each tool call with the status of its result by toolCallId", ()
=> {
const agentStep: ReActStep = {
...step("m1", "agent", 1, "acting", true),
toolCalls: [
@@ -120,11 +120,10 @@ describe("assembleContext", () => {
{ toolName: "executeOperator", toolCallId: "c2", input: {} },
{ toolName: "deleteOperator", toolCallId: "c3", input: {} },
],
- // Deliberately shorter than toolCalls: a call still awaiting its result
- // must not be reported as failed.
+ // Results are deliberately out of call order, and the third call was
never executed.
toolResults: [
- { toolCallId: "c1", output: "ok" },
{ toolCallId: "c2", output: "bad", isError: true },
+ { toolCallId: "c1", output: "ok" },
],
};
const content = contentOf(
@@ -132,7 +131,7 @@ describe("assembleContext", () => {
);
expect(content).toContain("- addOperator (succeeded)");
expect(content).toContain("- executeOperator (failed)");
- expect(content).toContain("- deleteOperator (succeeded)");
+ expect(content).toContain("- deleteOperator (failed)");
});
test("writes each past call's summary and result under it, so a failed call
is not repeated blindly", () => {
@@ -165,31 +164,16 @@ describe("assembleContext", () => {
" - Error:",
' [ERROR] Source operator "op7" not found',
" at resolveInputLinks",
- // No result recorded (a call the SDK rejected): only the call itself.
- "- deleteOperator (succeeded)",
+ // A call the SDK never executed has no result.
+ "- deleteOperator (failed)",
].join("\n")
);
// The operator's data stays in the dataflow section, not in the history.
expect(content).not.toContain("| a | b |");
});
- test("an [ERROR] result not flagged as an error still gets its whole message
as an Error block", () => {
- // Tool errors are "[ERROR] ..." strings and isError is not set for them
yet (#9120); an execution
- // error spans several lines, and its reason is only on the later ones.
- const agentStep: ReActStep = {
- ...step("m1", "agent", 1, "acting", true),
- toolCalls: [{ toolName: "executeOperator", toolCallId: "c1", input: {
operatorId: "op8" } }],
- toolResults: [{ toolCallId: "c1", output: "[ERROR] Operator op8:\nInput
port 0 has no link" }],
- };
- const content = contentOf(
- assembleContext([step("m1", "user", 0, "req", true), agentStep], new
WorkflowState(), new Map())
- );
- expect(content).toContain([" - Error:", " [ERROR] Operator op8:", "
Input port 0 has no link"].join("\n"));
- expect(content).not.toContain(" - Output: [ERROR]");
- });
-
test("matches results to calls by toolCallId, not by position", () => {
- // A call the SDK rejected has no result, so positions can shift.
+ // A call the SDK never executed has no result, so positions can shift.
const agentStep: ReActStep = {
...step("m1", "agent", 1, "acting", true),
toolCalls: [
@@ -202,7 +186,7 @@ describe("assembleContext", () => {
assembleContext([step("m1", "user", 0, "req", true), agentStep], new
WorkflowState(), new Map())
);
expect(content).toContain(
- ["- addOperator (succeeded)", "- deleteOperator (succeeded)", " -
Output: Deleted operator op0"].join("\n")
+ ["- addOperator (failed)", "- deleteOperator (succeeded)", " - Output:
Deleted operator op0"].join("\n")
);
});
});
diff --git a/agent-service/src/agent/util/context-utils.ts
b/agent-service/src/agent/util/context-utils.ts
index 3d5e5ee5ea..f5078e2706 100644
--- a/agent-service/src/agent/util/context-utils.ts
+++ b/agent-service/src/agent/util/context-utils.ts
@@ -122,10 +122,10 @@ function serializeTask(steps: ReActStep[], status:
"completed" | "ongoing"): str
lines.push(`Thought: ${step.content}`);
}
if (step.toolCalls && step.toolCalls.length > 0) {
- for (let i = 0; i < step.toolCalls.length; i++) {
- const tc = step.toolCalls[i];
- const tr = step.toolResults?.find(r => r.toolCallId === tc.toolCallId);
- const statusAttr = tr?.isError ? "failed" : "succeeded";
+ const toolResultsByCallId = new Map(step.toolResults?.map(result =>
[result.toolCallId, result]));
+ for (const tc of step.toolCalls) {
+ const tr = toolResultsByCallId.get(tc.toolCallId);
+ const statusAttr = !tr || tr.isError ? "failed" : "succeeded";
lines.push(`- ${tc.toolName} (${statusAttr})`);
lines.push(...serializeToolCallDetails(tc.input, tr));
}
@@ -150,8 +150,7 @@ function serializeToolCallDetails(input: any, result: {
output: any; isError?: b
if (!result) return lines;
const text = typeof result.output === "string" ? result.output :
JSON.stringify(result.output);
if (text === undefined || text === "") return lines;
- // Tool errors come back as "[ERROR] ..." strings, so the marker counts as
well as isError.
- if (result.isError || text.startsWith("[ERROR]")) {
+ if (result.isError) {
lines.push(" - Error:");
lines.push(...text.split("\n").map(line => ` ${line}`));
} else {