Repository navigation
fix(core): reload authoritative state before permission admin writes - #2731
birdie7761 wants to merge 7 commits into
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 AI Review
This PR fixes two real production failure modes in setPermissionMode / replacePermissionContext: (1) cross-replica stale overwrite when another pod has advanced the persisted state, and (2) promotion of unpersisted failed-call state (e.g., dangling tool_use without tool_result) into the store. The fix introduces a stateForPermissionAdminWrite helper that reloads authoritative state from the store before mutating — the same pattern already used by activateSlotForContext and clearContext. A mirrorPermissionContext guard ensures in-flight call instances also receive the permission update before the admin save, closing the OVERWRITE race window. The implementation is clean, follows established codebase patterns, and the 8-test regression suite is thorough. Javadoc is excellent. One minor asymmetry: the mirror-before-save ordering test and the no-store guard test only cover setPermissionMode, not replacePermissionContext.
| modeAtAdminSave.set(inFlight.getPermissionContext().getMode()); | ||
| } | ||
| super.save(u, s, key, value); | ||
| } |
There was a problem hiding this comment.
[nitpick] The inFlightMirrorPrecedesTheAdminSave ordering test only covers setPermissionMode. A symmetric test for replacePermissionContext would guard against future refactoring that might diverge the two entry points' mirror-before-save ordering. The current coverage is acceptable since both share the same installPermissionContext helper, but adding the sibling test (similar to how tests 3/4 and 5/6 are symmetric pairs) would make the suite fully airtight.
| /** An assistant turn carrying a tool_use block with no matching tool_result. */ | ||
| private static Msg danglingToolUseAssistantMsg() { | ||
| return Msg.builder() | ||
| .name("asst") |
There was a problem hiding this comment.
[nitpick] withoutStorePermissionToggleMutatesCachedState only tests setPermissionMode. A sibling test for replacePermissionContext without a store would complete the guard coverage for the no-store path across both public entry points.
| */ | ||
| private AgentState stateForPermissionAdminWrite(String userId, String sid) { | ||
| if (stateStore == null) { | ||
| return getAgentState(userId, sid); |
There was a problem hiding this comment.
[nitpick] stateForPermissionAdminWrite unconditionally calls loadOrCreateAgentStateForSlot when a store is configured, while the nearby clearContext method first checks stateStore.exists() and falls back to the cached instance when the store has no record. The difference is functionally correct here (creating a state for a permission admin write is intentional, and loadOrCreateAgentStateForSlot creates a fresh state when nothing is found), but a brief inline comment noting the deliberate divergence from clearContext would help future maintainers avoid 'normalizing' the two paths.
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 AI Review
This PR fixes two real production failure modes in setPermissionMode / replacePermissionContext: (1) cross-replica stale overwrite when another pod has advanced the persisted state, and (2) promotion of unpersisted failed-call state (e.g., dangling tool_use without tool_result) into the store. The fix introduces a stateForPermissionAdminWrite helper that reloads authoritative state from the store before mutating — the same pattern already used by activateSlotForContext and clearContext. A mirrorPermissionContext guard ensures in-flight call instances also receive the permission update before the admin save, closing the OVERWRITE race window. The implementation is clean, follows established codebase patterns, and the 8-test regression suite is thorough. Javadoc is excellent. One minor asymmetry: the mirror-before-save ordering test and the no-store guard test only cover setPermissionMode, not replacePermissionContext.
| modeAtAdminSave.set(inFlight.getPermissionContext().getMode()); | ||
| } | ||
| super.save(u, s, key, value); | ||
| } |
There was a problem hiding this comment.
[nitpick] The inFlightMirrorPrecedesTheAdminSave ordering test only covers setPermissionMode. A symmetric test for replacePermissionContext would guard against future refactoring that might diverge the two entry points' mirror-before-save ordering. The current coverage is acceptable since both share the same installPermissionContext helper, but adding the sibling test (similar to how tests 3/4 and 5/6 are symmetric pairs) would make the suite fully airtight.
| /** An assistant turn carrying a tool_use block with no matching tool_result. */ | ||
| private static Msg danglingToolUseAssistantMsg() { | ||
| return Msg.builder() | ||
| .name("asst") |
There was a problem hiding this comment.
[nitpick] withoutStorePermissionToggleMutatesCachedState only tests setPermissionMode. A sibling test for replacePermissionContext without a store would complete the guard coverage for the no-store path across both public entry points.
| */ | ||
| private AgentState stateForPermissionAdminWrite(String userId, String sid) { | ||
| if (stateStore == null) { | ||
| return getAgentState(userId, sid); |
There was a problem hiding this comment.
[nitpick] stateForPermissionAdminWrite unconditionally calls loadOrCreateAgentStateForSlot when a store is configured, while the nearby clearContext method first checks stateStore.exists() and falls back to the cached instance when the store has no record. The difference is functionally correct here (creating a state for a permission admin write is intentional, and loadOrCreateAgentStateForSlot creates a fresh state when nothing is found), but a brief inline comment noting the deliberate divergence from clearContext would help future maintainers avoid 'normalizing' the two paths.
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 AI Review
This PR fixes two real production failure modes in setPermissionMode / replacePermissionContext: (1) cross-replica stale overwrite when another pod has advanced the persisted state, and (2) promotion of unpersisted failed-call state (e.g., dangling tool_use without tool_result) into the store. The fix introduces a stateForPermissionAdminWrite helper that reloads authoritative state from the store before mutating — the same pattern already used by activateSlotForContext and clearContext. A mirrorPermissionContext guard ensures in-flight call instances also receive the permission update before the admin save, closing the OVERWRITE race window. The implementation is clean, follows established codebase patterns, and the 8-test regression suite is thorough. Javadoc is excellent. One minor asymmetry: the mirror-before-save ordering test and the no-store guard test only cover setPermissionMode, not replacePermissionContext.
| modeAtAdminSave.set(inFlight.getPermissionContext().getMode()); | ||
| } | ||
| super.save(u, s, key, value); | ||
| } |
There was a problem hiding this comment.
[nitpick] The inFlightMirrorPrecedesTheAdminSave ordering test only covers setPermissionMode. A symmetric test for replacePermissionContext would guard against future refactoring that might diverge the two entry points' mirror-before-save ordering. The current coverage is acceptable since both share the same installPermissionContext helper, but adding the sibling test (similar to how tests 3/4 and 5/6 are symmetric pairs) would make the suite fully airtight.
| /** An assistant turn carrying a tool_use block with no matching tool_result. */ | ||
| private static Msg danglingToolUseAssistantMsg() { | ||
| return Msg.builder() | ||
| .name("asst") |
There was a problem hiding this comment.
[nitpick] withoutStorePermissionToggleMutatesCachedState only tests setPermissionMode. A sibling test for replacePermissionContext without a store would complete the guard coverage for the no-store path across both public entry points.
| */ | ||
| private AgentState stateForPermissionAdminWrite(String userId, String sid) { | ||
| if (stateStore == null) { | ||
| return getAgentState(userId, sid); |
There was a problem hiding this comment.
[nitpick] stateForPermissionAdminWrite unconditionally calls loadOrCreateAgentStateForSlot when a store is configured, while the nearby clearContext method first checks stateStore.exists() and falls back to the cached instance when the store has no record. The difference is functionally correct here (creating a state for a permission admin write is intentional, and loadOrCreateAgentStateForSlot creates a fresh state when nothing is found), but a brief inline comment noting the deliberate divergence from clearContext would help future maintainers avoid 'normalizing' the two paths.
3c4576d to
be6ee52
Compare
setPermissionMode and replacePermissionContext read the whole AgentState from the never-refreshed in-process stateCache and wrote it back via saveAgentState. With a store configured this had two production failure modes (issue agentscope-ai#2535): - Cross-replica stale overwrite: a permission toggle on a replica whose cached entry lagged behind the store reverted the newer persisted conversation (the default ConflictPolicy.OVERWRITE turned the CAS mismatch into an unconditional overwrite of the stale copy). - Failed-call poison promotion: a call that mutated the cached instance but never persisted left that half-state in the cache; a later setPermissionMode CAS-saved it (version still matched), permanently breaking the session with dangling tool_use / missing tool_result. Both entry points now resolve the slot through the same authoritative reload used by activateSlotForContext and the clearContext fix (loadOrCreateAgentStateForSlot, replacing the cache entry and slot version) before installing and persisting the permission context. Unpersisted mutations in the previously cached local instance are discarded in favor of the authoritative store state (call-path persistence goes through saveStateToSession and is unaffected); without a store the previous in-process behavior is unchanged. In-flight calls still hold the previously cached instance and persist it at call end; the new permission context is mirrored onto that instance BEFORE the admin save, so an end-of-call save racing inside the gap can no longer hit the OVERWRITE policy and swallow the change: saves landing after the mirror carry the new context, saves landing before it are superseded by the admin save. The call keeps its captured call-scoped engine, per the existing javadoc contract. New ReActAgentPermissionAdminWriteTest reproduces both failure modes with two agents sharing one store (multi-replica pattern from clearContextReloadsPersistedStateBeforeClearingConversation): the two truncation tests, both poison-promotion tests and the mirror-ordering test fail on main and pass with this change; three guard tests lock the no-store and in-flight behavior.
be6ee52 to
c1c8da3
Compare
There was a problem hiding this comment.
Summary
First review. setPermissionMode / replacePermissionContext now resolve the state to mutate through stateForPermissionAdminWrite, which reloads the authoritative persisted state (mirroring the per-call reload in activateSlotForContext) before the admin write, so a toggle from one replica can no longer revert newer persisted state written by another, and an unpersisted failed-call state is no longer promoted into the store. The ordering choice in installPermissionContext (mirror onto the previously cached instance before saveAgentState) is the subtle part, and it is both documented and pinned by inFlightMirrorPrecedesTheAdminSave / replacePermissionContextMirrorPrecedesTheAdminSave; withoutStore* covers the no-store fallback. 10 new tests cover each branch of the fix rather than the happy path only. No correctness, locking or compatibility issue found. LGTM.
Not a merge decision — CI and maintainer approval still apply.
Automated review by github-manager-bot
…dmin-write-reload # Conflicts: # agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java
AgentScope-Java Version
2.0.3-SNAPSHOT (main @
00215511)Description
Fixes #2535
setPermissionMode/replacePermissionContextread the wholeAgentStatefrom the never-refreshed in-processstateCache(getAgentState'scomputeIfAbsent— a cache hit never goes back to the store) and wrote it back wholesale viasaveAgentState. With a store configured this had two production failure modes:ConflictPolicy.OVERWRITE, which unconditionally writes the stale copy (with only a WARN log).setPermissionModeCAS-saves that half-state (e.g. a trailing assistant message withtool_useand notool_result). Every subsequent call fails withPending tool calls exist without results, permanently breaking the session — the exact production incident in the issue.This PR applies the issue's suggested direction 1 — the same authoritative reload already used by
activateSlotForContexton every call and by theclearContextfix:loadOrCreateAgentStateForSlotfirst (replacing thestateCacheentry andslotVersionsslot) when a store is configured, then install and persist the permission context. Without a store the previous in-process behavior is unchanged.conflictPolicy; the overwrite baseline is now the just-reloaded fresh state, shrinking the loss surface from a whole stale session to the micro-window delta.Regression tests
New
ReActAgentPermissionAdminWriteTestuses two agents sharing one store to model a multi-replica deployment (the same pattern as the existingclearContextReloadsPersistedStateBeforeClearingConversation):setPermissionModeon a stale replica must not truncate the newer persisted conversation — fails on main (restored context was: []);replacePermissionContextlikewise — fails on main;tool_use) must not be promoted into the store by a permission toggle — fails on main (expected: <1> but was: <2>);replacePermissionContext— fails on main (guards the shared helper against the two entry points diverging);expected: <BYPASS> but was: <DEFAULT>);The poison tests run against
JsonFileAgentStateStoreso the reload round-trips through serialization, matching the production MySQL/Redis stores (InMemoryAgentStateStorealiases instances by reference — noted in the test class javadoc).Compatibility: no storage-format change —
AgentStatefields, serialization and the store API are untouched, and the reload helper is the same production code path already used byactivateSlotForContext/clearContext(including theLegacyStateLoaderfallback for older formats). Previously persisted sessions can only become safer: they are no longer reverted by a stale replica or poisoned by a failed call. The one deliberate behavior change — unpersisted local cache mutations are discarded in favor of the authoritative store state — is documented on the helper; regular call-path persistence goes throughsaveStateToSessionand is unaffected.How to test
Checklist
Please check the following items before code is ready to be reviewed.
mvn spotless:applymvn test— core: 2282, harness: 828, 0 failures)