Skip to content

Race condition in InvocationReplayState.incrementAgentReplayIndex during parallel agent execution #1009

@Harishvishwa01

Description

@Harishvishwa01

Description

InvocationReplayState maintains replay indices per agent using a HashMap:

private final Map<String, Integer> agentReplayIndices = new HashMap<>();

The class documentation mentions:

"Per-invocation replay state to isolate concurrent runs"
"Per-agent replay indices for parallel execution"

However, HashMap is not thread-safe, and the method incrementAgentReplayIndex performs a non-atomic read-modify-write sequence:

public void incrementAgentReplayIndex(String agentName) {
  int currentIndex = getAgentReplayIndex(agentName);
  setAgentReplayIndex(agentName, currentIndex + 1);
}

If multiple threads update the same agent index concurrently, the following race condition may occur:

  1. Thread A reads index 1
  2. Thread B reads index 1
  3. Thread A writes 2
  4. Thread B writes 2

The expected value should be 3, but the result becomes 2.

This can cause incorrect replay ordering or skipped increments during parallel agent execution.


Suggested Improvement

Use a thread-safe structure such as ConcurrentHashMap and perform atomic updates using merge().

Example improvement:

import java.util.concurrent.ConcurrentHashMap;

private final Map<String, Integer> agentReplayIndices = new ConcurrentHashMap<>();

public void incrementAgentReplayIndex(String agentName) {
  agentReplayIndices.merge(agentName, 1, Integer::sum);
}

This ensures the increment operation is atomic and prevents lost updates when multiple agents update the same index concurrently.


Additional Context

Since the class explicitly supports parallel execution, ensuring thread-safe replay index updates will make the replay mechanism deterministic and more reliable under concurrent agent runs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions