[Bug] Concurrent Executa `host/uploadFile` Calls Intermittently Fail During `confirm` with `r2_key does not belong to this invoke` in Platform-Installed Mode

Summary

We use the Executa host/uploadFile reverse RPC in an Anna App to upload temporary files. The upload follows the standard flow:

negotiate → PUT to presigned URL → confirm

When multiple independent tools.invoke calls execute this flow concurrently, some calls fail during confirm:

invoke error: {
  'code': -32204,
  'message': 'r2_key does not belong to this invoke',
  'data': {
    'errorCode': 'UPLOAD_INVALID_REQUEST'
  }
}

Notably:

  • All negotiate requests succeed.
  • All file PUT requests to their presigned URLs succeed.
  • For each call, the Executa sends the exact r2_key returned by that call’s own negotiate request back during confirm.
  • Every reverse RPC JSON-RPC ID is unique, and each response is routed to the correct request.
  • The same stress test does not reproduce the issue under local anna-app dev.
  • The issue is consistently reproducible after packaging and uploading the Executa to the Anna platform, then installing and running it through a Local Agent.

Our working hypothesis is that concurrent reverse RPCs are not reliably associated with their parent invoke because the parent invoke context is missing. The current official Python and Node.js Host Upload SDKs, our reproduction code, and the Host Upload client in ppt-engine do not propagate context.invoke_id in reverse RPC params.


Test Environment

  • Anna App: Host Upload concurrency diagnostic demo
  • Executa: Host Upload via Executa
  • Executa version: 0.2.4
  • Executa protocol: v2
  • Host capability: host.upload
  • Executa packaging: PyInstaller single-file Anna Binary
  • Local platform: macOS darwin-x86_64
  • Test file: one 256 KiB PNG file per call
  • Upload mode: forced negotiate → PUT → confirm
  • Concurrency: 8
  • Total calls: 10
  • Agent: Local Agent running on the same machine

We tested two execution modes:

  1. Running the Executa locally through anna-app dev.
  2. Building the Executa as an Anna Binary, uploading it to the Anna platform, and installing and running it through a Local Agent on the same machine.

Both modes use the same frontend stress-test logic and the same Executa upload implementation, but they produce different results.


Application and Invocation Logic

The frontend first asks the Executa to create a 256 KiB file in a local temporary directory:

const sampleReply = await invoke("make_sample", {
  size_bytes: 256 * 1024,
  filename: "host-upload-race-sample.png",
});

It then starts multiple workers that invoke the same Executa tool concurrently:

async function worker() {
  while (true) {
    const index = nextIndex++;
    if (index >= total) return;
    await runRaceCall(sample, index, config);
  }
}

await Promise.all(
  Array.from({ length: concurrency }, () => worker()),
);

Each runRaceCall starts an independent tools.invoke call:

await anna.tools.invoke({
  tool_id: EXECUTA_TOOL_ID,
  method: "host_upload_path",
  args: {
    path: sample.path,
    filename: `${runId}-${callId}.png`,
    mime_type: "image/png",
    purpose: "user_artifact",
    mode: "negotiate",
    run_id: runId,
    call_id: callId,
    delay_before_confirm_ms: delayMs,
    jitter_ms: jitterMs,
  },
});

This is not a single tools.invoke call uploading multiple files concurrently. It is a set of independent tools.invoke calls concurrently targeting the same Executa process.


Executa Upload Implementation

1. negotiate

The Executa reads the local file and sends a reverse RPC to the Host:

info = await host_upload.negotiate(
    filename=name,
    mime_type=mime,
    size_bytes=size,
    purpose="user_artifact",
    metadata={
        "diagnostic_run_id": run_id,
        "diagnostic_call_id": call_id,
    },
)

r2_key = info["r2_key"]

The reverse RPC written to stdout has the following shape:

{
  "jsonrpc": "2.0",
  "id": "<unique-reverse-rpc-id>",
  "method": "host/uploadFile",
  "params": {
    "mode": "negotiate",
    "filename": "<run-id>-<call-id>.png",
    "mime_type": "image/png",
    "size_bytes": 262144,
    "purpose": "user_artifact",
    "metadata": {
      "diagnostic_run_id": "<run-id>",
      "diagnostic_call_id": "<call-id>"
    }
  }
}

2. Upload the File with PUT

The Executa uploads the file directly using the presigned URL returned by negotiate:

headers = dict(info.get("headers") or {})
headers["Content-Length"] = str(size)

with open(path, "rb") as file:
    request = urllib.request.Request(
        info["put_url"],
        data=file,
        method="PUT",
        headers=headers,
    )
    with urllib.request.urlopen(request, timeout=300) as response:
        put_status = response.status

In this reproduction, all 10 PUT requests returned HTTP 200.

