Skip to content

feat(agui): queue messages that arrive during an active run - #4281

Open
ck-ys wants to merge 13 commits into
agentscope-ai:mainfrom
ck-ys:feat/agui-message-queue
Open

ck-ys wants to merge 13 commits into
agentscope-ai:mainfrom
ck-ys:feat/agui-message-queue

Conversation

@ck-ys

@ck-ys ck-ys commented Nov 20, 2026 •

Copy link
Copy Markdown

AgentScope-Java Version

2.1.0-SNAPSHOT

Description

Refs #4223.

Correction (2026-11-21): an earlier version of this description said the claim re-checks an attached client and reported 522 tests. The claim is pull-only and has no connected-client state, and the module runs 620 tests; the text below is the corrected version.

This adds a bounded, per-thread FIFO for messages that arrive while a run is active, or that a client chooses to queue while the thread is idle, plus the HTTP surface a client needs to accept, inspect, claim and withdraw them.

  • One queue per thread, capacity 16 by default (agentscope.agui.queue.capacity), 429 when full.
  • Acceptance answers with the message id and, while the message is still queued, its position; position is -1 once the message has left the queue. The statuses are ACCEPTED, DUPLICATE, CONFLICT for the same id with a different trailing message, and FULL at capacity.
  • FIFO is fixed at acceptance. Claiming consumes: a queued entry is delivered at most once and never returned to the queue. A claimed input is not de-duplicated by the run endpoint, so replaying it twice would execute it twice.
  • DELETE /agui/queue/{threadId}/{messageId} withdraws a message that has not been claimed.
  • Off by default (agentscope.agui.queue.enabled=false): existing users see no change in behaviour.

Claim, replay and the hand-off guard

Claim and execution are two requests. A claim hands the message to the client, which then posts it to /agui/run; between the two the thread genuinely is idle, so without a guard a second claim in that gap would hand out the next message, which the active-run check would then reject after it had already left the queue.

At claim time the server re-reads the thread state under the same striped thread-state lock that a run start takes. It removes the head of the queue only while no run is active and no interrupt is unresolved. If the thread is still busy when the recheck runs, the claim returns 204 and the message stays queued; a run that started and finished while the claim waited leaves the thread idle, so the recheck does not refuse on that ground. Two concurrent claims are serialised by the queue, and the hand-off guard stops the second one within the hand-off window.

There is no separate attached-client flag, because there is no server-initiated dispatch: the queue never starts a run, and a claim request is the only way a message is delivered to a client. That request proves a client was reachable when it was sent; it does not prove that the response arrives or that the client replays the message. A claim already in flight when the client disconnects can therefore still consume the message, which is the at-most-once hand-off boundary below.

After a hand-off the queue stays closed until a later claim sees the run id it handed out (the replay), or observes the thread busy after the delivery, with five seconds as the fallback when neither arrives.

Withdrawal keeps the id protected

A withdrawn message keeps its id in the ledger as WITHDRAWN for the retention window. A retry of the original submission that reaches the server after the withdrawal response was lost is therefore acknowledged as DUPLICATE instead of being queued and executed again, which is what the queue contract asks for: a withdrawn id stays protected while it is retained. Reusing a retained id with a different trailing message is still rejected with 409. Both documentation pages describe the state and the behaviour.

Keeping that identifier costs a ledger entry, so eviction now skips ids whose message is still queued. Without that, a burst of withdrawals could evict a waiting message, and its retry would be accepted under a new body instead of rejected as a conflict. The retention bound still applies to everything else.

Boundaries

  • Same process only; no cross-replica coordination in this slice.
  • Delivery is at most once: a claimed message is not redelivered.
  • The gap between a claim and its replay is not transactional. If the client crashes, the claim response is lost, or another run starts on the thread first, the claimed message is lost. The five-second guard closes further claims, not run starts. The claim-time lock closes the check-then-dequeue race, not this hand-off race.
  • No connected-client registry. Dispatch is pull-only, so the queue cannot push a run into a disconnected session, but it also cannot verify that a claim response reached the client. A disconnect after the claim request was sent does not cancel the dequeue.
  • The issue also asked for an attached-client recheck and a test that disconnects the client before release. This slice has no connection state to recheck and no server-side dispatch that could target a disconnected session, so the disconnect half is not covered; the recheck covers idleness and unresolved interrupts, and the pause tests cover a run start and an unresolved interrupt.
  • The queue registry and the per-thread run-id map are not evicted. A thread that never returns keeps its queue and its run-id entry for the life of the process.
  • A claimed or withdrawn id is protected only while it is retained: the ledger keeps up to idempotency-retention ids per thread, and after eviction the id can be submitted again. An id whose message is still queued is never evicted.
  • The two convenience claim overloads that pass no run-id evidence are package-private; the HTTP layer goes through AguiRequestProcessor.claimIfIdle, which uses the full overload with the run-id evidence.

Known item

AguiRequestProcessor.Builder.recordLastRunId defaults to true. The map behind it backs the hand-off guard and costs one entry per thread that ever started a run; the Spring starters turn it off when the queue is off. A processor built directly against this extension therefore keeps recording with no queue to serve. Defaulting it to false would move that cost onto the only setup that needs it, at the price of an explicit line for anyone wiring the queue by hand. The coordinator also allocates its 64 striped locks unconditionally, so flipping the default would not remove that allocation; it only stops the per-thread run-id entry. Left as is; say the word and I will flip it.

Tests

spotless:check passes. The reactor for the two queue modules, built with -am, passes on this branch: the agui extension module runs 620 tests across 25 classes and the starter runs 89, both green; the upstream modules it builds also pass (core 3479, with DangerousPathBypassTest excluded). That core class cannot create symlinks on this Windows host, so the unexcluded gate run fails there; the module run excludes it by class name. CI runs the full build on Linux and Windows. The pause-after-idle tests are not excluded.

Tests that cover this change:

  • AguiRequestProcessorTest.claimIfIdleDoesNotDeliverWhenARunStartsAfterTheIdleObservation — pause after the first idle observation, start a run before the claim is released: the claim returns empty, the message is still queued, and the refused claim invokes no model. After the run ends, the same message is delivered and replayed exactly once.
  • AguiRequestProcessorTest.claimIfIdleDoesNotDeliverWhileAnInterruptIsUnresolved — the same pause, but the run that starts before the release finishes with an unresolved interrupt: the claim returns empty, the message stays queued, and no model runs. After the interrupt is answered, the message is claimed and replayed once.
  • AguiRequestProcessorTest.claimIfIdleDoesNotDeliverWhileARunIsActive — the busy fast path leaves the message queued.
  • ThreadMessageQueueTest.shouldKeepTheIdentifierProtectedAfterWithdraw — withdraw, then retry the same trailing message under a different run id: DUPLICATE with state=WITHDRAWN, nothing claimable, and a different trailing message under the same id still CONFLICT.
  • ThreadMessageQueueTest.shouldNotEvictAQueuedIdentifierWhenWithdrawalsFillTheLedger — with a two-entry ledger, withdrawals plus a new message must not evict the message that is still waiting, so its retry stays DUPLICATE and a changed body stays CONFLICT; the withdrawn entry is the one evicted, so reusing its id is no longer treated as a conflict.
  • ThreadMessageQueueTest.shouldCompareOnlyTheTrailingMessageForDuplicates — an earlier message may differ and the submission is still a retry.
  • AguiQueueControllerTest.shouldAcknowledgeARetryAfterWithdrawAsADuplicate — the withdraw-then-retry sequence over HTTP.
  • AguiRequestProcessorTest.threadIsNotIdleWhileAnInterruptAwaitsItsAnswer — a real processor run leaves an interrupt open, isThreadIdle is false while isRunActive is false, and it becomes idle again once the resume is processed.

The documentation build validation passes for both the English and the Chinese page.

Checklist

  • Code has been formatted (mvn spotless:check passes)
  • All module tests are passing (mvn test on the reactor described above; the Windows symlink exclusion is described there)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (e.g. links, examples, etc.)
  • Code is ready for review

- release the 5 s window only when the run id handed out at delivery is the
  id the thread started, or when a later busy observation proves the thread
  moved on; the window stays as the fallback for a claim that is never
  replayed
- validate retention >= capacity at construction
- answer 400 for bodies with the messages or resume field absent instead of
  failing with 500, and clamp the window arithmetic at Long.MAX_VALUE
- record the last started run id only while the queue is enabled
- cover the above with queue, coordinator and controller tests
…boundaries

Covers acceptance and claim status codes, the idempotency fingerprint, the
identity-based release of the hand-off window, the resume rules, the
single-process and at-most-once boundaries, and the request-body edge cases.
- skip ids whose message is still queued when the ledger evicts, so a burst of
  withdrawals cannot drop a waiting message and let its retry in with a new body
- keep the withdrawn entry itself evictable once the ledger overflows, and
  cover both halves of the boundary in ThreadMessageQueueTest
- list the forgotten id as a 404 source in the withdraw endpoint javadoc
@mintlify

mintlify Bot commented Nov 20, 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 f0f9002.

Approve preview

… off

The claim read idleness and run evidence in the controller before entering
the queue lock. A run that started between that read and the dequeue still
received the message; the client's replay was then rejected as a concurrent
run, and under at-most-once hand-off the message was already gone.

Move the check into AguiRequestProcessor.claimIfIdle: re-read idleness and
the run evidence while holding the per-thread state lock that beginRun,
finishRun and trackPendingInterrupts take, and dequeue inside that lock.
Add the deterministic pause-after-idle test requested in the issue.
The claim re-reads the thread state when the request arrives and shares a
lock with starting a run, so a run start either makes the recheck fail or
waits for the dequeue. Say that instead of leaving the old wording, and
spell out that "busy" includes an unresolved interrupt.
…pt pause

The claim now takes its observation timestamp inside the thread-state lock,
so a lock wait cannot leave the hand-off window anchored before another
delivery. Read the run evidence before the idle state, matching the queue
contract, and say in the Javadoc that the busy fast path does not recheck.

Cover the unresolved-interrupt half of the pause the issue asked for, and
the busy fast path, so both rechecks have a direct test. Release the claim
thread and the run subscription on failure paths.
A run that is still active at the recheck keeps the message queued; a run
that finished while the claim waited leaves the thread idle. Say that
instead of implying every earlier run start keeps the message queued, and
describe the lock as per-thread striped.
A busy observation opens the hand-off window only when it was taken after
the delivery. The ledger keeps up to the retention count and evicts the
oldest non-queued entry, rather than the last N ids inserted.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant