Skip to content

fix(a2a): use protocol-standard contextId as sessionId instead of req… - #1827

Closed
pymBupt wants to merge 1 commit into
agentscope-ai:mainfrom
pymBupt:fix/a2a-session-id-use-contextId
Closed

pymBupt wants to merge 1 commit into
agentscope-ai:mainfrom
pymBupt:fix/a2a-session-id-use-contextId

Conversation

@pymBupt

@pymBupt pymBupt commented Jun 18, 2026

Copy link
Copy Markdown

…uiring metadata hardcoded key

Previously, AgentScopeAgentExecutor.getSessionId() read sessionId exclusively from message.metadata["sessionId"], forcing all A2A clients to hardcode this custom metadata key — inappropriate for multi-client interoperability.

The A2A protocol defines Message.contextId as the standard field for session/conversation context tracking.

Changes:

  • Prefer contextId (via RequestContext.getContextId()) as the sessionId source
  • Fallback to metadata["sessionId"] for backward compatibility
  • Add 3 unit tests covering the resolution strategy

Resolves #1603
Related: #820

AgentScope-Java Version

[The version of AgentScope-Java you are working on, e.g. 1.0.12, check your pom.xml dependency version or run mvn dependency:tree | grep agentscope-parent:pom(only mac/linux)]

Description

[Please describe the background, purpose, changes made, and how to test this PR]

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)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (e.g. links, examples, etc.)
  • Code is ready for review

…uiring metadata hardcoded key

Previously, AgentScopeAgentExecutor.getSessionId() read sessionId exclusively
from message.metadata["sessionId"], forcing all A2A clients to hardcode this
custom metadata key — inappropriate for multi-client interoperability.

The A2A protocol defines Message.contextId as the standard field for
session/conversation context tracking.

Changes:
- Prefer contextId (via RequestContext.getContextId()) as the sessionId source
- Fallback to metadata["sessionId"] for backward compatibility
- Add 3 unit tests covering the resolution strategy

Resolves agentscope-ai#1603
Related: agentscope-ai#820
@pymBupt
pymBupt requested a review from a team June 18, 2026 06:01
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@codecov

codecov Bot commented Jun 18, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.00000% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...e/a2a/server/executor/AgentScopeAgentExecutor.java 75.00% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@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 changes AgentScopeAgentExecutor.getSessionId() to prefer the A2A protocol-standard Message.contextId field over the custom metadata["sessionId"] key, while maintaining backward compatibility via fallback. This correctly addresses issue #1603 where all A2A clients were forced to hardcode a custom metadata key. The change is minimal (~24 lines in production code), backward-compatible, and well-documented with Javadoc. Three new unit tests cover the priority resolution strategy. The direction is correct and the implementation is clean. Minor suggestion: add test coverage for the edge case where context.getContextId() returns null.


@Test
@DisplayName("Should use contextId as sessionId when contextId is present")
void testSessionIdFromContextId() throws JSONRPCError {

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.

[recommended] Test coverage gap: The existing 3 tests cover contextId present, metadata fallback, and both present. Consider adding a test for the edge case where context.getContextId() returns null (not empty string) and no metadata sessionId exists — verifying the method returns empty string. This path is handled correctly in the code (contextId != null check) but has no test.


@Test
@DisplayName("Should use contextId as sessionId when contextId is present")
void testSessionIdFromContextId() throws JSONRPCError {

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] Test code duplication: The three test cases share extensive mock setup boilerplate (MessageSendParams mock, AtomicReference<AgentRequestOptions> capture, mockAgentRunner.stream stubbing, executor.execute call). Consider extracting a private helper method like executeAndCaptureOptions(contextId, metadataMap) to reduce duplication.

@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 changes AgentScopeAgentExecutor.getSessionId() to prefer the A2A protocol-standard Message.contextId field over the custom metadata["sessionId"] key, while maintaining backward compatibility via fallback. This correctly addresses issue #1603 where all A2A clients were forced to hardcode a custom metadata key. The change is minimal (~24 lines in production code), backward-compatible, and well-documented with Javadoc. Three new unit tests cover the priority resolution strategy. The direction is correct and the implementation is clean. Minor suggestion: add test coverage for the edge case where context.getContextId() returns null.


@Test
@DisplayName("Should use contextId as sessionId when contextId is present")
void testSessionIdFromContextId() throws JSONRPCError {

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.

[recommended] Test coverage gap: The existing 3 tests cover contextId present, metadata fallback, and both present. Consider adding a test for the edge case where context.getContextId() returns null (not empty string) and no metadata sessionId exists — verifying the method returns empty string. This path is handled correctly in the code (contextId != null check) but has no test.


@Test
@DisplayName("Should use contextId as sessionId when contextId is present")
void testSessionIdFromContextId() throws JSONRPCError {

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] Test code duplication: The three test cases share extensive mock setup boilerplate (MessageSendParams mock, AtomicReference<AgentRequestOptions> capture, mockAgentRunner.stream stubbing, executor.execute call). Consider extracting a private helper method like executeAndCaptureOptions(contextId, metadataMap) to reduce duplication.

@AgentScopeJavaBot AgentScopeJavaBot added bug Something isn't working area/ext/integration External protocols & middleware integrations labels Jun 19, 2026

@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

Switches the A2A server to resolve the agent sessionId from the protocol-standard contextId, falling back to the legacy metadata["sessionId"]. The direction is right — standard A2A clients should not have to invent a metadata key — but the precedence order silently re-keys sessions for existing clients, and the mocked tests do not pin down what RequestContext.getContextId() actually holds when the client omits it.

Note: the license/cla check is still pending, so this review is a COMMENT only — please sign the CLA (see reminder) before a maintainer looks at merging.


Automated review by github-manager-bot

// Prefer the protocol-standard contextId field
String contextId = context.getContextId();
if (contextId != null && !contextId.isEmpty()) {
return contextId;

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.

[Warning] This is a silent session-identity change for existing clients. Before, sessionId was exactly metadata["sessionId"]; after, a request that carries both a contextId and metadata["sessionId"] resolves to the contextId, so every store keyed by session (agent state persistence, memory, per-session isolation in distribution) starts a brand-new session on upgrade for anyone already passing a custom key. Precedence order is a product decision, but the compatible one is usually explicit-intent-first (metadata when present, contextId otherwise), or an opt-in config flag; please also call it out in the A2A docs/release notes if the flip is intentional.

private String getSessionId(RequestContext context, Message message) {
// Prefer the protocol-standard contextId field
String contextId = context.getContextId();
if (contextId != null && !contextId.isEmpty()) {

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.

[Warning] Please confirm what RequestContext.getContextId() returns for a message/send where the client sent no contextId. If the SDK materialises a generated contextId for the new task before execute() runs, then contextId != null && !isEmpty() is true for every fresh conversation and clients that relied on metadata["sessionId"] for continuity lose it — the opposite of the intent. The three new tests all stub getContextId() to a literal, so this path is exactly the one they cannot catch. An extra test with getContextId() -> null plus non-empty metadata.sessionId (and, if the SDK does generate one, a note in the javadoc) would settle it.

* <li>Backward-compatible fallback: {@code Message.metadata["sessionId"]}.</li>
* </ol>
*
* <p>This ensures any standard A2A client that sets {@code contextId} on the message

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.

[Info] The javadoc describes the metadata branch as a "Backward-compatible fallback", but the combination "contextId always wins" is not backward compatible for requests that carry both (see the comment on the return contextId; line). Worth aligning the wording with the actual contract, and stating which of the two IDs is the durable session key for state/memory so downstream readers do not have to infer it.

@oss-maintainer

Copy link
Copy Markdown
Collaborator

CLA Not Signed

The Contributor License Agreement (CLA) check is currently pending on this PR (license/cla: Contributor License Agreement is not signed yet.). This PR cannot be merged until the CLA is signed.

@pymBupt please sign the CLA via the CLA assistant badge in the comment above, or visit https://cla-assistant.io/agentscope-ai/agentscope-java. Once signed, the license/cla status will turn green.


Automated check by github-manager-bot

jujn pushed a commit that referenced this pull request Oct 25, 2026
…#3746)

## Description

A standard A2A client that sends `contextId` without custom
`message.metadata["sessionId"]` currently gives the server's
`AgentRunner` an empty session ID. Resolve
`AgentRequestOptions.sessionId` from the SDK-resolved context ID when no
non-blank legacy session ID is provided.

Explicit legacy metadata keeps precedence, including when the SDK
auto-generates a context ID. This preserves existing session keys. Null,
empty and whitespace-only legacy values fall back to the protocol
context; existing non-string metadata values retain their string
conversion. The protocol message's context ID is not rewritten.

This changes request-option mapping only; it does not add automatic
session persistence or runtime-context forwarding in the built-in
runner. English/Chinese documentation and the field Javadoc describe the
precedence.

Refs #1603 and #1827.
@jujn jujn closed this Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/ext/integration External protocols & middleware integrations bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]:A2A在传递userId、sessionId时发送逻辑和取值逻辑不一致,导致userId、sessionId在server端丢失。

5 participants