3. confirm

The Executa sends the r2_key returned by the same negotiate call back to the Host without modification:

result = await host_upload.confirm(r2_key=r2_key)

The corresponding reverse RPC is:

{
  "jsonrpc": "2.0",
  "id": "<another-unique-reverse-rpc-id>",
  "method": "host/uploadFile",
  "params": {
    "mode": "confirm",
    "r2_key": "<verbatim-r2-key-from-negotiate>"
  }
}

4. Reverse RPC Response Routing

The client generates a unique UUID for every reverse RPC and routes responses through a pending map:

request_id = uuid.uuid4().hex
future = loop.create_future()

with self._lock:
    self._pending[request_id] = future

self._write_frame({
    "jsonrpc": "2.0",
    "id": request_id,
    "method": "host/uploadFile",
    "params": params,
})

When a Host response arrives, the corresponding future is retrieved by JSON-RPC ID:

with self._lock:
    pending = self._pending.pop(message["id"], None)

In this reproduction:

  • 20 reverse RPCs were sent: 10 negotiate requests and 10 confirm requests.
  • All 20 reverse RPC IDs were unique.
  • All 20 response IDs matched their request IDs exactly.
  • There were no unmatched responses.
  • No call sent another call’s r2_key.

Reproduction Results

Frontend Results

There were 10 uploads in total:

call-001  confirm failed
call-002  confirm failed
call-003  confirm failed
call-004  confirm failed
call-005  succeeded
call-006  succeeded
call-007  succeeded
call-008  confirm failed
call-009  succeeded
call-010  succeeded

In summary:

negotiate succeeded: 10/10
PUT succeeded:       10/10
confirm succeeded:    5/10
confirm failed:       5/10

Every failed response was:

{
  "code": -32204,
  "message": "r2_key does not belong to this invoke",
  "data": {
    "errorCode": "UPLOAD_INVALID_REQUEST"
  }
}

Verification Against the Executa Backend Logs

For every failed call:

r2_key returned by negotiate
    == object key used by PUT
    == r2_key sent in the confirm request

In other words, the Executa did not modify, concatenate, or swap any r2_key values.

The logs also show a noteworthy pattern:

  • Failed calls 001, 002, 003, 004, and 008 each received a different invoke-scope path segment.
  • Successful calls 005, 006, and 007 shared the same scope path segment.
  • Later, successful calls 009 and 010 shared another scope path segment.

To avoid exposing account identifiers, signatures, and full object paths, only the redacted shape is shown below:

failed call-001 → .../<tool-id>/<scope-A>/user_artifact/<file-001>
failed call-002 → .../<tool-id>/<scope-B>/user_artifact/<file-002>
failed call-003 → .../<tool-id>/<scope-C>/user_artifact/<file-003>

succeeded call-005 → .../<tool-id>/<scope-X>/user_artifact/<file-005>
succeeded call-006 → .../<tool-id>/<scope-X>/user_artifact/<file-006>
succeeded call-007 → .../<tool-id>/<scope-X>/user_artifact/<file-007>

succeeded call-009 → .../<tool-id>/<scope-Y>/user_artifact/<file-009>
succeeded call-010 → .../<tool-id>/<scope-Y>/user_artifact/<file-010>

This pattern is more consistent with the Host or Agent selecting an incorrect or unstable parent invoke context while handling concurrent reverse RPCs than with an ordinary R2 write failure.


Difference Between Local anna-app dev and Platform-Installed Mode

Local anna-app dev

We tested local development mode with the same frontend code, Executa code, and stress-test parameters.

One complete run produced:

negotiate succeeded: 10/10
PUT succeeded:       10/10
confirm succeeded:   10/10
failed:               0

For every call, the negotiate r2_key, confirm r2_key, and final returned value matched exactly.

Uploaded to the Anna Platform and Run Through a Local Agent

We packaged the same Executa as an Anna Binary, uploaded it to the Anna platform, and installed it. The App initiated the calls in the platform environment, while the actual Agent continued to run locally. As a result, the Executa diagnostic JSONL files were still written to the local machine’s temporary directory.

In this mode, the same stress test produced confirm ownership failures in 5 out of 10 calls.

The difference is therefore not related to:

  • Whether the file originates in the cloud or locally.
  • A different R2 PUT implementation.
  • Whether the browser can access the presigned URL.
  • File bytes being transported through JSON-RPC.

The Executa always reads the file locally and uploads it directly to R2. The primary difference is that Executa registration, installation, and invocation go through the Anna platform and the Local Agent’s production execution path.


Working Hypothesis: Reverse RPC Does Not Carry the Parent context.invoke_id

We inspected the reverse RPC context-selection logic in the local Anna Runtime reference implementation. Its behavior can be summarized as follows:

ctx_in = params.get("context")
invoke_id = ctx_in.get("invoke_id")

if invoke_id in active_invoke_contexts:
    use(active_invoke_contexts[invoke_id])
elif len(active_invoke_contexts) == 1:
    use(the_only_active_invoke_as_fallback)
else:
    invoke_context = empty

In other words, when multiple invokes are executing concurrently, a reverse RPC should explicitly include:

{
  "params": {
    "context": {
      "invoke_id": "<parent-invoke-id>"
    }
  }
}

However, the host/uploadFile requests currently emitted by the Executa do not contain this field.

At the same time, the forward invoke request sent by the Agent to the Executa already includes:

{
  "method": "invoke",
  "params": {
    "tool": "host_upload_path",
    "arguments": {},
    "context": {
      "invoke_id": "<uuid>"
    }
  }
}

Our Executa currently reads only:

tool = params.get("tool")
args = params.get("arguments") or {}

It does not read or propagate:

params["context"]["invoke_id"]

The effective sequence is therefore:

Agent invoke(params.context.invoke_id = A)
  → Executa ignores A
  → reverse RPC negotiate (no context.invoke_id)
  → reverse RPC confirm (no context.invoke_id)
  → Agent cannot reliably identify the parent context among multiple active invokes
  → confirm fails when validating which invoke owns the r2_key

When there is only one active invoke—or when concurrent calls are completing and only one usable context happens to remain—the Runtime’s single-invoke fallback may allow a request to succeed. This would explain both the intermittent nature of the issue and why calls 009 and 010 succeeded later.


Why We Do Not Consider This a Nonstandard Application-Side Invocation

We reviewed the existing Host Upload SDKs and project code:

  • The official Python HostUploadClient does not include context.invoke_id in reverse RPC params.
  • The official Node.js HostUploadClient does not include context.invoke_id in reverse RPC params.
  • The current ExecutaHostUploadClient in ppt-engine does not propagate this field either.
  • The current Host Upload documentation examples for inline, negotiate, and confirm do not show params.context.invoke_id.

From an SDK and documentation consumer’s perspective, the current implementation follows the public examples and normal engineering practices. This appears more likely to be a contract mismatch between the following components:

Agent/Runtime
  Requires params.context.invoke_id to reliably associate a concurrent reverse RPC
  with its parent invoke

SDK/documentation/examples
  Do not expose, accept, or automatically propagate params.context.invoke_id

Expected Behavior

For multiple independent concurrent tools.invoke calls:

  1. Each forward invoke should have a stable and unique invoke context.
  2. Every reverse RPC initiated within that invoke should be automatically or explicitly associated with the same context.
  3. An r2_key returned by negotiate should be accepted by confirm within the same parent invoke.
  4. Other concurrent invokes should not affect that association.
  5. If a reverse RPC is missing required context, the Host should return an explicit missing context.invoke_id error instead of using a fallback in some cases and later surfacing the problem as r2_key does not belong to this invoke.

Suggested Fixes

We believe the issue could be addressed in one or more of the following ways.

Option 1: Automatically Propagate Invoke Context in the SDK

When processing a forward invoke, the Executa SDK could retain params.context and have HostUploadClient automatically attach the following to every reverse RPC:

{
  "context": {
    "invoke_id": "<current-parent-invoke-id>"
  }
}

Python could use contextvars.ContextVar to retain per-invoke context across concurrent tasks. Node.js could use AsyncLocalStorage or explicit parameter propagation.

Option 2: Clarify and Update the Protocol and Documentation

If params.context.invoke_id is required for reverse RPCs, we recommend:

  • Explicitly documenting the requirement in the Executa v2 protocol.
  • Updating the Python SDK.
  • Updating the Node.js SDK.
  • Updating the host/uploadFile documentation examples.
  • Adding an official regression test covering multiple concurrent forward invokes.

Option 3: Fail Earlier in the Runtime

When multiple invokes are active and a reverse RPC does not contain a valid context.invoke_id, we recommend returning an error such as:

{
  "code": -32602,
  "message": "reverse RPC requires params.context.invoke_id when multiple invokes are active",
  "data": {
    "errorCode": "MISSING_INVOKE_CONTEXT"
  }
}

This would prevent negotiate and the subsequent PUT from appearing to succeed, only for confirm to fail with an r2_key ownership error.

Option 4: Automatically Associate Reverse RPCs in the Host or Agent

If the protocol can associate a reverse RPC with the execution task of its forward invoke automatically, individual SDKs would not need to copy the context field manually. However, because multiple invokes share the same stdio channel, an explicit correlation ID may still be required at the wire-protocol level.


