Skip to content

fix(harness): claim workspace queue entries atomically - #3281

Merged
juruoO-o merged 4 commits into
agentscope-ai:mainfrom
liugy789:fix/atomic-workspace-queue-drain
Nov 11, 2026
Merged

juruoO-o merged 4 commits into
agentscope-ai:mainfrom
liugy789:fix/atomic-workspace-queue-drain

Conversation

@liugy789

@liugy789 liugy789 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #3280

AgentScope-Java Version

2.0.4-SNAPSHOT (contribution based on main at fefc196)

Description

Fixes a race in which concurrent WorkspaceMessageBus.queueDrain calls can both return the same entry. It also prevents drainers from seeing a queue entry before its payload write has completed.

Before

Producer:   write E.json --------------------------------> complete
Drainer A:  list E -> read E ---------------------------> return E -> delete E
Drainer B:        list E -> read E -> return E -> delete E

After

Producer:   write E.payload -> finish -> publish E.ready

Drainer A:  list E.ready -> create E.ready.claim (atomic) -> winner
Drainer B:  list E.ready -> create E.ready.claim (atomic) -> conflict/skip

Winner:     read payload -> delete ready + payload -> delete claim

Implementation

  • Write queue payloads to {entryId}.payload; publish {entryId}.ready only after the payload write succeeds.
  • Preserve draining of legacy {entryId}.json entries.
  • Acquire an atomic create-if-absent claim before reading an entry.
  • Release a claim after a read failure so a later drain can retry.
  • Retain a claim when entry deletion fails, avoiding another delivery when the first result may already have been returned.
  • Surface unexpected claim-storage failures instead of treating them as an empty queue; preserve entries already drained before a later claim failure.
  • Centralize already-exists results in WriteResult, so routed filesystem paths do not make a normal claim conflict look like a storage failure.
  • Keep MemoryStoreFilesystem explicitly non-atomic and unsuitable as a queue backend; its change only adopts the shared already-exists result factory.

The queue claim contract depends on the selected filesystem backend providing atomic create-if-absent writes. This change does not add leases, automatic recovery, or an acknowledgment/retry protocol.

Compatibility and behavior boundaries

  • New entries use .payload and .ready; older consumers that only scan .json will not see entries published by this version.
  • The new implementation can still drain legacy .json entries. Mixed-version consumers must not concurrently drain the same queue because older consumers do not understand the new format or claim markers.
  • Claims are not leased. A process crash after claiming can leave an entry unavailable until operator-led recovery.
  • queueDrain remains destructive; this does not provide end-to-end exactly-once processing.
  • The API/class Javadocs were updated. No separate documentation page was changed because the existing distributed-storage guidance remains applicable.

Tests

  • WorkspaceMessageBusTest (27 tests): concurrent drains for new and legacy entries, publish/read interleaving, legacy draining, missing payloads, claim-storage failures, partial results, and routed claim conflicts.
  • BaseSandboxFilesystemTest (28 tests): exclusive claims, existing-path conflicts, error classification and diagnostics, cleanup failures, and placeholder upload behavior.
  • DockerSandboxFileTransferIntegrationTest.filesystemWriteUploadsOverExclusivePlaceholder verifies the real Docker-backed placeholder/upload behavior.
  • ManagedMemoryAccessTest (2 tests) covers the MemoryStore-related change.

Verification

  • mvn -ntp -pl agentscope-harness,agentscope-service/service-dataplane spotless:apply — passed; no files needed formatting.
  • mvn -ntp -pl agentscope-harness,agentscope-service/service-dataplane spotless:check — passed.
  • WorkspaceMessageBusTest: 27 tests, 0 failures, 0 skipped.
  • BaseSandboxFilesystemTest: 28 tests, 0 failures; 5 skipped by macOS platform conditions.
  • ManagedMemoryAccessTest: 2 tests, 0 failures, 0 skipped.
  • Docker integration test: 10 tests, 0 failures, 0 skipped.

Checklist

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (API/class Javadocs)
  • Code is ready for review

@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Replaces the racy ls + read + delete drain with a two-phase publish ({id}.payload + {id}.ready) plus an atomic create-if-absent claim ({id}.ready.claim), centralizes the already-exists result in WriteResult, and hardens LocalFilesystem (CREATE_NEW) and BaseSandboxFilesystem (noclobber) so the claim primitive is real on those backends. This is a careful change — the concurrency and failure-injection tests are exactly what this kind of fix needs, and the docs on the at-most-once / no-lease boundaries are honest. CI and CLA are green. I am leaving this as comments rather than an approval for the three items below, the first of which can wedge a queue.

