sdk-python
sdk-python copied to clipboard
perf: deepcopy in GraphNode/SwarmNode state management adds ~1ms per graph node
Description
GraphNode.__post_init__ and reset_executor_state use copy.deepcopy() to save/restore conversation state. For a typical conversation (20 messages, 10 tools), each deepcopy call costs 0.218ms.
In a 5-node graph, this adds 1.1ms of pure copy overhead per execution. In a 20-node workflow, it's 9ms of latency from copies alone.
Benchmark
import copy, timeit
messages = [{'role': 'user', 'content': [{'type': 'text', 'text': f'Msg {i}'}]} for i in range(20)]
model_state = {'temperature': 0.7, 'tools': [{'name': f't{i}'} for i in range(10)]}
# Current: deepcopy
t = timeit.timeit(lambda: (copy.deepcopy(messages), copy.deepcopy(model_state)), number=1000)
print(f'deepcopy: {t:.3f}ms per call') # ~0.218ms
# Alternative: shallow copy each message dict
t = timeit.timeit(lambda: ([m.copy() for m in messages], model_state.copy()), number=1000)
print(f'shallow: {t:.6f}ms per call') # ~0.003ms
# Speedup: ~67x
Proposed Fix
Replace copy.deepcopy() with [msg.copy() for msg in messages] for message lists and state.copy() for model state.
This is safe because the executor only:
- Appends new messages (
agent.py:1123) - Replaces scalar values in model state
It does not mutate existing message dicts in-place.
Impact
- 5-node graph: 1.1ms → 0.002ms copy overhead
- 20-node workflow: 9ms → 0.01ms copy overhead
- At 100 req/sec: saves 11% of a CPU core
I'd like to submit a PR for this if the approach sounds reasonable.