Repository navigation
fix(harness): claim workspace queue entries atomically - #3281
Conversation
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
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—deleteQueueEntrydeletes the payload before the.readymarker; a failed payload delete (or a crash in between) leaves a permanently un-drainable ghost that also keepsqueuePeektrue. - [Warning]
BaseSandboxFilesystem.java:201— the claim now depends onset -Cin whatever shellexecute()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 (
.readyfirst, 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 -Cstays, name the shell requirement explicitly (and considerln -s/O_EXCLas the primitive); aSandboxBackedFilesystemthat cannot guarantee exclusivity should be documented as unsuitable forWorkspaceMessageBus, the wayMemoryStoreFilesystemnow is. - Prefer a structured already-exists signal on
WriteResultover 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); | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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; : > " |
There was a problem hiding this comment.
Two related concerns with the new noclobber claim:
- Shell dependency.
set -Cis a bash/ksh feature (also in POSIXsh, but with the well-known empty-prefix caveat for: > file). Ifexecute()here runs the command through a non-bash shell in some sandbox image, the guard can silently stop being exclusive. SinceWorkspaceMessageBuscorrectness now depends on this primitive, please make the requirement explicit (Javadoc onBaseSandboxFilesystem.write/ the sandbox image contract) or useln <tmp> <path>/open(O_CREAT|O_EXCL), which are closer to a universally atomic create-if-absent. - Failure leaves a 0-byte file. When
mkdir -pon a shared parent races, the other writer's file makes the noclobber redirect fail withEXISTSeven though this call never wrote anything; and whenuploadFilesfails 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.
There was a problem hiding this comment.
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; | ||
| } | ||
|
|
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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() | ||
| + " (" |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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):.readyis now removed before.payload, so a partial failure can no longer leave an un-drainable ghost entry that keepsqueuePeektrue.failedReadyDeletionRetainsPayloadForRecoverycovers 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.WriteResultTestexplicitly asserts that text matching alone is no longer treated as a conflict. - Sandbox claim contract documented (
BaseSandboxFilesystemJavadoc): theset -Crequirement and the "a backend without exclusive create must not backWorkspaceMessageBus" 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/.readyrollout 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 implicitset -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(), |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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).
|
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. |
…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
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
|
”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. |
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
Fixes #3280
AgentScope-Java Version
2.0.4-SNAPSHOT (contribution based on
mainatfefc196)Description
Fixes a race in which concurrent
WorkspaceMessageBus.queueDraincalls can both return the same entry. It also prevents drainers from seeing a queue entry before its payload write has completed.Before
After
Implementation
{entryId}.payload; publish{entryId}.readyonly after the payload write succeeds.{entryId}.jsonentries.WriteResult, so routed filesystem paths do not make a normal claim conflict look like a storage failure.MemoryStoreFilesystemexplicitly 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
.payloadand.ready; older consumers that only scan.jsonwill not see entries published by this version..jsonentries. Mixed-version consumers must not concurrently drain the same queue because older consumers do not understand the new format or claim markers.queueDrainremains destructive; this does not provide end-to-end exactly-once processing.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.filesystemWriteUploadsOverExclusivePlaceholderverifies 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.Checklist
mvn spotless:applymvn test)