Skip to content

[Bug]: Concurrent WorkspaceMessageBus.queueDrain calls can return the same queue entry #3280

Closed

Description

@liugy789

Describe the bug

WorkspaceMessageBus.queueDrain lists queue entries and then reads and deletes them without first acquiring exclusive ownership of each entry.

When two WorkspaceMessageBus instances share the same filesystem and drain concurrently, both can list and read the same entry before either deletes it. Both calls may then return a BusEntry with the same ID. This is silent; no exception is required.

There is also a producer/consumer race: queuePush writes JSON to a path that drainers can already list. If a drainer observes the file before the write is complete, it may read incomplete JSON and treat the entry as corrupt.

To Reproduce

The duplicate-drain race can be reproduced deterministically with a test-only filesystem wrapper:

  1. Create two WorkspaceMessageBus instances using the same LocalFilesystem root and busRoot.
  2. Push one entry to a queue.
  3. Wrap AbstractFilesystem.read with a barrier so both callers have read the entry before either drain continues to deletion.
  4. Run queueDrain concurrently on both instances.
  5. Aggregate the results. On the current implementation, both drains can return the same entry ID.

A related publication interleaving can be tested by pausing a filesystem write after only part of the JSON has been written, then draining before the write completes.

Expected behavior

  • Concurrent drain calls must not both return the same queue entry.
  • A queue entry must not become visible to drainers until its payload has been written completely.

This describes a queue-entry concurrency guarantee, not end-to-end exactly-once processing or crash-safe delivery.

Error messages

There is no required exception for duplicate returns; they can happen silently.

If a drainer observes a partially written file, the implementation may log a corrupt-JSON warning and delete that entry.

Environment (please complete the following information):

  • AgentScope-Java Version: main at fefc196
  • Java Version: 17.0.12
  • OS: macOS 14.8, aarch64
  • Filesystem: shared LocalFilesystem for the deterministic reproduction

Additional context

Duplicate drain:
Drainer A: list E -> read E --------------------> return E -> delete E
Drainer B:       list E -> read E -> return E -> delete E

Partial publication:
Producer: write E.json -------------------------> write complete
Drainer:             list E.json -> read partial -> parse as corrupt

A possible fix is to publish a ready marker only after the payload is complete, and require each drainer to acquire an atomic create-if-absent claim before reading an entry.

For distributed-store context, see the AgentScope-Java distributed storage documentation.

