Skip to content

feat(adk): clone and validate session events, restore past turns, and reject stale checkpoints - #1506

Open
hi-pender wants to merge 8 commits into
alpha/10from
feat/adk-session-event-clone
Open

hi-pender wants to merge 8 commits into
alpha/10from
feat/adk-session-event-clone

Conversation

@hi-pender

@hi-pender hi-pender commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

ADK session feature and correctness fixes for alpha/10.

Session behavior

  • Capture and validate events. The persister takes an in-memory snapshot of each queued event. ADK and reduction share clone helpers for framework-owned message fields. Opaque application values and read-only tool schemas retain their references. ADK validates emitted events before append and preserves stream and child-session identity.
  • Start a turn. A fresh turn submits session.status_running and the input messages in one ordered AppendEvents call. Atomicity depends on the store. The runner releases the session handle on setup and execution panics.
  • Return to an earlier answer. RollbackSession accepts any earlier idle(end_turn) in the same session, including a turn skipped by a previous rollback. Rollback appends a marker with the effective FromEventID and requested ToEventID. Set WithRollbackSessionFromEventID to reject the request with ErrSessionHeadChanged if the user’s starting point has changed.
  • Rebuild the next turn. Run follows rollback targets backward to the applicable messages_replaced or the start of the log, then replays messages in order. Message updates retain the target message ID. Both replay and rollback default to 300 pages and detect stalled pagination. Configure them independently with SessionConfig.MaxReplayLoadPages and WithRollbackSessionMaxLoadPages.
  • Resume an interrupt. A session checkpoint records the persisted idle event’s ID. Resume compares it with the latest checkpoint-relevant event and returns ErrCheckpointStale if the session has advanced. It decodes execution state before appending x.resume.request_started. TurnLoop uses the checkpoint consumption result to preserve retryable state and queued inputs.
  • Retry cleanup after rollback. When the rollback marker is durable but checkpoint deletion fails, errors.As exposes a *RollbackCheckpointCleanupError. Pass its RollbackEventID to RetryRollbackCheckpointCleanup to retry only deletion. A newer execution or rollback protects its checkpoint, even when two rollbacks chose the same idle.

The event log guides walk through replay, reduction clear, resume, rollback and timeline pagination. English · 中文

Alpha compatibility

  • Go API and stored rollbacks. Rename RollbackSessionOptions.ExpectedHeadEventID to FromEventID and WithRollbackSessionExpectedHeadEventID to WithRollbackSessionFromEventID. The stored rollback source changed from SessionRollbackEvent.PreviousHeadCommitEventID to FromEventID. In a custom SessionEventStore.LoadEvents, read rollback.from_event_id when present and fall back to rollback.previous_head_commit_event_id for older JSON records. For gob or other field-name formats, decode the legacy field in the storage representation and map it to FromEventID.
  • Existing checkpoints and replacements. Checkpoints without IdleEventID still validate session ownership when SessionID is present. New messages_replaced writes require at least one message. Previously stored explicit empty lists still replay as a cleared context.
  • Span metadata. ModelSpanMeta.Usage now uses *schema.TokenUsage, and TTFTMS moves from SpanEvent to ModelSpanMeta. This removes SpanEvent.Name, ModelSpanMeta.Accepted and ModelUsage. The event classification, normalization and emitted-kind validation helpers are now package-private.

Validation

  • GOWORK=off go test -race -count=1 ./... passed on Go 1.27.1. Focused rollback, cleanup, checkpoint resume and pagination regressions also passed on Go 1.18.10.
  • Incremental golangci-lint against alpha/10 reported zero issues in ./internal/schema/... and ./adk/....
  • On darwin/arm64 with Go 1.27.1, BenchmarkSessionEventClone measured 9 allocations per schema.Message snapshot and 7 per schema.AgenticMessage snapshot. The encode/decode/validate path using schema.HumanReadableSerializer measured 369 and 351 allocations respectively.

Comment thread adk/chatmodel.go Resolved
@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.64905% with 79 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.78%. Comparing base (269a188) to head (5212a93).

Files with missing lines Patch % Lines
adk/runner.go 86.63% 16 Missing and 17 partials ⚠️
adk/session.go 89.07% 18 Missing and 14 partials ⚠️
adk/wrappers.go 78.57% 2 Missing and 4 partials ⚠️
adk/turn_loop_checkpoint.go 87.09% 2 Missing and 2 partials ⚠️
adk/chatmodel.go 71.42% 1 Missing and 1 partial ⚠️
internal/schema/message_clone.go 99.18% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##           alpha/10    #1506      +/-   ##
============================================
+ Coverage     82.26%   82.78%   +0.51%     
============================================
  Files           216      218       +2     
  Lines         36662    36743      +81     
============================================
+ Hits          30160    30416     +256     
+ Misses         4362     4227     -135     
+ Partials       2140     2100      -40     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread adk/session.go Resolved
Follow rollback targets during bounded replay and let callers guard the source with FromEventID. Report checkpoint cleanup failures after a successful rollback and support retrying the deletion by rollback event ID.

Record the idle event in session checkpoints, preserve pending inputs across failed resumes, and batch turn start with its input. Document the event model and migration in English and Chinese.
@hi-pender hi-pender changed the title refactor(adk): clone session events and centralize timeline validation feat(adk): restore historical session turns and reject stale checkpoints Nov 27, 2026
@hi-pender hi-pender changed the title feat(adk): restore historical session turns and reject stale checkpoints feat(adk): clone and validate session events, restore past turns, and reject stale checkpoints Nov 27, 2026
@mrh997

mrh997 commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

问题简述: 为什么将新写入的 messages_replaced 改为必须至少包含一条消息?此前空列表可以表达清空上下文,这个 PR 也仍支持历史空列表替换的重放。这里是否有具体的执行或存储约束,要求禁止新写入空列表?

导致问题的链路: 如果业务需要支持 /clear,希望保留同一个 SessionID 和完整事件日志,但清空当前模型上下文,让下一次 Run/Query 从新输入开始,那么原先的 messages_replaced([]) 可以表达这个操作,新增校验会拒绝它。

修复建议: 如果没有必须禁止空列表的约束,能否继续允许显式的空列表替换?如果这个限制是有意的设计,请说明 /clear 应使用哪个 API 或事件实现,以及对应的重放语义。

@mrh997

mrh997 commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

问题简述: 为什么将历史重放和回滚查找从没有页数上限,改为默认最多扫描 300 页?新增上限要解决什么具体问题,300 页的取值依据是什么?

导致问题的链路: 对于正常分页的长会话,如果 300 页内还没有找到生效的 messages_replaced、日志开头或所需的回滚位置,原先可以继续读取,现在会返回 ErrSessionScanLimitExceeded,导致 Run/Query 或回滚失败。这会改变已有长会话的行为。

修复建议: 能否说明长会话超过上限时的推荐处理方式,并考虑提供显式不限制页数的选项?目前非正值仍使用默认 300 页,只能调大上限。如果主要是防止异常分页,重复游标和空页检查之外,硬性页数上限还要覆盖哪种场景?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants