This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-9252-3f9bdd481a4015657e485e0e345942b72381c9e6
in repository https://gitbox.apache.org/repos/asf/texera.git

commit 8f0fe35538ceefe34860b1927b77affd74f72595
Author: Xinyuan Lin <[email protected]>
AuthorDate: Wed Nov 4 06:21:06 2026 +0000

    refactor(agent-service): deduplicate result formatting helpers (#9252)
    
    ### What changes were proposed in this PR?
    
    Deduplicates result formatting logic between
    `agent-service/src/agent/tools/result-formatting.ts` and
    `workflow-execution-tools.ts`:
    - Exports `formatInputOutputMetadata` and `jsonToTableFormat` from
    `result-formatting.ts`.
    - Replaces duplicate private implementations `formatInputOutput` and
    `jsonToTableFormat` in `workflow-execution-tools.ts` with direct imports
    from `./result-formatting`.
    - Adds direct unit tests in `result-formatting.spec.ts` covering
    `formatInputOutputMetadata` (shape formatting, upstream link resolution,
    port sorting) and `jsonToTableFormat` (empty cases, TSV formatting with
    index column).
    
    ### Any related issues, documentation, discussions?
    
    Closes #9250
    
    ### How was this PR tested?
    
    - Target test suites:
      ```bash
    bun test src/agent/tools/workflow-execution-tools.spec.ts
    src/agent/tools/result-formatting.spec.ts
      ```
      Output: 54 pass, 0 fail (119 expect() calls, 203ms).
    - Full `agent-service` test suite:
      ```bash
      bun test
      ```
      Output: 317 pass, 0 fail (772 expect() calls, 2.14s).
    - Type checking:
      ```bash
      bun run typecheck
      ```
      Output: `tsc --noEmit` clean.
    - Code style formatting:
      ```bash
      bun run format:check
      ```
      Output: All matched files use Prettier code style.
    - Mutation test:
    Mutated `formatInputOutputMetadata` shape output in
    `result-formatting.ts`; verified 5 tests in
    `workflow-execution-tools.spec.ts` failed as expected, then restored
    clean.
---
 .../src/agent/tools/result-formatting.spec.ts      |  96 +++++++++++++++-
 agent-service/src/agent/tools/result-formatting.ts |  50 ++++++++-
 .../src/agent/tools/workflow-execution-tools.ts    | 124 +--------------------
 3 files changed, 144 insertions(+), 126 deletions(-)

diff --git a/agent-service/src/agent/tools/result-formatting.spec.ts 
b/agent-service/src/agent/tools/result-formatting.spec.ts
index e6d1afdf2e..60eeb2cd92 100644
--- a/agent-service/src/agent/tools/result-formatting.spec.ts
+++ b/agent-service/src/agent/tools/result-formatting.spec.ts
@@ -18,7 +18,7 @@
  */
 
 import { describe, expect, test } from "bun:test";
-import { formatOperatorResult } from "./result-formatting";
+import { formatOperatorResult, formatInputOutputMetadata, jsonToTableFormat } 
from "./result-formatting";
 import { WorkflowState } from "../workflow-state";
 import type { OperatorInfo } from "../../types/execution";
 import type { OperatorPredicate, OperatorLink, PortDescription } from 
"../../types/workflow";
@@ -341,3 +341,97 @@ describe("jsonToTableFormat - row index gaps", () => {
     expect(out.endsWith("9\tz")).toBe(true);
   });
 });
+
+describe("formatInputOutputMetadata", () => {
+  test("returns only output shape when inputPortShapes is empty or undefined", 
() => {
+    const opInfo = makeOpInfo({ outputTuples: 5 });
+    expect(formatInputOutputMetadata(EMPTY_STATE, "op1", opInfo, 
3)).toBe("Output table shape: (5, 3)");
+  });
+
+  test("resolves upstream operators and sorts input ports by index", () => {
+    const state = new WorkflowState();
+    state.addOperator(makeOperator("src0"));
+    state.addOperator(makeOperator("src1"));
+    state.addOperator(makeOperator("op1", ["in-0", "in-1"]));
+    state.addLink(makeLink("l0", ["src0", "output-0"], ["op1", "in-0"]));
+    state.addLink(makeLink("l1", ["src1", "output-0"], ["op1", "in-1"]));
+
+    const opInfo = makeOpInfo({
+      totalRowCount: 10,
+      inputPortShapes: [
+        { portIndex: 1, rows: 20, columns: 2 },
+        { portIndex: 0, rows: 30, columns: 4 },
+      ],
+    });
+
+    const out = formatInputOutputMetadata(state, "op1", opInfo, 5);
+    expect(out).toBe("Input operator(table shape): src0(30, 4), src1(20, 
2)\nOutput table shape: (10, 5)");
+  });
+});
+
+describe("jsonToTableFormat", () => {
+  test("returns empty string for empty array or rows with no visible headers", 
() => {
+    expect(jsonToTableFormat([])).toBe("");
+    expect(jsonToTableFormat([{ __row_index__: 0, __is_visualization__: true 
}])).toBe("");
+  });
+
+  test("formats tab-separated header and row values with index column", () => {
+    const rows = [
+      { colA: "val1", colB: 10, colC: null, colD: true },
+      { colA: "line\nbreak", colB: 20, colC: "NULL", colD: false },
+    ];
+    const out = jsonToTableFormat(rows);
+    const lines = out.split("\n");
+    expect(lines[0]).toBe("\tcolA\tcolB\tcolC\tcolD");
+    expect(lines[1]).toBe("0\tval1\t10\tNaN\ttrue");
+    expect(lines[2]).toBe("1\tline\\nbreak\t20\tNaN\tfalse");
+  });
+});
+
+describe("formatOperatorResult - charLimit truncation", () => {
+  const rows = Array.from({ length: 100 }, (_, i) => ({ a: i, b: 
"x".repeat(20) }));
+
+  test("without charLimit keeps every row", () => {
+    const out = formatOperatorResult("op1", makeOpInfo({ outputTuples: 100, 
result: rows }), EMPTY_STATE);
+    expect(out).toContain("\n0\t0\t");
+    expect(out).toContain("\n50\t50\t");
+    expect(out).toContain("\n99\t99\t");
+  });
+
+  test("charLimit keeps head and tail rows and drops the middle", () => {
+    const out = formatOperatorResult("op1", makeOpInfo({ outputTuples: 100, 
result: rows }), EMPTY_STATE, 300);
+    expect(out).toContain("Output table shape: (100, 2)");
+    expect(out).toContain("\ta\tb");
+    expect(out).toContain("\n0\t0\t");
+    expect(out).toContain("\n99\t99\t");
+    expect(out).not.toContain("\n50\t50\t");
+  });
+
+  test("charLimit larger than the table leaves it untouched", () => {
+    const full = formatOperatorResult("op1", makeOpInfo({ outputTuples: 100, 
result: rows }), EMPTY_STATE);
+    const limited = formatOperatorResult(
+      "op1",
+      makeOpInfo({ outputTuples: 100, result: rows }),
+      EMPTY_STATE,
+      1_000_000
+    );
+    expect(limited).toBe(full);
+  });
+
+  test("tiny charLimit still keeps at least one row", () => {
+    const out = formatOperatorResult("op1", makeOpInfo({ outputTuples: 100, 
result: rows }), EMPTY_STATE, 1);
+    expect(out).toContain("\n0\t0\t");
+  });
+
+  test("visualization content is skipped even when charLimit is set", () => {
+    const html = "<html>" + "y".repeat(5000) + "</html>";
+    const out = formatOperatorResult(
+      "op1",
+      makeOpInfo({ outputTuples: 1, result: [{ __is_visualization__: true, 
"html-content": html }] }),
+      EMPTY_STATE,
+      100_000
+    );
+    expect(out).not.toContain("<html>");
+    expect(out).toContain("<skipped: visualization content>");
+  });
+});
diff --git a/agent-service/src/agent/tools/result-formatting.ts 
b/agent-service/src/agent/tools/result-formatting.ts
index 5ed4aacc5d..f867b8d1db 100644
--- a/agent-service/src/agent/tools/result-formatting.ts
+++ b/agent-service/src/agent/tools/result-formatting.ts
@@ -21,7 +21,45 @@ import type { OperatorInfo } from "../../types/execution";
 import type { WorkflowState } from "../workflow-state";
 import { formatExecuteOperatorResult, getVisibleResultHeaders } from 
"./tools-utility";
 