Activity

  1. liugy789 commented on Sep 24, 2026

    @liugy789
    ContributorAuthor

    I have prepared a fix on a local branch, including regression coverage for concurrent drains and entries published before the payload write completes. I will submit a pull request shortly.

  2. liugy789 commented on Sep 24, 2026

    @liugy789
    ContributorAuthor

    I have opened PR #3281 to address this issue. It includes regression tests for concurrent queue drains and entries observed before their payload is fully published: #3281

  3. added
    bug
    area/harness
    on Sep 24, 2026
  4. oss-maintainer commented on Sep 24, 2026

    @oss-maintainer
    Collaborator

    Issue Evaluation

    Category: bug / area/harness (message bus) | Status: Confirmed | Severity: high

    Verified against main @ 320822d40 (engine-assisted static read; the blobs for WorkspaceMessageBus.java, LocalFilesystem.java and WorkspaceMessageBusTest.java are byte-identical to the reported fefc196, so the report is evaluated against exactly the code the reporter saw). Paths below are under agentscope-harness/src/main/java/io/agentscope/harness/.

    Claim-by-claim check

    Claim Result Evidence
    queueDrain lists → reads → deletes with no ownership step, so two drainers over one shared directory can both return the same entry ID TRUE agent/bus/WorkspaceMessageBus.java:95 (listSorted) → :100 (readFileContent) → :126 (fs.delete(...), result discarded); entry ID is derived from the filename at :109, so both callers emit the identical entryId. No synchronized / ReentrantLock / CAS anywhere in agent/bus/
    …and deletion cannot serve as the ownership point today TRUE LocalFilesystem.java:529-555 implements delete as Files.exists + Files.delete (not deleteIfExists); RemoteFilesystem.java:596-611 returns WriteResult.ok unconditionally even when nothing matched
    queuePush can expose an entry before its payload is complete TRUE for LocalFilesystem (and the shell-backed sandbox fs); not applicable to the KV/remote backend WorkspaceMessageBus.java:83-85 writes straight to the listable path — no temp+rename, no ready marker, no lock. LocalFilesystem.java:328+:340 is a check-then-Files.writeString, so the path exists with 0 bytes before the body lands. Worse: LocalFilesystem.java:289-295 turns an empty file into a non-null "System reminder: File exists but has empty contents" string, so readFileContent returns non-null, the JSON parse fails, and the corrupt branch at WorkspaceMessageBus.java:115-125 deletes the entry — silent loss while queuePush reports success. RemoteFilesystem.java:264-277 (putIfVersion(ns, path, value, 0L)) has no torn-read window
    Proposed shape (ready marker after payload completion + atomic create-if-absent per-entry claim) is the right direction TRUE, with one hard prerequisite The AbstractFilesystem API has no atomic create-if-absent primitive: AbstractFilesystem.java:66-74 documents write as "error if file already exists", but only RemoteFilesystem.java:268 actually guarantees it; LocalFilesystem.java:328/:340 is TOCTOU (no CREATE_NEW), so a claim built on plain write can be won twice and the bug survives. Correct precedents already exist off-interface: agent/transcript/FilesystemTranscriptStore.java:62-63 (CREATE_NEW) and agent/sandbox/snapshot/LocalSandboxSnapshot.java:71-89 (temp + ATOMIC_MOVE)

    Root cause. The read-failure branch at WorkspaceMessageBus.java:101-108 is explicit — "Transient read failure (race with concurrent drain …). Do NOT delete — preserve the entry so the next drain can retry it" — so the window where the loser reads after the winner deleted is handled; the window where both read before either deletes is not. Both reported defects violate statements in the interface itself: agent/bus/MessageBus.java:29-31 ("Each entry is returned at most once") and :59-61 ("Returned entries are removed from the queue atomically").

    Same-class exposures the report does not cover (not required by its stated guarantees, but in the paths a fix touches):

    1. logAppend trim — WorkspaceMessageBus.java:155-163 is a list→delete loop with no ownership step: two concurrent appenders over one shared directory delete overlapping "excess" entries and can trim below maxLen, including entries the other just wrote.
    2. logRead — fromJson at :197 has no try/catch (unlike the queue at :115), so one partially published log entry makes the whole logRead / sessionReadEvents call throw instead of skipping a record.
    3. queuePush discards the write result at :85: if the path already exists (LocalFilesystem.java:328 → WriteResult.fail) the payload is silently dropped and the returned ID still names somebody else's entry. IDs are seeded from System.nanoTime() (:63, :233-235), so two buses constructed in the same clock tick can collide — and because drain sorts by path (:260), cross-instance "arrival order" (MessageBus.java:66) is really instance-creation order.
    4. agent/bus/WorkspaceAsyncToolRegistry.java:125-147 — read → delete → write status update with no ownership guard; concurrent complete/markTimeout can lose a transition (same pattern, adjacent class).

    Testability. agent/bus/WorkspaceMessageBusTest.java is entirely sequential; the closest case to this topology, twoInstancesShareSameDirectory (:194-206), is strictly sequential — its concurrent variant fails today. Neither guarantee is guarded by any test, and both are reproducible with a barrier wrapper around ls/read plus @TempDir and LocalFilesystem — no external service needed (the RecordingFilesystem extends LocalFilesystem pattern at agent/middleware/ToolResultEvictionMiddlewareTest.java:418 shows the shape).

    PR route. @liugy789 PR #3281 (OPEN, +741/-60, same author as this issue) already implements exactly this shape — .payload + .ready publication plus an atomic claim threaded through AbstractFilesystem / LocalFilesystem / RemoteFilesystem / BaseSandboxFilesystem / MemoryStoreFilesystem, with legacy .json draining preserved — and it states plainly that claims are not leased. No automated PR from us: a second generated patch would duplicate community work, and #3281 will be reviewed on the scheduled PR rotation, where the items above (claim artifacts vs the *.json matcher, delete-after-read ownership, crash/lease trade-off, and the logAppend/logRead windows) get inline review.

    Caveats. Static review only — nothing was compiled or reproduced here; the probability of either race (microseconds locally, plausibly wider on NFS/EFS-mounted shared workspaces) and the nanoTime ID-collision rate are code-path observations, not observed failures. Also worth a doc decision: MessageBus.java:42 calls WorkspaceMessageBus a "single-process" implementation while WorkspaceMessageBus.java:39-41 presents a shared backend as the cross-process route — the interface contract carries no single-process caveat, and the in-same-JVM two-instance case is unambiguously affected either way.


    Automated evaluation by github-manager-bot

  5. added a commit that references this issue on Nov 11, 2026
    bedf292
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/harnessbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions