Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions agent/a2aagent/a2a_agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ type A2AAgent struct {
a2aClientURL string

// anonymousCookieInitLocks serializes first anonymous-cookie acquisition
// within this A2AAgent instance. Session services that implement
// within this A2AAgent instance. Session services that provide an available
// session.StateInitializationService additionally coordinate separate agent
// instances or processes that share the same backing store.
anonymousCookieInitMu sync.Mutex
Expand Down Expand Up @@ -224,7 +224,7 @@ func isolateCoordinatedAnonymousCookieSessions(
persistentSession *session.Session,
service session.Service,
) (*session.Session, *session.Session) {
if _, ok := service.(session.StateInitializationService); !ok ||
if _, ok := availableStateInitializationService(service); !ok ||
!hasPersistentSessionKey(persistentSession) {
// Without a stable persistent key, coordination cannot be used and the
// existing fallback must keep sharing transient session state.
Expand Down
6 changes: 3 additions & 3 deletions agent/a2aagent/a2a_agent_option.go
Original file line number Diff line number Diff line change
Expand Up @@ -349,9 +349,9 @@ func WithEnableStreaming(enable bool) Option {

// WithRequireAnonymousIdentityCoordination controls fail-closed anonymous
// identity initialization. When enabled, a first anonymous request requires a
// stable persistent session key and a session service that implements
// session.StateInitializationService. Existing valid cookie state can still be
// used without coordination. The default is false.
// stable persistent session key and a session service that provides an
// available session.StateInitializationService. Existing valid cookie state
// can still be used without coordination. The default is false.
func WithRequireAnonymousIdentityCoordination(enabled bool) Option {
return func(a *A2AAgent) {
a.requireAnonymousIdentityCoordination = enabled
Expand Down
45 changes: 45 additions & 0 deletions agent/a2aagent/a2a_agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -819,6 +819,18 @@ func TestA2AAgent_CoordinatedCookieStateUsesPrivateSessionSnapshots(
)
require.Same(t, transientSession, transientSnapshot)
require.Same(t, transientSession, transientPersistentSnapshot)

unavailableService := &unavailableStateInitializationService{
Service: service,
}
unavailableSnapshot, unavailablePersistentSnapshot :=
isolateCoordinatedAnonymousCookieSessions(
persistentSession,
persistentSession,
unavailableService,
)
require.Same(t, persistentSession, unavailableSnapshot)
require.Same(t, persistentSession, unavailablePersistentSnapshot)
}

func TestA2AAgent_TransientAnonymousCookieRemainsSharedWithCapableService(
Expand Down Expand Up @@ -1876,6 +1888,18 @@ func TestAnonymousCookieRequestHandlerStrictCoordinationPreflight(t *testing.T)
scope,
),
},
{
name: "unavailable session service",
state: newAnonymousCookieState(
session.NewSession("app", "user-1", "session-a"),
session.NewSession("app", "user-1", "session-a"),
&unavailableStateInitializationService{
Service: sessionmemory.NewSessionService(),
},
stateKey,
scope,
),
},
{
name: "missing persistent session key",
state: newAnonymousCookieState(
Expand Down Expand Up @@ -6979,6 +7003,27 @@ type sessionServiceWithoutStateInitialization struct {
session.Service
}

type unavailableStateInitializationService struct {
session.Service
calls atomic.Int32
}

func (s *unavailableStateInitializationService) StateInitializationAvailable() bool {
return false
}

func (s *unavailableStateInitializationService) LoadOrInitializeSessionState(
context.Context,
session.Key,
string,
func([]byte) bool,
func(context.Context) ([]byte, error),
...session.StateInitializationProjection,
) ([]byte, bool, error) {
s.calls.Add(1)
return nil, false, errors.New("unavailable initializer was called")
}

type failingStateInitializationService struct {
session.Service
err error
Expand Down
16 changes: 15 additions & 1 deletion agent/a2aagent/anonymous_coordination.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ func (s *anonymousCookieState) stateInitializer() (
if s == nil || s.sessionService == nil {
return nil, session.Key{}, false
}
initializer, ok := s.sessionService.(session.StateInitializationService)
initializer, ok := availableStateInitializationService(s.sessionService)
if !ok {
return nil, session.Key{}, false
}
Expand All @@ -166,6 +166,20 @@ func (s *anonymousCookieState) stateInitializer() (
return initializer, key, true
}

func availableStateInitializationService(
service session.Service,
) (session.StateInitializationService, bool) {
initializer, ok := service.(session.StateInitializationService)
if !ok {
return nil, false
}
availability, reportsAvailability := service.(session.StateInitializationAvailability)
if reportsAvailability && !availability.StateInitializationAvailable() {
return nil, false
}
return initializer, true
}

func (s *anonymousCookieState) usesCanonicalRecord() bool {
if _, _, present := s.loadCanonicalRecord(); present {
return true
Expand Down
23 changes: 18 additions & 5 deletions docs/mkdocs/en/a2a.md
Original file line number Diff line number Diff line change
Expand Up @@ -1001,8 +1001,21 @@ agent automatically uses `session.StateInitializationService` when the
configured `SessionService` provides it. The capability coordinates the first
anonymous cookie across agent instances that share the same backing store.
The in-memory session service coordinates callers sharing the same service
instance; the Redis session service coordinates callers across service
instances.
instance. Redis, MySQL, and TDSQL coordinate callers across service instances
that share the same backing store.
MySQL and TDSQL enable the capability by default. Deployments using
`WithSkipDBInit(true)` must provision the `state_initialization_leases` table
and indexes from the current schema and migrate `session_states.created_at` to
`TIMESTAMP(6)`. It must also provision and backfill
`session_states.state_initialization_active` and its unique index so each
logical session has at most one active row. Startup performs a read-only
prerequisite check even when DDL initialization is skipped.

During a staged schema migration, configure
`mysql.WithStateInitialization(false)`. Lenient mode then keeps the previous
per-agent fallback without accessing the lease table. Strict mode still fails
before contacting the remote agent because the capability is unavailable.
Re-enable the option after every instance uses the migrated schema.

When the capability is unavailable, the agent keeps the existing per-agent
initialization lock and persistence behavior. Enable fail-closed behavior when
Expand All @@ -1017,11 +1030,11 @@ a2aAgent, err := a2aagent.New(

The option defaults to `false`. When enabled, strict mode fails the invocation
before contacting the remote agent if there is no stable persistent session key
or the session service does not implement the coordination capability. This
or the session service does not provide an available coordination capability. This
capability check cannot determine whether separate service instances actually
share coordination state. Deployments requiring cross-process coordination
must configure a shared backend such as Redis instead of separate in-memory
services.
must configure a shared backend such as Redis, MySQL, or TDSQL instead of
separate in-memory services.

The canonical `.record.v1` value and its legacy projection are committed
together on the coordinated paths, so a new writer remains readable by a
Expand Down
103 changes: 103 additions & 0 deletions docs/mkdocs/en/session/mysql.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ MySQL storage is suitable for production environments and applications requiring
| --- | --- | --- | --- |
| `WithTablePrefix(prefix string)` | `string` | `""` | Table name prefix |
| `WithSkipDBInit(skip bool)` | `bool` | `false` | Skip automatic table creation |
| `WithStateInitialization(enabled bool)` | `bool` | `false` | Enable coordinated session-state initialization |

### Hook Configuration

Expand Down Expand Up @@ -193,8 +194,10 @@ CREATE TABLE IF NOT EXISTS `{{PREFIX}}session_states` (
`updated_at` TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
`expires_at` TIMESTAMP(6) NULL DEFAULT NULL,
`deleted_at` TIMESTAMP(6) NULL DEFAULT NULL,
`state_initialization_active` TINYINT NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_{{PREFIX}}session_states_unique_active` (`app_name`,`user_id`,`session_id`,`deleted_at`),
UNIQUE KEY `idx_{{PREFIX}}session_states_state_init_active` (`app_name`,`user_id`,`session_id`,`state_initialization_active`),
KEY `idx_{{PREFIX}}session_states_expires` (`expires_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```
Expand Down Expand Up @@ -298,6 +301,105 @@ See [session/mysql/schema.sql](https://github.com/trpc-group/trpc-agent-go/blob/

## Version Upgrade

### Coordinated Initialization Migration

Coordinated state initialization requires exactly one active `session_states`
row for each `(app_name, user_id, session_id)`. On an existing MySQL or TDSQL
deployment, first deploy the new service version everywhere with
`WithStateInitialization(false)`. Then quiesce session creation, migrate the
active-row marker and unique index, provision the lease table and indexes, and
re-enable the capability.

Back up the table and resolve duplicate active rows before running the DDL:

```sql
-- Step 1: find duplicate active sessions. Resolve every returned group first.
SELECT app_name, user_id, session_id, COUNT(*) AS active_count
FROM `{{PREFIX}}session_states`
WHERE deleted_at IS NULL
GROUP BY app_name, user_id, session_id
HAVING active_count > 1;

-- Step 2: add and backfill the nullable marker. Soft-deleted rows stay NULL.
ALTER TABLE `{{PREFIX}}session_states`
ADD COLUMN state_initialization_active TINYINT NULL DEFAULT NULL;
UPDATE `{{PREFIX}}session_states`
SET state_initialization_active = 1
WHERE deleted_at IS NULL;

-- Step 3: enforce one active row. For TDSQL, user_id remains in the UNIQUE
-- index so the constraint is shard-local.
CREATE UNIQUE INDEX `idx_{{PREFIX}}session_states_state_init_active`
ON `{{PREFIX}}session_states`(
app_name, user_id, session_id, state_initialization_active
);
```

Before re-enabling state initialization, provision the lease schema with the
variant matching the deployment. When `WithSkipDBInit(true)` is set, the service
does not create this table or its indexes, so they must be provisioned during
the migration. Replace `{{PREFIX}}` with the configured table prefix. The
expanded table names must fit MySQL's 64-character table-name limit. The Go
initializer uses prefixed index names for the active-row index in Step 3 and the
lease indexes below when they fit the 64-character index-name limit; for an
overlong index name, use the deterministic table-scoped fallback (for example,
`idx_session_states_state_init_active` or `idx_state_initialization_leases_uniq`)
instead of truncating the prefix.

MySQL:

```sql
CREATE TABLE IF NOT EXISTS `{{PREFIX}}state_initialization_leases` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`coordination_key` BINARY(32) NOT NULL,
`user_id` VARCHAR(255) NOT NULL,
`owner_token` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`session_row_id` BIGINT NOT NULL,
`session_created_at` TIMESTAMP(6) NOT NULL,
`expires_at` TIMESTAMP(6) NOT NULL,
`updated_at` TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE UNIQUE INDEX `idx_{{PREFIX}}state_initialization_leases_uniq`
ON `{{PREFIX}}state_initialization_leases` (`coordination_key`, `user_id`);
CREATE INDEX `idx_{{PREFIX}}state_initialization_leases_exp`
ON `{{PREFIX}}state_initialization_leases` (`expires_at`);
```

TDSQL:

```sql
CREATE TABLE IF NOT EXISTS `{{PREFIX}}state_initialization_leases` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`coordination_key` BINARY(32) NOT NULL,
`user_id` VARCHAR(255) NOT NULL,
`owner_token` CHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`session_row_id` BIGINT NOT NULL,
`session_created_at` TIMESTAMP(6) NOT NULL,
`expires_at` TIMESTAMP(6) NOT NULL,
`updated_at` TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
PRIMARY KEY (`id`, `user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci shardkey=user_id;

CREATE UNIQUE INDEX `idx_{{PREFIX}}state_initialization_leases_uniq`
ON `{{PREFIX}}state_initialization_leases` (`coordination_key`, `user_id`);
CREATE INDEX `idx_{{PREFIX}}state_initialization_leases_exp`
ON `{{PREFIX}}state_initialization_leases` (`expires_at`);
```

Startup fails closed while the column/index is missing, the index is not unique,
or an active row does not have marker value `1`. After all instances use the
migrated schema, re-enable state initialization. The service writes marker `1`
for active rows and clears it on soft deletion. If writes could not be quiesced,
repeat the duplicate check and marker `UPDATE` immediately before creating the
unique index; do not re-enable the capability until they succeed. Startup also
checks both sides of the invariant: rows with `deleted_at IS NULL` must have
marker `1`, while soft-deleted rows must have a `NULL` marker. The check uses an
`EXISTS` probe and stops after the first inconsistent row, but the existing
indexes do not lead with either predicate column, so a healthy deployment may
still scan the full table or an entire index once during startup.

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
### Legacy Data Migration

If your database was created with an older version, follow these migration steps.
Expand Down Expand Up @@ -394,3 +496,4 @@ SHOW INDEX FROM session_summaries WHERE Key_name = 'idx_session_summaries_unique
4. **Soft delete**: Enabled by default; queries automatically filter deleted records
5. **MySQL version**: Requires MySQL 5.6.5+ for multiple TIMESTAMP columns with CURRENT_TIMESTAMP
6. **Unique constraint**: MySQL's UNIQUE constraint does not prevent multiple NULL values; the application layer handles active record uniqueness
7. **Coordinated initialization migration**: With state initialization enabled, `WithSkipDBInit(true)` still verifies that `session_states.created_at` uses `TIMESTAMP(6)`, that the active-row marker and unique index are consistent, and that the lease table and required indexes exist. Use `WithStateInitialization(false)` only as a temporary migration opt-out; it disables lease cleanup and causes consumers such as anonymous A2A coordination to use their unavailable-capability behavior.
15 changes: 12 additions & 3 deletions docs/mkdocs/zh/a2a.md
Original file line number Diff line number Diff line change
Expand Up @@ -967,7 +967,16 @@ subAgent, _ := a2aagent.New(
`SessionService` 实现了 `session.StateInitializationService`,agent 会自动
使用该能力。它会在共享同一后端的多个 agent 实例之间协调首次匿名 Cookie
初始化。in-memory session service 只协调共享同一个 service 实例的调用方;
Redis session service 可以跨 service 实例协调。
Redis、MySQL 和 TDSQL session service 可以在共享同一后端时跨 service 实例协调。
MySQL 和 TDSQL 默认开启该能力。使用 `WithSkipDBInit(true)` 的部署必须先按当前
schema 创建 `state_initialization_leases` 表及其索引,并将
`session_states.created_at` 迁移为 `TIMESTAMP(6)`;同时还必须创建并回填
`session_states.state_initialization_active` 及其唯一索引,确保每个逻辑 session
最多只有一条活跃记录。即使跳过 DDL 初始化,服务启动时仍会执行只读的前置条件校验。

分阶段迁移 schema 时,可配置 `mysql.WithStateInitialization(false)`。此时 lenient
模式会保留原有的单 agent 回退路径,并且不会访问 lease 表;strict 模式仍会因为
协调能力不可用而在联系远端 agent 前失败。所有实例都使用新 schema 后再重新开启。

如果后端不支持该能力,agent 会保留现有的单 agent 初始化锁和持久化行为。
如果业务必须保证跨实例协调,可以开启 fail-closed 模式:
Expand All @@ -980,9 +989,9 @@ a2aAgent, err := a2aagent.New(
```

该选项默认为 `false`。启用后,strict 模式在缺少稳定持久化 session key,或
`SessionService` 不支持协调能力时,会在联系远端 agent 前使调用失败。该能力检查
`SessionService` 未提供可用协调能力时,会在联系远端 agent 前使调用失败。该能力检查
无法判断不同 service 实例是否实际共享协调状态。需要跨进程协调的部署必须使用
Redis 等共享后端,而不能使用相互独立的 in-memory service。
Redis、MySQL 或 TDSQL 等共享后端,而不能使用相互独立的 in-memory service。

在支持协调的路径中,规范 `.record.v1` 值和 legacy 投影会一起提交,因此新版本
写入的状态仍可被变更前的旧版本读取。这种兼容性是有意设计为单向的:规范记录
Expand Down
Loading
Loading