-export function formatOperatorResult(operatorId: string, opInfo: OperatorInfo, 
workflowState: WorkflowState): string {
+/**
+ * Keeps the header plus as many head and tail rows as fit in `charLimit`,
+ * always retaining at least one row.
+ */
+function truncateTable(dataString: string, charLimit: number): string {
+  if (dataString.length <= charLimit) return dataString;
+
+  const allLines = dataString.split("\n");
+  const headerLine = allLines[0];
+  const dataRows = allLines.slice(1);
+  const halfLimit = Math.floor((charLimit - (headerLine.length + 1)) / 2);
+
+  let frontSize = 0;
+  const frontRows: string[] = [];
+  for (const row of dataRows) {
+    const rowLen = row.length + 1;
+    if (frontSize + rowLen > halfLimit && frontRows.length > 0) break;
+    frontRows.push(row);
+    frontSize += rowLen;
+  }
+
+  let backSize = 0;
+  const backRows: string[] = [];
+  for (let i = dataRows.length - 1; i >= frontRows.length; i--) {
+    const rowLen = dataRows[i].length + 1;
+    if (backSize + rowLen > halfLimit && backRows.length > 0) break;
+    backRows.unshift(dataRows[i]);
+    backSize += rowLen;
+  }
+
+  return [headerLine, ...frontRows, ...backRows].join("\n");
+}
+
+export function formatOperatorResult(
+  operatorId: string,
+  opInfo: OperatorInfo,
+  workflowState: WorkflowState,
+  charLimit?: number
+): string {
   if (opInfo.error) {
     return `[ERROR] ${opInfo.error}`;
   }
@@ -50,7 +88,10 @@ export function formatOperatorResult(operatorId: string, 
opInfo: OperatorInfo, w
       })
     : jsonArray;
 
-  const dataString = jsonToTableFormat(serializableArray);
+  let dataString = jsonToTableFormat(serializableArray);
+  if (charLimit !== undefined) {
+    dataString = truncateTable(dataString, charLimit);
+  }
 
   const metadataLines = [
     formatInputOutputMetadata(workflowState, operatorId, opInfo, columns),
@@ -61,7 +102,7 @@ export function formatOperatorResult(operatorId: string, 
opInfo: OperatorInfo, w
   return [briefSummary, ...metadataLines, 
dataString].filter(Boolean).join("\n");
 }
 
-function formatInputOutputMetadata(
+export function formatInputOutputMetadata(
   workflowState: WorkflowState,
   operatorId: string,
   opInfo: OperatorInfo,
@@ -96,13 +137,14 @@ function formatInputOutputMetadata(
   return `Input operator(table shape): ${inputPart}\n${outputLine}`;
 }
 
-function jsonToTableFormat(jsonResult: Record<string, any>[]): string {
+export function jsonToTableFormat(jsonResult: Record<string, any>[]): string {
   if (!jsonResult || jsonResult.length === 0) return "";
 
   const hasRowIndex = "__row_index__" in jsonResult[0];
   const headers = getVisibleResultHeaders(jsonResult[0]);
   if (headers.length === 0) return "";
 
+  // Leading tab aligns headers with the index column (pandas __repr__ style).
   const headerLine = "\t" + headers.join("\t");
   const formattedRows: string[] = [];
   let prevIndex = -1;
diff --git a/agent-service/src/agent/tools/workflow-execution-tools.ts 
b/agent-service/src/agent/tools/workflow-execution-tools.ts
index efe9f2f57c..7224fd6be9 100644
--- a/agent-service/src/agent/tools/workflow-execution-tools.ts
+++ b/agent-service/src/agent/tools/workflow-execution-tools.ts
@@ -19,7 +19,8 @@
 
 import { z } from "zod";
 import { tool } from "ai";
-import { createErrorResult, formatExecuteOperatorResult, 
getVisibleResultHeaders } from "./tools-utility";
+import { createErrorResult } from "./tools-utility";
+import { formatOperatorResult } from "./result-formatting";
 import type { WorkflowState } from "../workflow-state";
 import { getBackendConfig } from "../../api/backend-api";
 import { env } from "../../config/env";
@@ -318,41 +319,6 @@ async function executeWorkflowHttp(
   }
 }
 
-function formatInputOutput(
-  workflowState: WorkflowState,
-  operatorId: string,
-  opInfo: OperatorInfo,
-  outputColumns: number
-): string {
-  const outputRows = opInfo.totalRowCount ?? opInfo.outputTuples;
-  const outputLine = `Output table shape: (${outputRows}, ${outputColumns})`;
-
-  const inputShapes = opInfo.inputPortShapes;
-  if (!inputShapes || inputShapes.length === 0) {
-    return outputLine;
-  }
-
-  const inputLinks = workflowState.getAllLinks().filter(l => 
l.target.operatorID === operatorId);
-  const portIndexToUpstream = new Map<number, string>();
-  const op = workflowState.getOperator(operatorId);
-  for (const link of inputLinks) {
-    const portIdx = op?.inputPorts.findIndex(p => p.portID === 
link.target.portID) ?? -1;
-    if (portIdx >= 0) {
-      portIndexToUpstream.set(portIdx, link.source.operatorID);
-    }
-  }
-
-  const inputPart = inputShapes
-    .sort((a, b) => a.portIndex - b.portIndex)
-    .map(p => {
-      const name = portIndexToUpstream.get(p.portIndex) ?? 
`input${p.portIndex}`;
-      return `${name}(${p.rows}, ${p.columns})`;
-    })
-    .join(", ");
-
-  return `Input operator(table shape): ${inputPart}\n${outputLine}`;
-}
-
 function formatExecutionError(
   compilationErrors?: Record<string, string>,
   operatorErrors?: Array<{ operatorId: string; error: string }>,
@@ -384,45 +350,6 @@ function formatExecutionError(
   return lines.join("\n");
 }
 
-function jsonToTableFormat(jsonResult: Record<string, any>[]): string {
-  if (!jsonResult || jsonResult.length === 0) return "";
-
-  const hasRowIndex = jsonResult.length > 0 && "__row_index__" in 
jsonResult[0];
-  const headers = getVisibleResultHeaders(jsonResult[0]);
-  if (headers.length === 0) return "";
-  // Leading tab aligns headers with the index column (pandas __repr__ style).
-  const headerLine = "\t" + headers.join("\t");
-
-  const formattedRows: string[] = [];
-  let prevIndex = -1;
-
-  for (let i = 0; i < jsonResult.length; i++) {
-    const row = jsonResult[i];
-    const rowIndex = hasRowIndex ? (row["__row_index__"] as number) : i;
-
-    if (prevIndex >= 0 && rowIndex > prevIndex + 1) {
-      const dots = headers.map(() => "...").join("\t");
-      formattedRows.push(`...\t${dots}`);
-    }
-    prevIndex = rowIndex;
-
-    const cells = headers.map(h => {
-      const val = row[h];
-      if (val === null) return "NaN";
-      if (val === undefined) return "";
-      if (typeof val === "number" || typeof val === "boolean") return 
String(val);
-      if (typeof val === "string") {
-        if (val === "NULL") return "NaN";
-        return val.replace(/\t/g, "\\t").replace(/\n/g, "\\n");
-      }
-      return JSON.stringify(val);
-    });
-    formattedRows.push(`${rowIndex}\t${cells.join("\t")}`);
-  }
-
-  return [headerLine, ...formattedRows].join("\n");
-}
-
 export async function executeOperatorAndFormat(
   workflowState: WorkflowState,
   config: ExecutionConfig,
@@ -510,10 +437,6 @@ export async function executeOperatorAndFormat(
       return "(no result data)";
     }
 
-    const jsonArray = opInfo.result as Record<string, any>[];
-    const headers = jsonArray.length > 0 ? 
getVisibleResultHeaders(jsonArray[0]) : [];
-    const columns = headers.length;
-
     // Notify for every operator in the execution so upstream stats are also 
stored.
     if (options.onResult) {
       for (const [opId, info] of Object.entries(result.operators)) {
@@ -523,50 +446,9 @@ export async function executeOperatorAndFormat(
       }
     }
 
-    let dataString = jsonToTableFormat(jsonArray);
-
     // Safety-net: TSV serialization may add padding beyond backend's 
raw-record budget.
     const charLimit = config.maxOperatorResultCharLimit ?? 
DEFAULT_AGENT_SETTINGS.maxOperatorResultCharLimit;
-
-    if (dataString.length > charLimit) {
-      const allLines = dataString.split("\n");
-      const headerLine = allLines[0];
-      const dataRows = allLines.slice(1);
-
-      const reservedSize = headerLine.length + 1;
-
-      const halfLimit = Math.floor((charLimit - reservedSize) / 2);
-
-      let frontSize = 0;
-      const frontRows: string[] = [];
-      for (const row of dataRows) {
-        const rowLen = row.length + 1;
-        if (frontSize + rowLen > halfLimit && frontRows.length > 0) break;
-        frontRows.push(row);
-        frontSize += rowLen;
-      }
-
-      let backSize = 0;
-      const backRows: string[] = [];
-      for (let i = dataRows.length - 1; i >= frontRows.length; i--) {
-        const rowLen = dataRows[i].length + 1;
-        if (backSize + rowLen > halfLimit && backRows.length > 0) break;
-        backRows.unshift(dataRows[i]);
-        backSize += rowLen;
-      }
-
-      const keptRows = [...frontRows, ...backRows];
-      dataString = [headerLine, ...keptRows].join("\n");
-    }
-
-    const shapeLine = formatInputOutput(workflowState, operatorId, opInfo, 
columns);
-
-    const warningLines = opInfo.warnings?.map(w => w) ?? [];
-
-    const metadataLines = [shapeLine, ...warningLines].filter(Boolean);
-
-    const briefSummary = formatExecuteOperatorResult(operatorId);
-    return [briefSummary, ...metadataLines, 
dataString].filter(Boolean).join("\n");
+    return formatOperatorResult(operatorId, opInfo, workflowState, charLimit);
   } catch (error: any) {
     if (error.name === "AbortError") {
       throw error;

Reply via email to