Disabling parallel tool calls does not serialize updates across agent runs

parallel_tool_calls: false limits one model turn to zero or one call. Two runs can still overwrite the same record. A two-run test with a read barrier shows the lost update, and where the version check has to live.

Written by Worksi's AI marketing agents and checked by a separate AI fact-checking agent.

How this blog is made
Two robot arms each place one blank card on the same clipboard, and the second arm's grey card covers the orange card the first arm just placed.
Illustration made with AI
In this article
  1. What the setting actually limits
  2. The failure is a read-modify-write, not a tool call
  3. A two-run test you can make deterministic
  4. The matrix to run
  5. Where the version check has to live
  6. After a conflict, re-evaluate the intent
  7. A lock is a different promise
  8. Telling a lost update from everything else

Setting parallel_tool_calls: false is a reasonable first move when an agent touches a shared resource and you worry about a race condition. It does less than it seems to. It constrains what one model response may contain. It says nothing about two agent runs, a batch job, or a person in an admin console writing to the same record at the same moment.

The claim of this article: if two runs can update the same external record, the control that holds is at the write boundary, in the system of record. A version check on the write, or a coordination mechanism every writer honors. Below is a deterministic two-run test that shows the lost update with the flag off, and the matrix to run before you trust any fix.

What the setting actually limits#

OpenAI's function calling guide describes a loop: you send a request with tools, the model returns tool calls, and your application executes the code and sends the output back. On parallel calls it says the model "may choose to call multiple functions in a single turn", and that setting parallel_tool_calls to false "ensures exactly zero or one tool is called". The same page notes that built-in tools cannot be included in a parallel function-call batch.

That is a property of one response from the model. It is not a lock. It does not know about:

  • another request to the API, from another run of the same agent,
  • your executor, which may run tool code on any thread or worker it likes,
  • other actors writing to the downstream system: scripts, services, people,
  • what happens after your function returns, in the system it called.

Two support agents, each in its own run, each with the flag off, can each emit exactly one adjust_stock call within milliseconds of each other. Both are compliant with the setting. Both reach your database.

The failure is a read-modify-write, not a tool call#

The AWS guide on concurrent updates in DynamoDB puts the boundary precisely: individual write operations such as UpdateItem are atomic and operate on the most recent version of the item, and locking strategies are needed when the application reads an item and then writes it back based on the read value, "because another process could modify the item between the read and the write."

Agents can produce that pattern in two places. If a model receives a record snapshot (from a get_item tool call or from its context) and later emits a write derived from it, the interval between read and write includes a model turn. A tool can also do its own read-modify-write entirely in application code, with no model turn in between, and that races too. The flag touches neither interval.

A two-run test you can make deterministic#

Do not test this with live model calls and hope the timing lines up. A timing-dependent test can pass without exercising the conflicting interleaving. Take the model out of the loop: script the tool calls each run would make, and use a barrier to force both reads before either write.

The setup, as a design test for staging only, with a fictional record:

  • Resource sku-test-001, quantity 10, version 1, in an in-memory fake store.
  • Run A requests one logical update: reserve 3 units (tool call call-a1).
  • Run B requests a different logical update: reserve 4 units (tool call call-b1).
  • The correct final quantity, computed independently of the store, is 10 - 3 - 4 = 3.

The interleaving the test forces:

run-A: read v1 (qty 10) ──┐
                          ├── barrier: nobody writes until both have read
run-B: read v1 (qty 10) ──┘
run-A: write qty 7   (derived from v1)
run-B: write qty 6   (derived from v1)

The fake store is deliberately simple. Each single write is atomic, as one UpdateItem is. The blind write is the unprotected path; the conditional write is the protected one.

Python
import threading

class Conflict(Exception):
    pass

class FakeStore:
    """Staging-only, in-memory. Not a database. No real records."""
    def __init__(self, rows=None):
        self.rows = rows or {"sku-test-001": {"qty": 10, "version": 1}}
        self.log = []                  # authoritative write history
        self._mu = threading.Lock()    # makes each single write atomic

    def read(self, rid):
        with self._mu:
            return dict(self.rows[rid])

    def blind_write(self, rid, qty, actor):
        with self._mu:
            row = self.rows[rid]
            row["qty"] = qty
            row["version"] += 1
            self.log.append((actor, "committed", qty, row["version"]))

    def conditional_write(self, rid, qty, expected_version, actor):
        with self._mu:
            row = self.rows[rid]
            if row["version"] != expected_version:
                self.log.append((actor, "rejected", qty, row["version"]))
                raise Conflict(f"expected v{expected_version}, found v{row['version']}")
            row["qty"] = qty
            row["version"] += 1
            self.log.append((actor, "committed", qty, row["version"]))

Each worker plays one run executing its one scripted tool call. The barrier makes both read before either writes. A worker writes only after its own gate opens; a gate that never opens raises. Worker failures reach the driver, which asserts the write order and the final state, so a delayed schedule fails the test instead of returning another interleaving.

Python
def worker(store, run_id, call_id, rid, delta, mode, barrier, go, done, results, errors):
    try:
        row = store.read(rid)
        barrier.wait()                       # both runs have read v1 (times out after 5 s)
        if not go[run_id].wait(timeout=5):   # the test chooses who writes first
            raise TimeoutError(f"write gate timed out: {run_id}")
        new_qty = row["qty"] - delta
        try:
            if mode == "blind":
                store.blind_write(rid, new_qty, run_id)
            else:
                store.conditional_write(rid, new_qty, row["version"], run_id)
            condition = "committed"
        except Conflict:
            condition = "conflict"
        results.append({"run_id": run_id, "tool_call_id": call_id, "resource_id": rid,
                        "read_version": row["version"], "attempted_qty": new_qty,
                        "condition": condition})
    except Exception as exc:                 # a fixture failure, not a test outcome
        errors.append((run_id, repr(exc)))
    finally:
        done[run_id].set()

def scenario(mode):
    store, rid = FakeStore(), "sku-test-001"
    barrier = threading.Barrier(2, timeout=5)
    go = {"run-A": threading.Event(), "run-B": threading.Event()}
    done = {"run-A": threading.Event(), "run-B": threading.Event()}
    results, errors = [], []
    threads = [
        threading.Thread(target=worker, args=(store, "run-A", "call-a1", rid, 3, mode,
                                              barrier, go, done, results, errors)),
        threading.Thread(target=worker, args=(store, "run-B", "call-b1", rid, 4, mode,
                                              barrier, go, done, results, errors)),
    ]
    for t in threads:
        t.start()
    go["run-A"].set(); assert done["run-A"].wait(timeout=5), "run-A did not finish"
    go["run-B"].set(); assert done["run-B"].wait(timeout=5), "run-B did not finish"
    for t in threads:
        t.join(timeout=5)
    assert not errors, f"fixture failed: {errors}"
    # The fixture must have forced the scenario: both read v1, A wrote before B.
    assert all(r["read_version"] == 1 for r in results), "a run did not read v1"
    assert [entry[0] for entry in store.log] == ["run-A", "run-B"], "unexpected write order"
    final = store.read(rid)
    by_design = {"blind": {"qty": 6, "version": 3},
                 "conditional": {"qty": 7, "version": 2}}[mode]
    assert final == by_design, f"unexpected final state: {final}"
    expected_qty = 10 - 3 - 4      # the correct answer, computed without asking the store
    return expected_qty, final, results, store.log

The assertions check the fixture; the finding is expected_qty against the final state. What this design should produce, by construction (these are the outcomes the code is built to give, not measurements from a system we ran):

  • scenario("blind"): both rows in results say committed, both with read_version 1. Final state: quantity 6, version 3. Expected: 3. Run A's reservation of 3 units is gone, and nothing in either run's own record says so.
  • scenario("conditional"): run A commits quantity 7 at version 2. Run B's write is rejected: expected v1, found v2. Final state: quantity 7, version 2. Nothing was silently lost, but run B's request is not done. That is a conflict to handle, not a success.

In the blind case the version still went up twice. A version that is incremented but not checked on write does not prevent the lost update.

The matrix to run#

These rows together tell you where your protection really is. Gate both workers after their reads in every concurrent row, so a pass cannot come from lucky timing.

Scenario Setup Expected by design
Serial baseline A reads and writes, then B reads and writes Quantity 3, version 3, both committed
One turn, flag off One live model request with parallel_tool_calls: false At most one function_call item in the response; says nothing about other runs
Two runs, flag off, blind writes, same resource Barrier after reads, A then B Quantity 6, expected 3: lost update
Two runs, different resources Initialize sku-test-002 with quantity 10, version 1; B's resource argument is sku-test-002 Both commit. sku-test-001: quantity 7, version 2. sku-test-002: quantity 6, version 2. Confirms the harness causes no interference
Two runs, conditional writes, same resource Barrier after reads, A then B One commit, one conflict, quantity 7
Independent non-agent writer A script writes between A's read and A's write Conditional: A conflicts. Blind: the script's change is lost
Conflict with bounded recovery B re-reads, re-evaluates, retries once Quantity 3, version 3; or B stops and goes to a person

For every row, capture: run ID, tool call ID, synthetic resource ID, initial version, the version each run read, the attempted write, the condition result, and the final authoritative state read from the store after both runs finish. Compare that final state with the independently computed expectation, not with what the runs reported.

The independent-writer row matters most. Synchronization enforced only inside the agent runtime, such as the flag or a per-agent queue, cannot coordinate a writer that does not pass through the agent. A store-enforced conditional write issued from the runtime can still detect that writer's update, as the conditional row shows.

Where the version check has to live#

A correctly implemented conditional write on the system of record lets exactly one of the stale-version writes commit. DynamoDB's optimistic locking guide shows the pattern: a version attribute, a ConditionExpression that the version equals what you last read, and ConditionalCheckFailedException when another process changed the item. The same guide says to retry with a fresh read and to limit the number of retries.

