Skip to content

Self-improving AI Employees for everyone

fix(execution): correlation-id dedup + idle-state clear_node_status

trohitgc85113740e81
diff --git a/client/src/components/parameterPanel/OutputSection.tsx b/client/src/components/parameterPanel/OutputSection.tsx
index 1e748009..14102420 100644
--- a/client/src/components/parameterPanel/OutputSection.tsx
+++ b/client/src/components/parameterPanel/OutputSection.tsx
@@ -23,11 +23,15 @@ const OutputSection: React.FC<OutputSectionProps> = ({
return null;
}
- // Combine local execution results with WebSocket nodeStatuses from workflow execution
+ // Combine local execution results with WebSocket nodeStatuses from
+ // workflow execution. Dedup uses the backend-issued `execution_id`
+ // correlation token: the request-response and the broadcast for the
+ // same run carry the same id, so we can fold them into one entry.
+ // The previous implementation hashed outputs via JSON.stringify, which
+ // collapsed two distinct executions whose payloads happened to match.
const combinedResults = React.useMemo(() => {
const results = [...executionResults];
- // Check if there's output from workflow execution in nodeStatuses.
// WebSocket node_output messages store data in the `output` field,
// while node_status messages use `data`. Check both so the formatted
// response renderer (getMainResponse → ReactMarkdown) receives the
@@ -35,10 +39,21 @@ const OutputSection: React.FC<OutputSectionProps> = ({
const nodeStatus = nodeStatuses[selectedNode.id];
const statusData = nodeStatus?.data || nodeStatus?.output;
if (nodeStatus && statusData && (nodeStatus.status === 'success' || nodeStatus.status === 'error')) {
- const alreadyExists = results.some(r =>
- r.nodeId === selectedNode.id &&
- JSON.stringify(r.outputs) === JSON.stringify(statusData)
- );
+ const broadcastExecutionId: string | undefined = statusData?.execution_id;
+ const alreadyExists = results.some((r) => {
+ // Preferred: correlate by backend-issued execution_id token.
+ if (broadcastExecutionId && r.executionId) {
+ return r.executionId === broadcastExecutionId;
+ }
+ // Backward-compat fallback for results constructed before the
+ // execution_id field was wired (or for synthetic catch-block
+ // entries): structural equality on outputs, scoped to this
+ // node id. Same shape used by the pre-correlation-id code.
+ return (
+ r.nodeId === selectedNode.id &&
+ JSON.stringify(r.outputs) === JSON.stringify(statusData)
+ );
+ });
if (!alreadyExists) {
const wsResult: ExecutionResult = {
@@ -50,7 +65,8 @@ const OutputSection: React.FC<OutputSectionProps> = ({
executionTime: 0,
outputs: statusData,
nodeData: [[{ json: statusData }]],
- error: nodeStatus.status === 'error' ? statusData?.error : undefined
+ error: nodeStatus.status === 'error' ? statusData?.error : undefined,
+ executionId: broadcastExecutionId,
};
results.unshift(wsResult);
}
diff --git a/client/src/components/parameterPanel/__tests__/OutputSection.test.tsx b/client/src/components/parameterPanel/__tests__/OutputSection.test.tsx
index b720069d..ab14d808 100644
--- a/client/src/components/parameterPanel/__tests__/OutputSection.test.tsx
+++ b/client/src/components/parameterPanel/__tests__/OutputSection.test.tsx
@@ -212,6 +212,74 @@ describe('OutputSection', () => {
expect(screen.getByTestId('result-count').textContent).toBe('0');
});
+ it('dedups by executionId when both sides carry one (correlation-id pattern)', () => {
+ setNodeStatus({
+ 'n-1': {
+ status: 'success',
+ data: { ok: true, execution_id: 'exec-abc' },
+ },
+ });
+
+ const existing = [
+ {
+ success: true,
+ nodeId: 'n-1',
+ nodeType: 'http',
+ nodeName: 'HTTP',
+ timestamp: 't1',
+ executionTime: 10,
+ outputs: { ok: true },
+ nodeData: [[{ json: { ok: true } }]],
+ executionId: 'exec-abc',
+ },
+ ];
+
+ render(
+ <OutputSection
+ selectedNode={{ id: 'n-1', type: 'http' } as any}
+ executionResults={existing as any}
+ onClearResults={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByTestId('result-count').textContent).toBe('1');
+ });
+
+ it('keeps two distinct results when execution_ids differ even if outputs match', () => {
+ setNodeStatus({
+ 'n-1': {
+ status: 'success',
+ data: { ok: true, execution_id: 'exec-second' },
+ },
+ });
+
+ const existing = [
+ {
+ success: true,
+ nodeId: 'n-1',
+ nodeType: 'http',
+ nodeName: 'HTTP',
+ timestamp: 't1',
+ executionTime: 10,
+ outputs: { ok: true },
+ nodeData: [[{ json: { ok: true } }]],
+ executionId: 'exec-first',
+ },
+ ];
+
+ render(
+ <OutputSection
+ selectedNode={{ id: 'n-1', type: 'http' } as any}
+ executionResults={existing as any}
+ onClearResults={vi.fn()}
+ />,
+ );
+
+ // Two distinct runs with identical payloads -- correlation-id keeps
+ // them separate where the old JSON-stringify dedup would collapse.
+ expect(screen.getByTestId('result-count').textContent).toBe('2');
+ });
+
it('invokes onClearResults when the clear button is pressed', async () => {
const onClear = vi.fn();
render(
diff --git a/client/src/services/executionService.ts b/client/src/services/executionService.ts
index a3a6a236..2bbc9cc8 100644
--- a/client/src/services/executionService.ts
+++ b/client/src/services/executionService.ts
@@ -16,6 +16,15 @@ export interface ExecutionResult {
error?: string;
data?: any;
nodeData: INodeExecutionData[][];
+ /**
+ * Backend-issued correlation token (uuid4 hex) that identifies a
+ * single run end-to-end. Carried through every node_status broadcast
+ * for the run plus the execute_node response payload, so dedup logic
+ * in OutputSection compares execution_id rather than the brittle
+ * JSON.stringify(outputs). Optional for results constructed before
+ * a backend response is available (e.g. catch-block error stubs).
+ */
+ executionId?: string;
}
// WebSocket execution function type (passed from components using useWebSocket)
@@ -106,7 +115,8 @@ export class ExecutionService {
executionTime: result.execution_time || executionTime,
outputs: outputData,
data: outputData,
- nodeData: nodeExecutionData
+ nodeData: nodeExecutionData,
+ executionId: result.execution_id,
};
} else {
const errorOutputData = result.result || {
@@ -130,7 +140,8 @@ export class ExecutionService {
error: result.error,
outputs: errorOutputData,
data: errorOutputData,
- nodeData: errorData
+ nodeData: errorData,
+ executionId: result.execution_id,
};
}
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index b5943455..5e35de01 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -12,6 +12,7 @@ Handles WebSocket connections from frontend clients for ALL operations:
import time
import asyncio
+import uuid
import weakref
from typing import Dict, Any, Callable, Awaitable, Optional, Set
from datetime import datetime
@@ -381,13 +382,24 @@ async def handle_get_credential_catalogue(data: Dict[str, Any], websocket: WebSo
@ws_handler("node_id", "node_type")
async def handle_execute_node(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Execute a workflow node with per-workflow status scoping (n8n pattern)."""
+ """Execute a workflow node with per-workflow status scoping (n8n pattern).
+
+ Generates an `execution_id` correlation token (uuid4 hex) and propagates
+ it through every broadcast for this run plus the response payload.
+ Frontend uses it for idempotent dedup -- two executions with identical
+ output payloads were previously collapsing because the dedup key was
+ JSON.stringify(outputs). This is the standard request-id / trace-id
+ pattern (OpenTelemetry, AWS X-Ray, etc.).
+ """
workflow_service = container.workflow_service()
broadcaster = get_status_broadcaster()
node_id, node_type = data["node_id"], data["node_type"]
workflow_id = data.get("workflow_id") # Per-workflow isolation
+ execution_id = uuid.uuid4().hex
- await broadcaster.update_node_status(node_id, "executing", workflow_id=workflow_id)
+ await broadcaster.update_node_status(
+ node_id, "executing", {"execution_id": execution_id}, workflow_id=workflow_id,
+ )
result = await workflow_service.execute_node(
node_id=node_id, node_type=node_type,
parameters=data.get("parameters", {}),
@@ -398,18 +410,24 @@ async def handle_execute_node(data: Dict[str, Any], websocket: WebSocket) -> Dic
)
if result.get("success"):
- await broadcaster.update_node_status(node_id, "success", result.get("result"), workflow_id=workflow_id)
- await broadcaster.update_node_output(node_id, result.get("result"), workflow_id=workflow_id)
+ success_payload = {**(result.get("result") or {}), "execution_id": execution_id}
+ await broadcaster.update_node_status(node_id, "success", success_payload, workflow_id=workflow_id)
+ await broadcaster.update_node_output(node_id, success_payload, workflow_id=workflow_id)
elif result.get("error") == "Cancelled by user":
# Cancelled trigger nodes go back to idle, not error
- await broadcaster.update_node_status(node_id, "idle", {"message": "Cancelled"}, workflow_id=workflow_id)
+ await broadcaster.update_node_status(
+ node_id, "idle", {"message": "Cancelled", "execution_id": execution_id}, workflow_id=workflow_id,
+ )
else:
- await broadcaster.update_node_status(node_id, "error", {"error": result.get("error")}, workflow_id=workflow_id)
+ await broadcaster.update_node_status(
+ node_id, "error", {"error": result.get("error"), "execution_id": execution_id}, workflow_id=workflow_id,
+ )
# Explicitly pass through success status (don't let decorator default to True)
ws_result = {
"success": result.get("success", False),
"node_id": node_id,
+ "execution_id": execution_id,
"result": result.get("result"),
"error": result.get("error"),
"execution_time": result.get("execution_time"),
diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.py
index a5109252..5ebd6daf 100644
--- a/server/services/status_broadcaster.py
+++ b/server/services/status_broadcaster.py
@@ -1001,17 +1001,34 @@ class StatusBroadcaster:
return self._status["nodes"].get(node_id)
async def clear_node_status(self, node_id: str) -> bool:
- """Clear a node's status and output from the cache."""
- if node_id in self._status["nodes"]:
- del self._status["nodes"][node_id]
- logger.info(f"[StatusBroadcaster] Cleared node status: {node_id}")
- # Broadcast that node status was cleared
- await self.broadcast({
- "type": "node_status_cleared",
- "node_id": node_id
- })
- return True
- return False
+ """Reset a node's status to idle.
+
+ Intentionally does NOT delete the dict entry. The previous behavior
+ deleted the slot, which created a race window: an in-flight
+ execution's subsequent `success` broadcast would re-create the
+ entry, leaving the UI stuck on a stale "completed" indicator on a
+ node the user just cancelled. Resetting to idle preserves entry
+ identity (so subsequent broadcasts update it normally) while
+ clearing the visible state.
+ """
+ had_status = node_id in self._status["nodes"]
+ previous_workflow = (
+ self._status["nodes"][node_id].get("workflow_id") if had_status else None
+ )
+ self._status["nodes"][node_id] = {
+ "status": "idle",
+ "data": {},
+ "timestamp": asyncio.get_event_loop().time(),
+ "workflow_id": previous_workflow,
+ "cleared": True,
+ }
+ logger.info(f"[StatusBroadcaster] Reset node status to idle: {node_id}")
+ await self.broadcast({
+ "type": "node_status_cleared",
+ "node_id": node_id,
+ "workflow_id": previous_workflow,
+ })
+ return had_status
def get_variable(self, name: str) -> Any:
"""Get a variable value."""