Questions for the Anna Team

  1. Does the host/uploadFile reverse RPC officially require params.context.invoke_id?
  2. If so, should this field be propagated automatically by the Executa SDK?
  3. Is the absence of this propagation in the current Python and Node.js Host Upload SDKs a known issue?
  4. Does the platform-installed Executa execution path through a Local Agent use different reverse RPC context management from anna-app dev?
  5. Why do some requests without context still succeed? Is this due to a fallback when only one invoke is active?
  6. Should the negotiate stage validate the invoke context immediately instead of waiting until confirm to detect an ownership mismatch?
  7. The error response uses code = -32204 with errorCode = UPLOAD_INVALID_REQUEST. Are both values consistent with the current official error-code definitions?

We can provide the complete redacted JSONL logs, the minimal reproduction demo, the Anna Binary, and the stress-test parameters. If helpful, we can also add additional context fields following the team’s guidance or compare behavior across specific Agent or Runtime versions.

Hi @HappyLight! :waving_hand:

What a fantastic piece of detective work — the redacted scope-path pattern analysis alone basically handed us the smoking gun. :man_detective: Thank you!

TL;DR: Confirmed platform bug, fixed across the whole stack — Agent 1.1.0-beta.26, platform 1.1.0-beta.103, and updated Python/Node.js/Go SDKs in the examples repo. Upgrade your Local Agent and rebuild against the latest SDK and concurrent uploads work reliably. :white_check_mark:

:magnifying_glass_tilted_left: What we found

Your hypothesis was very close — and the real bug was actually one layer deeper, on the host side:

  • The Agent kept the invoke context in a single mutable slot per Executa process. Under concurrent invokes, contexts overwrote each other (last-writer-wins). Your reverse RPCs were then evaluated against whichever invoke’s context happened to be in the slot — which is exactly why your failed calls each landed in a different invoke’s scope path, while successful calls shared one. That log pattern you spotted was the clobbering, verbatim. :clap:
  • This also means your Option 1 alone (SDK propagating context.invoke_id) wouldn’t have been enough — the host didn’t read that field at all. The fix needed both sides.
  • And why anna-app dev passes: the dev harness confirm path derived the expected invoke from the r2_key itself, so it structurally couldn’t catch ownership races. (Also fixed.)

:hammer_and_wrench: The fix (your Options 1 + 3 + 4, combined :grinning_face_with_smiling_eyes:)

  1. Agent (1.1.0-beta.26): per-invoke context registry — every reverse RPC is routed by an explicit params.context.invoke_id. Fallback to the sole active invoke only when exactly one is running (backward compatible with existing binaries); if multiple invokes are active and no id is given, you now get a fail-fast error instead of a late confirm ownership failure:

    { "code": -32602, "data": { "errorCode": "MISSING_INVOKE_CONTEXT" } }
    

    (Unknown ids get UNKNOWN_INVOKE_CONTEXT.)

  2. SDKs (Python / Node.js / Go): HostUploadClient and all other reverse-RPC clients now automatically stamp params.context.invoke_id — Python via contextvars, Node.js via AsyncLocalStorage, exactly as you suggested. Wrap your tool handler in the SDK’s bind_invoke() / bindInvoke() and everything propagates for free. One heads-up: Python contextvars don’t cross threads, so if you hop threads (e.g. run_coroutine_threadsafe), bind inside the coroutine.

  3. Platform (1.1.0-beta.103): the confirm ownership check now also binds the uploading user, and the protocol + Host Upload docs gained a dedicated concurrency/correlation section.

  4. Regression coverage: dedicated concurrent-invoke routing tests on the Agent, SDK context tests, and an E2E driver validating two concurrent invokes each carry their own invoke_id. :white_check_mark:

:pushpin: Your questions, quickly

1–3. It wasn’t officially required before — that was the gap. It is now the documented correlation mechanism, and the SDKs propagate it automatically (no manual work needed).
4. Not different context management per se — the dev-mode confirm path just couldn’t detect ownership mismatches (see above).
5. Exactly right: single-active-invoke situations picked the correct context by luck, which is why calls 009/010 succeeded once concurrency drained. :bullseye:
6. Agreed — with the fix, missing/ambiguous context now fails at the reverse-RPC boundary, before negotiate/PUT waste any work.
7. Good catch — there is a divergence between two error-code tables; the platform-side numbering you observed is authoritative for now, and a wire-contract alignment is tracked separately.

:package: To pick up the fix

  • Update your Local Agent to 1.1.0-beta.26+.
  • Rebuild your Executa against the latest SDK from the examples repo, wrapping your invoke handler with bind_invoke() / bindInvoke() (see the updated anna-app-file-upload-demo for the pattern).

Thank you again for the stellar report — reproduction demo, wire captures, ranked fix options and the correct error-code nitpick. You made this fix easy. :blue_heart: Happy (concurrent) uploading! :rocket::file_folder: