Repository navigation
fix(agui): share resume coordination state across replicas - #2890
ordinary-s wants to merge 6 commits into
Conversation
|
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 Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
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
|
This PR currently conflicts with git fetch origin
git checkout fix/agui-shared-resume-state
git rebase origin/main
# resolve conflicts, then:
git push --force-with-leaseThis 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.
168c76f to
8944797
Compare
|
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
left a comment
There was a problem hiding this comment.
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-checkedreleaseRun, and owner-checked atomicreplacePendingInterruptsare correctly specified;InMemoryAguiResumeStateStoreimplements them atomically viaConcurrentHashMap.compute/computeIfPresent, andRedisAguiResumeStateStoreimplements 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 toRunClaim.acquired(), the release script is idempotent and preservespendingInterrupts, and plainEVALavoids 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 cachedclose().then(release())cleanup (verified that Reactor'sMono.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_STARTEDat most once, and withholdingRUN_FINISHEDon 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;interruptOnDisconnectnow maps to the processor'sinterruptOnCancelwith disposal-based cancellation. Backward compatible — only additive builder methods; no existing public signatures changed; the redis module pom addition follows the module's existingprovided+optionalpattern and both modules are already registered inagentscope-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
releaseRunrecovery) 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.
prepareRunnow handles the validation-failure path withrun.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)invokesonClaimedbeforevalidate), but every exit path — validation error, validate-read failure, synchronous setup failure, cancellation during claim, claim failure (indeterminate, no release) — now flows throughFlux.usingWhen's complete/error/cancel hooks into the shared cached cleanup. Directly covered byAguiResumeLifecycleTest.contractErrorReleasesOwnershipWithoutDemand,validationReadFailureReleasesWithoutDemand,cancelDuringSuccessfulClaimWaitsForClaimAndReleasesWithoutRunningAgent, and the Redis-gatedzeroDemandContractErrorAllowsReplicaResumeAndPreservesNewOwner.
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.ymlruns plainmvn -B -T1 clean verify, so they never execute in CI. The always-onRedisAguiResumeStateStoreTestmocksjedis.eval(...)entirely, which means the actual Lua bodies (CLAIM_RUN_SCRIPT,RELEASE_RUN_SCRIPT,REPLACE_PENDING_SCRIPT— KEYS/ARGV indices, owner checks, the Luafalse→nil reply mapping inclaimRun, the conditionalDELinRELEASE_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 aredisservice container) by setting-Dagui.redis.integration=true, or at minimum add always-on unit tests asserting the exact script strings and theKEYS/ARGVcomposition for all three operations (today onlyreleaseUsesOneOwnerCheckedRedisOperationandpendingReplacementReturnsOwnerCheckResultAndClearsWithSameOperationcheck argument lists, and neither validates the script text or its Lua semantics). - [INFO]
RedisAguiResumeStateStore.java:152— The twoAguiResumeStateStoreimplementations disagree on blank identifiers:RedisAguiResumeStateStore.key()→requireIdentifierthrowsIllegalArgumentExceptionfor a blank/whitespacethreadId, whileInMemoryAguiResumeStateStoreonly doesObjects.requireNonNull(e.g.getPendingInterruptsat InMemoryAguiResumeStateStore.java:33 accepts""). A request withthreadId=""is therefore processed normally with the default in-memory store but fails withRUN_ERROR/INVALID_INPUT_ERRORonce a shared Redis store is configured — exactly the kind of deployment-dependent behaviour change the SPI is meant to prevent, and theAguiResumeStateStorejavadoc does not state any identifier requirements. Suggestion: document thethreadId/runIdidentifier contract (non-null, non-blank) on theAguiResumeStateStoreinterface and alignInMemoryAguiResumeStateStoreto reject blank values the same way, so both stores behave identically for malformed inputs. - [INFO]
AguiResumeLifecycleTest.java:148—contractErrorReleasesOwnershipWithoutDemandcontains a leftoverSystem.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 surroundingassertTrue(...)/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.
|
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
left a comment
There was a problem hiding this comment.
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
threadIdof" 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-integrationonly runsRedisAguiResumeLifecycleTestwith-am; the report check catches "did not run", so a renamed class fails loudly rather than passing vacuously. Consider apaths-ignorefor docs-only pushes later if the extra 30-minute job starts costing queue time.
Automated review by github-manager-bot
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
AguiResumeStateStorewith immutable pending snapshots, atomic claim, owner-checked release, and atomic owner-checked pending replacement. KeepInMemoryAguiResumeStateStoreas the default.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.Request lifecycle and recovery
boundedElasticscheduler, including pending writes and cleanup after cancellation. Ordinary token events do not require a separate blocking task.RUN_ERRORevents. EmitRUN_STARTEDonly if it has not already been sent, respectemitRunFinishedAfterError, and withhold the successfulRUN_FINISHEDwhen its pending write fails.Validation
Validated on JDK 21 with Java 17 compilation, including a disposable Redis 7.4 instance and actual Reactor Netty HTTP connections:
-Dagui.redis.integration=true; local port 16389, configurable via-Dagui.redis.port).mvn spotless:checkandgit diff --checkpassed.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.