Skip to content

fix(agui): share resume coordination state across replicas - #2890

Open
ordinary-s wants to merge 6 commits into
agentscope-ai:mainfrom
ordinary-s:fix/agui-shared-resume-state
Open

ordinary-s wants to merge 6 commits into
agentscope-ai:mainfrom
ordinary-s:fix/agui-shared-resume-state

Conversation

@ordinary-s

@ordinary-s ordinary-s commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #2773. AG-UI resume requests can reach a different replica from the one that recorded an interrupt. This PR moves pending interrupts and active-run ownership behind a shared store so replicas validate the same pending state and compete for one atomic claim.

Implementation

  • Add AguiResumeStateStore with immutable pending snapshots, atomic claim, owner-checked release, and atomic owner-checked pending replacement. Keep InMemoryAguiResumeStateStore as the default.
  • Add RedisAguiResumeStateStore, backed by one Redis hash per thread and Lua scripts. Claim before validating resume input; stale runs cannot overwrite pending state or release another run's owner.
  • Support explicit processor store injection and optional Spring store beans in both MVC and WebFlux.

Request lifecycle and recovery

  • Run synchronous resume-store calls on Reactor's boundedElastic scheduler, including pending writes and cleanup after cancellation. Ordinary token events do not require a separate blocking task.
  • Use a per-subscription resource to coordinate claim, state writes, and cleanup. Cancellation waits for an in-flight storage operation before releasing a confirmed claim; rejected or indeterminate claims are never blindly released.
  • Convert claim, validation, resume-injection, and pending-write failures into AG-UI RUN_ERROR events. Emit RUN_STARTED only if it has not already been sent, respect emitRunFinishedAfterError, and withhold the successful RUN_FINISHED when its pending write fails.
  • Attempt owner-checked release at most three times, with 50 ms and 100 ms retry delays, on completion, error, or cancellation. Log failed attempts, recovery, and exhaustion with thread/run IDs, phase, attempt count, and the exception. Retry only release, never agent execution.
  • Preserve the original processing exception and attach exhausted cleanup failures as suppressed exceptions. Cleanup failures are logged rather than emitted as dropped Reactor errors or a second terminal lifecycle.
  • Document asynchronous disposal, finite client timeouts, logging alerts, and administrative recovery that preserves pending interrupts in the English and Chinese v2 guides.

Validation

Validated on JDK 21 with Java 17 compilation, including a disposable Redis 7.4 instance and actual Reactor Netty HTTP connections:

  • 517 AG-UI tests passed.
  • 12 Redis tests passed, including 7 real Redis recovery and failure-lifecycle cases (-Dagui.redis.integration=true; local port 16389, configurable via -Dagui.redis.port).
  • 56 Spring configuration, resolver, session, and HTTP cases passed, including store selection, SSE errors, disconnect behavior, and contextual cleanup logging on completion/error/cancellation.
  • 5 MVC controller cases passed in a separate targeted run.
  • New lifecycle coverage includes cancellation during claim, bounded cleanup retries, lost release replies, same-run-ID rejected claims, preservation of pending state after errors, and storage calls off nonblocking threads.
  • Repository-wide mvn spotless:check and git diff --check passed.

Recovery limits

Release retries are bounded best effort; this PR does not introduce leases, fencing tokens, or TTL-based crash recovery. Exhausted cleanup, a process crash, or a lost claim reply can leave ownership behind. A claim with an unknown outcome is reported as an error without automatic claim retry or release.

Use fresh run IDs because they also identify ownership. Before administrative releaseRun(threadId, oldRunId), confirm that the old agent, tools, and cleanup attempts have stopped. This owner-checked operation preserves pending interrupts; deleting the whole Redis key would lose resume state. Tools that ignore cancellation may outlive the protocol subscription, and a write whose reply was lost may already have committed.

@ordinary-s

Copy link
Copy Markdown
Contributor Author

The CI failure appears to be caused by the known flaky @tempdir cleanup race in agentscope-harness (DirectoryNotEmptyException, tracked in #2251). This PR does not modify the agentscope-harness module, and the failure occurred before the AG-UI/Redis modules were reached in the reactor build. Could someone please re-run the failed job when convenient?

@codecov

codecov Bot commented Aug 29, 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

First review of this PR (never reviewed before). Replacing the coordinator's in-memory activeRunsByThread / pendingInterruptsByThread maps with the AguiResumeStateStore SPI (in-memory + Redis implementations, atomic Lua claim/release/replace) is the right shape for stateless horizontal scaling: ownership is now an explicit RunClaim, releaseRun is a conditional delete, replacePendingInterrupts is owner-checked in both implementations (the in-memory one compares state.activeRunId(), the Redis script compares ACTIVE_RUN_FIELD), and a store failure is propagated instead of being treated as missing state — which is the failure mode that would otherwise silently allow two concurrent runs for one thread. AguiRunLifecycle + Flux.usingWhen make claim/setup/cancel/release one unit, and the test set is unusually thorough for this area (cross-replica resume, duplicate-rejected-claim-must-not-release-the-owner, lost-release-reply retry, cancel-during-claim, non-blocking-thread offload).

Coverage caveat, so this is not read as a full sign-off: the diff is +2608/-105 over 22 files. This pass read the AG-UI core (AguiRequestProcessor, AguiResumeCoordinator, AguiRunLifecycle, AguiResumeStateStore, the in-memory store) and the Redis store's owner-check/claim paths in full, and the Spring starters/tests only as a summary. No build or test run was possible here — this host has no JDK 17 or Maven (runtime-env reports all toolchains [NOT FOUND]), so the concurrency claims are unverified by execution.

One concern is inline: the contract-error path in AguiRequestProcessor leaves an already-claimed run to be released by the usingWhen completion handler, so a subscriber that never applies demand can pin the thread's owner slot.


Automated review by github-manager-bot

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently conflicts with main and cannot be merged as-is. Please rebase (or merge main) and resolve the conflicts:

git fetch origin
git checkout fix/agui-shared-resume-state
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

This is a one-time reminder. Feel free to @mention me for a re-review after the conflicts are resolved.


Automated notification by github-manager-bot

Release acquired ownership before emitting contract errors, sharing one cleanup process and release retry budget. Keep automatic disconnect interruption within the validated subscription lifecycle and finish it before release to protect a newer owner.

Add deterministic lifecycle and transport regression coverage, real Redis handoff tests, bounded waits, and document the cleanup contracts.
@ordinary-s
ordinary-s force-pushed the fix/agui-shared-resume-state branch from 168c76f to 8944797 Compare September 15, 2026 16:44
@ordinary-s

Copy link
Copy Markdown
Contributor Author

The latest CI is now green, and the PR is mergeable without conflicts. @oss-maintainer could you please take another look when convenient?

@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

Since the last review round (commit 168c76f), 5 new commits landed, the largest being 8944797 "coordinate early cleanup and disconnect cancellation". Re-reviewed the full 25-file diff at head, focused on the ownership semantics:

  • SPI (AguiResumeStateStore): claimRun (create-if-absent), owner-checked releaseRun, and owner-checked atomic replacePendingInterrupts are correctly specified; InMemoryAguiResumeStateStore implements them atomically via ConcurrentHashMap.compute/computeIfPresent, and RedisAguiResumeStateStore implements them as three single-key Lua scripts. I verified both implementations agree on all edge cases I could construct (double claim, same-run-id reclaim, release of a non-owner, replace after release, pending-interrupt preservation across release).
  • Redis Lua scripts: KEYS/ARGV usage is correct, each script touches a single key (hash-slot safe in Redis Cluster), return false → nil maps correctly to RunClaim.acquired(), the release script is idempotent and preserves pendingInterrupts, and plain EVAL avoids NOSCRIPT issues. There is deliberately no TTL/lease on the coordination keys — this is explicitly documented as a bounded best-effort design with manual recovery steps, so it is a stated limit rather than a defect.
  • Ownership lifecycle (AguiRunLifecycle): the cached close().then(release()) cleanup (verified that Reactor's Mono.cache() does not cancel the source on subscriber cancel) gives one shared cleanup per subscription with a single 3-attempt/50–100 ms release retry budget; cancellation during an in-flight claim is serialized through the lifecycle monitor; a lost claim reply is treated as indeterminate and never blindly released; a lost release reply is safe because the release script is owner-checked and idempotent. Suppressed-exception attachment, RUN_STARTED at most once, and withholding RUN_FINISHED on a failed pending write all match the code.
  • Reactor: all store calls (claim, validate reads, pending writes, release, cancellation interrupt) run on boundedElastic; terminal events are delivered after cleanup completes; tests assert no dropped errors (Hooks.onErrorDropped) and no event-loop blocking.
  • Spring auto-config: MVC/WebFlux expose ObjectProvider<AguiResumeStateStore> and default to per-processor in-memory state when absent; interruptOnDisconnect now maps to the processor's interruptOnCancel with disposal-based cancellation. Backward compatible — only additive builder methods; no existing public signatures changed; the redis module pom addition follows the module's existing provided+optional pattern and both modules are already registered in agentscope-all/agentscope-bom.
  • Docs (en + zh): every behavioural claim I checked (cleanup budget and log levels, indeterminate claims, RUN_STARTED/RUN_FINISHED rules, no-TTL limits, manual releaseRun recovery) matches the implementation in both languages.
  • Tests: cancellation-during-claim, cross-coordinator/cross-replica races, lost replies, exhausted release, zero-demand cleanup, and run-id reuse are all covered — though the real-Redis cross-replica tests are opt-in (see findings).

Overall: no correctness defects found in the distributed-ownership core; the remaining findings are a CI test-coverage gap and two minor items.

Previous findings status

  • AguiRequestProcessor.java ~211 (UNRESOLVED from last round) — "On this path the run has already been claimed (beginRun invokes onClaimed before validate(input)), but the release only runs from the Flux.using resource cleanup..." → FIXED at head 8944797. prepareRun now handles the validation-failure path with run.finish("validation", null).thenMany(contractErrorEvents(...)) (AguiRequestProcessor.java:210-219), which runs the owner-checked release as part of the subscribed stream before the error events are delivered, even with zero downstream demand or a subscriber that never requests events. The claim/validate ordering is unchanged (AguiResumeCoordinator.beginRun(input, onClaimed) invokes onClaimed before validate), but every exit path — validation error, validate-read failure, synchronous setup failure, cancellation during claim, claim failure (indeterminate, no release) — now flows through Flux.usingWhen's complete/error/cancel hooks into the shared cached cleanup. Directly covered by AguiResumeLifecycleTest.contractErrorReleasesOwnershipWithoutDemand, validationReadFailureReleasesWithoutDemand, cancelDuringSuccessfulClaimWaitsForClaimAndReleasesWithoutRunningAgent, and the Redis-gated zeroDemandContractErrorAllowsReplicaResumeAndPreservesNewOwner.

Verdict

COMMENT — not a block: the ownership/claim-release core is correct and the previously raised leak path is fixed and regression-tested at 89447971. Only the CI coverage gap (real-Redis Lua scripts never execute in mvn verify) is worth addressing before merge; the two Info items are quick cleanups. CI is green on the current head and the PR is mergeable, so this is ready for a maintainer to look at once the unresolved thread can be resolved.

Findings

  • [WARNING] RedisAguiResumeLifecycleTest.java:67 — The only tests that exercise the cross-replica semantics of this PR against a real Redis — RedisAguiResumeLifecycleTest (lost release reply, indeterminate claim, exhausted release, zero-demand contract error across two stores) — are gated behind @EnabledIfSystemProperty(named = "agui.redis.integration", matches = "true") plus a local Redis on port 16389, and .github/workflows/maven-ci.yml runs plain mvn -B -T1 clean verify, so they never execute in CI. The always-on RedisAguiResumeStateStoreTest mocks jedis.eval(...) entirely, which means the actual Lua bodies (CLAIM_RUN_SCRIPT, RELEASE_RUN_SCRIPT, REPLACE_PENDING_SCRIPT — KEYS/ARGV indices, owner checks, the Lua false→nil reply mapping in claimRun, the conditional DEL in RELEASE_RUN_SCRIPT) are never executed by the default suite; a typo or semantic regression in any script would pass CI while silently breaking claim/release/ownership across replicas. I verified the scripts line-by-line and they look correct, so this is a coverage gap, not a known bug. Suggestion: run this test class in CI against an ephemeral Redis (testcontainers or a redis service container) by setting -Dagui.redis.integration=true, or at minimum add always-on unit tests asserting the exact script strings and the KEYS/ARGV composition for all three operations (today only releaseUsesOneOwnerCheckedRedisOperation and pendingReplacementReturnsOwnerCheckResultAndClearsWithSameOperation check argument lists, and neither validates the script text or its Lua semantics).
  • [INFO] RedisAguiResumeStateStore.java:152 — The two AguiResumeStateStore implementations disagree on blank identifiers: RedisAguiResumeStateStore.key() → requireIdentifier throws IllegalArgumentException for a blank/whitespace threadId, while InMemoryAguiResumeStateStore only does Objects.requireNonNull (e.g. getPendingInterrupts at InMemoryAguiResumeStateStore.java:33 accepts ""). A request with threadId="" is therefore processed normally with the default in-memory store but fails with RUN_ERROR/INVALID_INPUT_ERROR once a shared Redis store is configured — exactly the kind of deployment-dependent behaviour change the SPI is meant to prevent, and the AguiResumeStateStore javadoc does not state any identifier requirements. Suggestion: document the threadId/runId identifier contract (non-null, non-blank) on the AguiResumeStateStore interface and align InMemoryAguiResumeStateStore to reject blank values the same way, so both stores behave identically for malformed inputs.
  • [INFO] AguiResumeLifecycleTest.java:148 — contractErrorReleasesOwnershipWithoutDemand contains a leftover System.out.println("C01: acquired=...") debug block (lines 148–158) that dumps internal claim/cleanup state on every run of the test. It adds noise to CI output and looks like an unfinished debugging aid from the commit that introduced the test. Suggestion: delete the println block — the surrounding assertTrue(...)/latch assertions already capture the same state — or replace it with a targeted assertion message if some of that detail was meant to be kept.

Automated review by github-manager-bot — re-review after the rebase/fix push; replying to the request for re-review.

@ordinary-s

Copy link
Copy Markdown
Contributor Author

The latest CI is now green, and the PR is mergeable without conflicts. @oss-maintainer could you please take another look when convenient?

@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

The new commit is a clean response to the identifier-contract feedback: AguiResumeStateStore now states the contract (non-null, non-blank, used raw — no trimming), InMemoryAguiResumeStateStore and RedisAguiResumeStateStore validate identically via one helper, the Redis tests prove rejection happens before any Jedis interaction (verifyNoInteractions), and the validThreadIdIsUsedWithoutNormalization cases lock in the raw-key semantics on both backends. The new redis-integration CI job — real redis:7.4.11 service plus a surefire-XML assertion that fails on zero tests or any skip — is exactly the guard that keeps the shared-state claim from silently rotting. Approving from a review standpoint; the two notes below are non-blocking.

Notes

  • [Info] Key naming is open-ended by design: a threadId of " x " or with a newline passes validation and becomes part of the Redis key (<prefix>" x "), and Redis keys are unlimited so nothing will error — it just becomes hard to inspect from a client. Fine to keep raw (the contract explicitly forbids normalisation), but if upstream AG-UI ever supplies untrusted ids, a length/charset bound in the store layer would be cheaper to debug than a stuck interrupt key.
  • [Info] redis-integration only runs RedisAguiResumeLifecycleTest with -am; the report check catches "did not run", so a renamed class fails loudly rather than passing vacuously. Consider a paths-ignore for docs-only pushes later if the extra 30-minute job starts costing queue time.

Automated review by github-manager-bot

@jujn jujn added the P2 重要不紧急 label Nov 4, 2026

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

P2 重要不紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: AguiResumeCoordinator loses HITL interrupt state across instances

3 participants