Findings

  • [Warning] WorkspaceMessageBus.java:352 — deleteQueueEntry deletes the payload before the .ready marker; a failed payload delete (or a crash in between) leaves a permanently un-drainable ghost that also keeps queuePeek true.
  • [Warning] BaseSandboxFilesystem.java:201 — the claim now depends on set -C in whatever shell execute() uses, and the class Javadoc does not state which backends actually guarantee atomic create-if-absent.
  • [Warning] WriteResult.java:46 — isAlreadyExists() matches on message prefix/suffix, making a human-readable string the contract for distinguishing "contended" from "storage failure".
  • [Info] WorkspaceMessageBus.java:146 — three claim outcomes are handled inline; a small enum would keep the "return partial results vs. throw" rule obvious.
  • [Info] WorkspaceMessageBus.java:52 — entry ids are seeded per process, so cross-node ordering is not really guaranteed; worth stating next to the delivery-semantics wording.

Suggestions

  • Reverse the delete order (.ready first, then .payload), or fall through so the marker is always attempted, and add a test for the "payload deleted but marker removal failed" state.
  • If set -C stays, name the shell requirement explicitly (and consider ln -s/O_EXCL as the primitive); a SandboxBackedFilesystem that cannot guarantee exclusivity should be documented as unsuitable for WorkspaceMessageBus, the way MemoryStoreFilesystem now is.
  • Prefer a structured already-exists signal on WriteResult over message matching.

Compatibility note

Mixed-version rollouts are the sharpest edge here: consumers that only scan .json will not see entries published by this build, so a rolling upgrade of a distributed deployment needs all drain-side instances moved together. Explicitly flagging this in the release notes (not just the PR description) would help operators.


Automated review by github-manager-bot

}
String payloadPath = path.substring(0, path.length() - ".ready".length()) + ".payload";
return readFileContent(payloadPath);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change in deleteQueueEntry: delete the .ready marker first, then the payload.

As written, if fs.delete(payloadPath) fails, the method returns early and the .ready marker survives with no payload. The entry is then listed forever: claim → readQueueEntryContent returns null → releaseClaim → repeat on every drain. queuePeek also stays permanently true, and the blocking entry is never garbage collected (only the crash-between-the-two-deletes case can produce such a ghost, but it is enough to wedge a queue).

Deleting .ready first inverts that: a mid-way failure leaves an orphan .payload that is invisible to listQueueEntries instead of an un-drainable ghost. The test missingPayloadDoesNotConsumeDrainLimit covers the symptom but not this recovery path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7d8f1f9. deleteQueueEntry now removes .ready before .payload; the failure-injection test verifies that a failed marker deletion retains the payload.

+ " ]; then echo 'EXISTS'; exit 1; fi; "
+ "mkdir -p \"$(dirname "
+ ")\" 2>&1 || exit 1; "
+ "if (set -C; : > "

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two related concerns with the new noclobber claim:

  1. Shell dependency. set -C is a bash/ksh feature (also in POSIX sh, but with the well-known empty-prefix caveat for : > file). If execute() here runs the command through a non-bash shell in some sandbox image, the guard can silently stop being exclusive. Since WorkspaceMessageBus correctness now depends on this primitive, please make the requirement explicit (Javadoc on BaseSandboxFilesystem.write / the sandbox image contract) or use ln <tmp> <path> / open(O_CREAT|O_EXCL), which are closer to a universally atomic create-if-absent.
  2. Failure leaves a 0-byte file. When mkdir -p on a shared parent races, the other writer's file makes the noclobber redirect fail with EXISTS even though this call never wrote anything; and when uploadFiles fails after a successful claim, delete() rolls the placeholder back, so a concurrent waiter can observe the path appearing and disappearing. Both are fine for the queue protocol, but the Javadoc should state which backends actually give atomic create-if-absent.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Documented the POSIX-shell set -C requirement and the atomic create-if-absent requirement for queue backends. Empty markers now retain the exclusive placeholder without a separate upload.

public boolean isSuccess() {
return error == null;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

String sniffing with startsWith + endsWith turns the human-readable message into a wire contract: rewording either constant in any backend silently converts a claim conflict into "storage failure", which in queueDrain escalates to a thrown IllegalStateException on an otherwise healthy queue.

WriteResult is already a type in the public model package, so a structured signal is cheap here — e.g. add an AlreadyExists boolean/error-kind field (or return a sealed result / dedicated WriteResult.alreadyExists marker type) and have RemoteFilesystem / LocalFilesystem / MemoryStoreFilesystem produce it. That also removes the need for the message suffix to stay in sync across backends.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WriteResult now carries a structured alreadyExists signal instead of inferring it from the error message. A regression test covers a matching message on a non-conflict failure.

throw new IllegalStateException(
"queueDrain: failed to claim entry "
+ fi.path()
+ " ("

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor readability point: this !claim.isAlreadyExists() branch mixes three outcomes (contended claim, storage failure with nothing drained, storage failure after partial success). Extracting something like claimOutcome(claimPath) returning CLAIMED | CONTENDED | FAILED would make the control flow — and the "return what we already have vs. throw" rule — much easier to follow for future changes.

* be shared (for example a remote/KV-backed store); a pure local disk backend remains
* single-process.
*
* <p>Mode D (pub/sub) is degraded to polling: {@link #subscribe} returns a {@code Flux} that emits

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth calling out explicitly in the class Javadoc that entry ids are generated from a per-process System.nanoTime() seed, so sorted(Comparator.comparing(FileInfo::path)) orders by id string rather than by cross-process publish time. Not introduced here, but "at-most-once delivery" reads like an ordering guarantee to some readers, so it is worth stating whether FIFO across nodes is expected at all.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Re-review after the new commit 7d8f1f9. All three items from my previous review are addressed properly, and each fix comes with a targeted test — this is ready from my side.

What changed since the last review

  • Delete order fixed (WorkspaceMessageBus.deleteQueueEntry): .ready is now removed before .payload, so a partial failure can no longer leave an un-drainable ghost entry that keeps queuePeek true. failedReadyDeletionRetainsPayloadForRecovery covers the new failure window.
  • Structured already-exists signal (WriteResult.alreadyExists): message-prefix matching is gone; the flag is a real record field, with the legacy two-arg constructor preserved so existing backends keep compiling. WriteResultTest explicitly asserts that text matching alone is no longer treated as a conflict.
  • Sandbox claim contract documented (BaseSandboxFilesystem Javadoc): the set -C requirement and the "a backend without exclusive create must not back WorkspaceMessageBus" rule are now explicit, which was the main ambiguity before.
  • Ordering caveat documented: the per-instance nanoTime() id seed and the failed-publication semantics are called out in the class Javadoc.
  • Release notes: the mixed-version .payload/.ready rollout constraint is now in both the en and zh release notes — that closes the compatibility concern from the last round.

Findings

  • [Info] WorkspaceMessageBus.java:124 — retained payloads/claims after a failed publication are now the only new garbage path; consider documenting or pruning them in a follow-up.
  • [Info] BaseSandboxFilesystem.java:226 — the empty-content early return is correct but depends on an implicit set -C + exit-code contract; the Javadoc now names it.

Neither blocks merging. CI (build windows/ubuntu) is still in progress at review time.


Automated review by github-manager-bot

"queuePush: publication of {} failed ({}); retaining payload {}"
+ " for possible drain or operator recovery",
readyPath,
publish.error(),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Retaining the payload on a failed publication is the right call (a failed write does not prove the marker is ours to remove), but it does mean .payload and .ready.claim files can now accumulate with no .ready entry to discover them — queuePeek/queueDrain will not see them, and only an explicit queueDelete(key) removes the whole queue directory. Worth a follow-up note in the operator-recovery doc (or a periodic prune of orphan *.payload/*.claim files) so "operator-led recovery" has a concrete mechanism behind it.

}

if (content.isEmpty()) {
return WriteResult.ok(filePath);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

content.isEmpty() short-circuit relies on set -C having created the placeholder and on execute() exit codes being trustworthy; checkCmd also ends with exit 1 on the EXISTS/CreateFailed paths, so the contract is implicit. Naming it in the Javadoc (already partially done) plus this early return makes the semantics clear enough — just make sure non-POSIX shells in execute() implementations are actually covered by the existing tests (the Docker integration test update suggests they are).

@liugy789

Copy link
Copy Markdown
Contributor Author

On the informational points from the earlier review: the WorkspaceMessageBus Javadoc now states that per-instance ID seeds do not guarantee FIFO across processes, and both English and Chinese release notes document the mixed-version rollout constraint. I left the claim-outcome enum out of this change to keep the fix focused; the three outcomes remain at a single call site.

@jujn jujn added the P0 重要紧急 label Nov 4, 2026
…queue-drain

# Conflicts:
#	agentscope-harness/src/main/java/io/agentscope/harness/agent/filesystem/sandbox/BaseSandboxFilesystem.java
#	agentscope-harness/src/test/java/io/agentscope/harness/agent/bus/WorkspaceMessageBusTest.java
#	agentscope-harness/src/test/java/io/agentscope/harness/agent/filesystem/sandbox/BaseSandboxFilesystemTest.java
#	docs/v2/en/docs/others/release-notes.md
#	docs/v2/zh/docs/others/release-notes.md
@mintlify

mintlify Bot commented Nov 11, 2026

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit e24c683.

Approve preview

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ liugy789
❌ ”zhuzhiyu.zzy“


”zhuzhiyu.zzy“ seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@juruoO-o
juruoO-o merged commit bedf292 into agentscope-ai:main Nov 11, 2026
8 of 9 checks passed
chickenlj pushed a commit that referenced this pull request Nov 13, 2026
Backport the verified fix to the 2.0.x implementation and retain its existing public contracts where the upstream kernel differs.

(cherry picked from commit bedf292)
Backport-review-patch: b51c8e5cf647f28db5f8ad9d8e666e6b3b08b645
Constraint: No AgentScope Service or SDK migration
Confidence: high
Not-tested: Whole-repository verification pending after lane integration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P0 重要紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

5 participants