@devries-cameron20 / composio-1 / commits / 53c024a9c
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(py): keep local results when remote multi-execute transport fails (#4386)

## Summary Follow-up to #4310. The TypeScript SDK (since #3800) catches a thrown backend call for the remote half of a mixed `COMPOSIO_MULTI_EXECUTE_TOOL` batch and turns it into one failure entry per remote slug, so completed local results are not lost. The Python SDK still let the exception escape `_route_multi_execute`, discarding every local result that had already run. This ports the TypeScript behavior so both SDKs return the same shape on a remote transport failure. Fixes # ## Changes - Catch the remote future's exception in `_route_multi_execute` and keep `str(error)`, falling back to `Remote tool execution failed` when the message is empty (same fallback as TS). - Synthesize `{response: {successful: False, data: {}, error}, tool_slug, error}` for each remote index and merge them in original request order. - Recompute `total_count` / `success_count` / `error_count` on transport failure, as TS does. - Add two regression tests mirroring the TS cases in `customToolRouting.test.ts`: local results preserved with per-tool remote errors, and the empty-message fallback. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactor/Chore - [ ] Documentation - [ ] Breaking change ## How Has This Been Tested? - `uv run --locked --group dev pytest tests/test_custom_tools.py -q`: 87 passed. - `uv run --locked --group dev nox -s chk`: ruff and mypy clean. - Without the source change, the new `test_remote_transport_failure_keeps_local_results` raises `RuntimeError: remote unavailable` out of `_route_multi_execute`. ## Checklist - [x] I have read the Code of Conduct and this PR adheres to it - [x] I ran linters/tests locally and they passed - [ ] I updated documentation as needed - [x] I added tests or explain why not applicable - [ ] I added a changeset if this change affects published packages (Python does not use Changesets) ## Additional context TypeScript reference: `ts/packages/core/src/models/ToolRouterSession.ts`, the `remoteErrorMessage` branch, and the test "should preserve successful local results when remote transport fails". https://claude.ai/code/session_01PAXMbiZd3qPoJ8Z9uPvEAb EOF -R ComposioHQ/composio

Alberto Schiabel committed Sep 8, 2026 at 18:11 UTC 53c024a9c891b72aead0b626b8d98d22cdb065c7
2 files changed +101 -15
python/composio/core/models/tool_router_session.py
+41 -15
@@ -487,10 +487,17 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
487 for idx, future in local_futures:
488 local_results.append((idx, future.result()))
489
490 - # Gather remote result
490 + # Gather remote result. A transport failure (exception from the
491 + # backend call) must not discard completed local results, so it
492 + # is captured here and surfaced as per-tool failures below
493 + # (matches TS).
494 remote_result: t.Optional[t.Dict[str, t.Any]] = None
495 + remote_error_message: t.Optional[str] = None
496 if remote_future:
493 - remote_result = remote_future.result()
497 + try:
498 + remote_result = remote_future.result()
499 + except Exception as error:
500 + remote_error_message = str(error) or "Remote tool execution failed"
501
502 # If only one local tool and no remote, return unwrapped
503 if not remote_indices and len(local_results) == 1:
@@ -515,11 +522,26 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
522 # Restore original request order, then re-index sequentially.
523 remote_data_raw = (remote_result or {}).get("data")
524 remote_data = remote_data_raw if isinstance(remote_data_raw, dict) else {}
518 - remote_results_list = (
519 - remote_data.get("results", [])
520 - if isinstance(remote_data.get("results"), list)
521 - else []
522 - )
525 + remote_results_list: t.List[t.Dict[str, t.Any]]
526 + if remote_error_message is not None:
527 + remote_results_list = [
528 + {
529 + "response": {
530 + "successful": False,
531 + "data": {},
532 + "error": remote_error_message,
533 + },
534 + "tool_slug": parsed[index]["tool_slug"],
535 + "error": remote_error_message,
536 + }
537 + for index in remote_indices
538 + ]
539 + else:
540 + remote_results_list = (
541 + remote_data.get("results", [])
542 + if isinstance(remote_data.get("results"), list)
543 + else []
544 + )
545 merged_results = [
546 {
547 **entry,
@@ -534,19 +556,23 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
556 all_results = [{**entry, "index": i} for i, entry in enumerate(merged_results)]
557 failed = sum(1 for r in all_results if r.get("error"))
558 merged_data = {**remote_data, "results": all_results}
537 - if local_entries and any(
538 - key in remote_data
539 - for key in ("total_count", "success_count", "error_count")
559 + if local_entries and (
560 + remote_error_message is not None
561 + or any(
562 + key in remote_data
563 + for key in ("total_count", "success_count", "error_count")
564 + )
565 ):
566 merged_data["total_count"] = len(all_results)
567 merged_data["success_count"] = len(all_results) - failed
568 merged_data["error_count"] = failed
569
545 - remote_error = (
546 - str(remote_result.get("error"))
547 - if remote_result and remote_result.get("error") is not None
548 - else None
549 - )
570 + remote_error = remote_error_message
571 + if remote_error is None and remote_result:
572 + raw_remote_error = remote_result.get("error")
573 + remote_error = (
574 + str(raw_remote_error) if raw_remote_error is not None else None
575 + )
576 has_any_error = any(r.get("error") for _, r in local_results) or bool(
577 remote_error
578 )
python/tests/test_custom_tools.py
+60
@@ -1344,6 +1344,66 @@ class TestMultiExecuteRouting:
1344 assert result["successful"] is True
1345 assert result["data"]["results"][0]["tool_slug"] == "GREP"
1346
1347 + def test_remote_transport_failure_keeps_local_results(self, grep_tool):
1348 + """A raised backend error becomes per-tool failures (matches TS)."""
1349 + s = self._make_session(grep_tool)
1350 + tm = MagicMock()
1351 +
1352 + def failing_backend(slug, args):
1353 + raise RuntimeError("remote unavailable")
1354 +
1355 + tm._wrap_execute_tool_for_tool_router.return_value = failing_backend
1356 + result = s._route_multi_execute(
1357 + {
1358 + "tools": [
1359 + {"tool_slug": "GREP", "arguments": {"pattern": "x"}},
1360 + {"tool_slug": "REMOTE", "arguments": {}},
1361 + {"tool_slug": "OTHER_REMOTE", "arguments": {}},
1362 + ]
1363 + },
1364 + tm,
1365 + )
1366 + assert result["successful"] is False
1367 + assert result["error"] == "2 out of 3 tools failed"
1368 + results = result["data"]["results"]
1369 + assert [r["tool_slug"] for r in results] == ["GREP", "REMOTE", "OTHER_REMOTE"]
1370 + assert [r["index"] for r in results] == [0, 1, 2]
1371 + assert results[0]["response"] == {
1372 + "successful": True,
1373 + "data": {"matches": ["x"], "path": "."},
1374 + }
1375 + assert "error" not in results[0]
1376 + for entry in results[1:]:
1377 + assert entry["error"] == "remote unavailable"
1378 + assert entry["response"] == {
1379 + "successful": False,
1380 + "data": {},
1381 + "error": "remote unavailable",
1382 + }
1383 + assert result["data"]["total_count"] == 3
1384 + assert result["data"]["success_count"] == 1
1385 + assert result["data"]["error_count"] == 2
1386 +
1387 + def test_remote_transport_failure_uses_fallback_message(self, grep_tool):
1388 + s = self._make_session(grep_tool)
1389 + tm = MagicMock()
1390 +
1391 + def failing_backend(slug, args):
1392 + raise RuntimeError()
1393 +
1394 + tm._wrap_execute_tool_for_tool_router.return_value = failing_backend
1395 + result = s._route_multi_execute(
1396 + {
1397 + "tools": [
1398 + {"tool_slug": "GREP", "arguments": {"pattern": "x"}},
1399 + {"tool_slug": "REMOTE", "arguments": {}},
1400 + ]
1401 + },
1402 + tm,
1403 + )
1404 + assert result["successful"] is False
1405 + assert result["data"]["results"][1]["error"] == "Remote tool execution failed"
1406 +
1407 def test_remote_batch_error_without_item_errors_uses_batch_message(self, grep_tool):
1408 s = self._make_session(grep_tool)
1409 tm = MagicMock()