Skip to content

fix(core): reload authoritative state before permission admin writes - #2731

Open
birdie7761 wants to merge 7 commits into
agentscope-ai:mainfrom
birdie7761:fix/2535-permission-admin-write-reload
Open

birdie7761 wants to merge 7 commits into
agentscope-ai:mainfrom
birdie7761:fix/2535-permission-admin-write-reload

Conversation

@birdie7761

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.0.3-SNAPSHOT (main @ 00215511)

Description

Fixes #2535

setPermissionMode / replacePermissionContext read the whole AgentState from the never-refreshed in-process stateCache (getAgentState's computeIfAbsent — a cache hit never goes back to the store) and wrote it back wholesale via saveAgentState. With a store configured this had two production failure modes:

  • Cross-replica stale overwrite. Pod A caches session state v1; pod B advances the store to v2; a permission toggle on pod A then persists v1 again — the newer conversation is silently truncated. The version CAS does not save this: the mismatch falls into the default ConflictPolicy.OVERWRITE, which unconditionally writes the stale copy (with only a WARN log).
  • Failed-call poison promotion. A call that failed mid-flight mutated the cached instance but never persisted it; the store version therefore still matches, so a later setPermissionMode CAS-saves that half-state (e.g. a trailing assistant message with tool_use and no tool_result). Every subsequent call fails with Pending 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 activateSlotForContext on every call and by the clearContext fix:

  • Both entry points resolve the slot through loadOrCreateAgentStateForSlot first (replacing the stateCache entry and slotVersions slot) when a store is configured, then install and persist the permission context. Without a store the previous in-process behavior is unchanged.
  • In-flight edge (called out in the issue): an in-flight call still holds the previously cached instance and persists it at call end, which would revert the toggle. The new permission context is mirrored onto that instance before the admin save — 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 ("an in-flight call keeps the engine it started with").
  • CAS conflicts inside the reload→save micro-window follow the existing 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 ReActAgentPermissionAdminWriteTest uses two agents sharing one store to model a multi-replica deployment (the same pattern as the existing clearContextReloadsPersistedStateBeforeClearingConversation):

  1. setPermissionMode on a stale replica must not truncate the newer persisted conversation — fails on main (restored context was: []);
  2. replacePermissionContext likewise — fails on main;
  3. a never-persisted failed-call tail (dangling tool_use) must not be promoted into the store by a permission toggle — fails on main (expected: <1> but was: <2>);
  4. the same poison scenario through replacePermissionContext — fails on main (guards the shared helper against the two entry points diverging);
  5. in-flight cached instances keep receiving both the mode change and a replaced permission context (guards for the mirror);
  6. the mirror happens before the admin save — an observing store records the previously cached instance's mode at the moment the admin save fires and asserts it already carries the new mode (closes the OVERWRITE gap; fails on the mirror-after-save ordering with expected: <BYPASS> but was: <DEFAULT>);
  7. without a store the toggle still mutates the cached state in place (guard).

The poison tests run against JsonFileAgentStateStore so the reload round-trips through serialization, matching the production MySQL/Redis stores (InMemoryAgentStateStore aliases instances by reference — noted in the test class javadoc).

Compatibility: no storage-format change — AgentState fields, serialization and the store API are untouched, and the reload helper is the same production code path already used by activateSlotForContext / clearContext (including the LegacyStateLoader fallback 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 through saveStateToSession and is unaffected.

How to test

mvn -pl agentscope-core -Dtest=ReActAgentPermissionAdminWriteTest -DfailIfNoTests=false test
mvn -pl agentscope-core test                                        # 2282 tests, 0 failures
mvn -pl agentscope-core -am install -DskipTests
mvn -pl agentscope-harness test                                     # 828 tests, 0 failures

Checklist

Please check the following items before code is ready to be reviewed.

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test — core: 2282, harness: 828, 0 failures)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (javadoc on both entry points documents the reload semantics)
  • Code is ready for review

@codecov

codecov Bot commented Aug 16, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@AgentScopeJavaBot AgentScopeJavaBot added bug Something isn't working area/core/agent Agent runtime, pipeline, hooks, plan labels Aug 16, 2026

@AgentScopeJavaBot AgentScopeJavaBot 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.

🤖 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);
}

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.

[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")

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.

[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);

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.

[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 AgentScopeJavaBot 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.

🤖 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);
}

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.

[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")

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.

[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);

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.

[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 AgentScopeJavaBot 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.

🤖 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);
}

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.

[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")

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.

[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);

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.

[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.

@birdie7761
birdie7761 force-pushed the fix/2535-permission-admin-write-reload branch from 3c4576d to be6ee52 Compare August 16, 2026 11:08
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.
@birdie7761
birdie7761 force-pushed the fix/2535-permission-admin-write-reload branch from be6ee52 to c1c8da3 Compare August 16, 2026 11:10

@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. 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

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

area/core/agent Agent runtime, pipeline, hooks, plan bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]:setPermissionMode 读取未回源的进程内 stateCache 并整体写回,多副本下会静默覆盖更新的 AgentState

3 participants