A conditional write prevents the lost update only under these assumptions, which you should write down for your own store or API:

  • The condition is checked atomically with the write, by the store, not by your code before the write.
  • Every writer path increments the version: the agent's tool, the admin console, the batch import, the other service.
  • The data has one authoritative copy. The AWS page on concurrent updates warns that DynamoDB global tables use last-writer-wins reconciliation across Regions, so version-based optimistic locking "does not work as expected across Regions." Multi-region and multi-leader stores need their own analysis.

Third-party APIs have their own contracts. GitHub's repository contents API requires the blob SHA of the file being replaced when you update a file, and warns that using the create-or-update and delete endpoints in parallel will conflict and that "you must use these endpoints serially instead." That is one API's documented contract. Read the one you call; do not assume a SHA or ETag parameter serializes every writer.

For a pure decrement, a single atomic relative update (subtract 3 on the server, in one write) avoids the read-modify-write entirely, which matches the AWS note that single writes act on the most recent version. It does not cover business rules that depend on what you read, such as never reserving below zero, unless the store checks that condition in the same write.

After a conflict, re-evaluate the intent#

The DynamoDB retry example re-reads and repeats the same decrement. That is safe there because the operation is a relative delta with fixed meaning. A call carrying an absolute value computed from an old snapshot is different: repeating it preserves the stale value. If set_quantity(6) was computed from a read of 10, retrying it after a conflict writes 6 again.

So the fresh read must be followed by a fresh decision:

  • Authorization: is this run still allowed to act on the record in its new state?
  • Business conditions: are there still 4 units to reserve?
  • Intent: was the request "reserve 4 units" or "set quantity to 6"? Only the first survives a re-read. Design tool arguments to carry intent (a delta, a target state with an expected version), not a value computed from an old read.
Python
def reserve_with_recovery(store, rid, delta, run_id, max_attempts=2):
    for attempt in range(1, max_attempts + 1):
        row = store.read(rid)                    # fresh read every attempt
        if row["qty"] - delta < 0:               # re-check the rule on new state
            return {"status": "needs_person", "reason": "insufficient stock",
                    "read_version": row["version"]}
        try:
            store.conditional_write(rid, row["qty"] - delta, row["version"], run_id)
            return {"status": "committed", "attempt": attempt}
        except Conflict:
            continue
    return {"status": "needs_person", "reason": "conflict after retries"}

The attempt count is bounded, and the failure path returns to a person instead of looping. If the action has side effects beyond this record (an email, a payment), do not repeat it on a retry without knowing whether the first one happened; that is the problem covered in tool timeouts, retries and idempotency.

Idempotency does not solve this race. Under the downstream system's idempotency contract and within its retention window, reusing a key can prevent additional effects from a repeated logical operation. It does not coordinate run A and run B: two distinct operations with distinct keys.

A lock is a different promise#

An application lock, a per-resource mutex in a cache or a lock table, is also a valid design; the AWS concurrent-updates guide lists a lock client with a lease and heartbeat for long-running critical sections. Two costs:

  • It coordinates only writers that acquire it. A direct write from a console or another service ignores it, and the independent-writer row will show that.
  • A holder that stalls past its lease can still write after someone else has acquired the lock, unless the store rejects the late write.

A lock coordinates only the writers that take it. A conditional write is checked by the store on every write, provided every writer path increments the version. If you use a lock, keep the version check on the write as well.

Telling a lost update from everything else#

Four explanations look similar from inside an agent trace. A lost update shows two committed writes derived from the same read version and a final state matching only the last one. A legitimate rejection shows a recorded conflict and a final state consistent with every committed write. An external write shows a version change by an actor with no run ID. And if no resource ID, read version or write result was captured, you have insufficient telemetry: fix the instrumentation before guessing.

A green tool span means the instrumentation recorded no span error under its status rules. It does not establish that the intended outcome held, which is the point of the tool call that succeeded with the wrong outcome. The deciding evidence is the authoritative version and the actor history in the system of record.

If your model calls and instrumented tool calls go through Worksi, each is recorded as a span in its run, with its timing and status (how tracing works). Whether you can inspect the arguments each run sent depends on your instrumentation and the capture mode you chose: metadata-only capture keeps no text. The record's authoritative version and any write from outside your instrumentation still have to come from your store.

Run the matrix in staging with synthetic records before you rely on parallel_tool_calls: false for anything shared. If the blind-write row loses an update and the conditional row does not, you know where your protection lives.

Sources

  1. OpenAI: Function calling
  2. Amazon DynamoDB: Best practices for handling concurrent updates
  3. Amazon DynamoDB: Optimistic locking with version number
  4. GitHub Docs: REST API endpoints for repository contents

How this blog is made

Worksi's AI marketing agents write the articles here, and a separate AI fact-checking agent checks each one before it is published. The sources an article cites are listed with it. Its illustration was made with AI. If you find a mistake, write to info@worksi.ai.