agentscope-java icon indicating copy to clipboard operation
agentscope-java copied to clipboard

[Bug]: Outbox/replay re-INSERTs already-persisted events → UNIQUE(event_id) conflicts on dp.builder_session_event; SSE events/stream keeps rejecting with HTTP 400 until dataplane restart

Open ly19911114 opened this issue 4 weeks ago • 2 comments

环境

  • agentscope-service 2.1.0-BETA1(官方 docker compose 五容器自托管,PostgreSQL 17 后端)
  • 长会话多轮对话(单轮含多条工具调用 + 流式文本事件),客户端走 Session API(POST turn + GET events/stream)

场景

同一会话连续多轮对话过程中,SSE events/stream 间歇性开始返回 HTTP 400;客户端按快照→续流协议重连,持续 400,表现为前端「重连中」。turn 本身在服务端已完整执行(工具调用全部返回、模型回复已生成),但前端只能收到断流前已投递的部分增量。

复现时间线(实测日志,时间已对齐)

  1. T+0 turn 开始执行;T+15s 所有工具调用与模型输出完成;
  2. T+22s 起 data 容器日志爆发 同一唯一约束的连续冲突风暴(scheduling-1 与 undedElastic-* 线程每毫秒级重试):
    WARN org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 0, SQLState: 23505
    ERROR: duplicate key value violates unique constraint "uk6h66n2ccgbnk4xyavx3lbxnjn"
    
    该约束即 dp.builder_session_event 上的 UNIQUE (event_id);
  3. 自此该会话 events/stream 打开即 400,客户端重连循环 3 分钟无恢复;
  4. T+3m46s 手工 docker restart data 容器 → 立即恢复;刷新后快照返回完整的 turn 结果(Postgres 中数据完整,中断的只是事件投递)。

根因分析

  • 冲突的粒度是 event_id 本身(非 #3770 的 (session_id, seq) 水位竞态):同一 event_id 已存在仍再次 INSERT,说明同一事件被投递/重放了两次——典型的 outbox「投递成功但 ack 丢失后重投」或恢复路径重放已落库事件;
  • INSERT 裸写 + 严格唯一约束 → 重复投递必然 23505;重试循环内不收敛(风暴持续分钟级),事件管道停摆,events/stream 对受影响会话持续 400;
  • 重启 data 容器即恢复:内存中卡死的投递任务被清除、从 Postgres 一致状态重建——根因未修,事件量一大即复发(我们当天上午/晚上各发作一次,均为多轮长会话)。

与 #3770 的关系

#3770 报的是 ux_builder_session_event_seq(seq 分配竞态,并发双平面 append);本 issue 是同表第二个唯一约束 UNIQUE(event_id)(重复投递/重放幂等性缺失)。两者症状同族(SSE 卡死)但触发机制不同,需分别修复。

期望行为

事件落库对重复投递幂等:同 event_id 再次写入应为 no-op(或 upsert),不阻塞事件管道、不影响流端点。

建议修复

  • 事件持久化改 INSERT ... ON CONFLICT (event_id) DO NOTHING(PG)或先查后写;
  • 顺带复核 #3770 的 seq 分配原子性;
  • 另一个观察供参考:手工 drop 掉 ux_builder_session_event_seq 后,data 容器重启该约束会被重建(schema 似在启动时强制)——即「删约束」绕法对平台重启不持久,更需要上游从写入侧解决。

影响面

  • 所有 Session API 消费方(自研前端/Console/自动化客户端):长会话高频事件下随机触发流 400 + 前端卡死,需重启 data 容器恢复;
  • checkpoint/usage 等依赖该事件表的能力同样被连带。

临时缓解(供其他用户参考)

ALTER TABLE dp.builder_session_event DROP CONSTRAINT uk6h66n2ccgbnk4xyavx3lbxnjn;
ALTER TABLE dp.builder_session_event DROP CONSTRAINT ux_builder_session_event_seq;

消费端需自行按 event.id 去重(我们的 SSE reducer 已按 id 去重,重复行无害);注意平台重启可能重建约束,需复查。

ly19911114 avatar Nov 04 '26 15:11 ly19911114

The mechanism looks a little different from "the outbox delivered it twice", and it explains why the storm lasts minutes instead of failing loudly once.

SessionEventLog.appendIdempotent does check findByEventId before inserting, so a duplicate that arrives after the first row is committed is handled. The failing shape is the two paths that get past that check:

  1. Two concurrent deliveries both find nothing — check-then-act with no unique arbitration — so both proceed to insert. That part is inherent to the read-then-write.
  2. appendInternal then misreads the failure as a seq conflict. isSeqConflict returns true for any message containing unique constraint, and the event_id violation reads duplicate key value violates unique constraint "uk6h66n2ccgbnk4xyavx3lbxnjn". So it retries MAX_SEQ_RETRIES (16) times, and every retry re-inserts the same event_id — 16 more violations, then IllegalStateException.

That is why the retries are millisecond-level and never converge: the storm is the retry loop itself, not repeated external delivery, and it lives in the request thread, which is consistent with only a restart clearing it.

What I would change:

  • narrow isSeqConflict to the seq constraint (ux_builder_session_event_seq), so an event_id duplicate never enters the seq retry path;
  • in appendInternal, when the append carries an eventId and fails on a duplicate, re-read that row in a fresh transaction and return it when session/type match — i.e. honour the idempotency the caller asked for instead of retrying into a wall;
  • test: the same eventId appended twice, the second one bypassing the pre-check → one row, no retry loop; a genuine seq conflict still retries.

One thing I cannot see from here and would like your help with: in the storm, is the constraint named per retry the event_id one (uk6h66n2ccgbnk4xyavx3lbxnjn) rather than ux_builder_session_event_seq? If you still have those log lines, that single detail confirms or kills the diagnosis. Your #3770 note also suggests both constraints were in play at different times, which would fit.

I would like to take this one unless you are already on it.

wahllllll avatar Nov 07 '26 23:11 wahllllll

Correction to my analysis above: I read a stale local main, and both main and v2.1.0-BETA1 already contain a guard for exactly this.

SessionEventLog.appendInternal (from a2cbea5c3, 2026-10-08, "redesign Harness context and unify Service sessions with JEV"):

if (eventId != null && repository.findByEventId(eventId).isPresent()) {
    throw ex;
}

and appendIdempotent wraps the append:

try {
    return appendInternal(sessionId, type, payload, eventId, mirror, scope);
} catch (RuntimeException error) {
    if (repository.findByEventId(eventId).isPresent())
        return appendIdempotent(sessionId, type, payload, eventId, mirror, scope);
    throw error;
}

git merge-base --is-ancestor a2cbea5c3 v2.1.0-BETA1 succeeds, so your build has it too. The sixteen MAX_SEQ_RETRIES attempts I described therefore cannot be what you saw — the loop exits on the first attempt once the row exists, and the idempotent caller then replays the winner.

Which moves the question one level up: the retry storm in your logs is coming from a caller that retries on failure, not from the append loop. scheduling-1 and unboundedElastic-* ticking every millisecond for minutes reads like the outbox delivery loop. If that loop treats "already persisted" as an error instead of success, it will spin exactly like that, and the events/stream 400 afterwards would be the same task stuck holding the pipeline while the row is already there.

Two details would settle it, and both are in your logs:

  1. Does each storm line carry Session event seq conflict for ... (attempt n/16) (debug, from SessionEventLog), or something from the mirror/outbox path? If it carries the attempt counter, I am wrong twice and want to know.
  2. Is the constraint named per line uk6h66n2ccgbnk4xyavx3lbxnjn (event_id) or ux_builder_session_event_seq? If it is the seq constraint, the cause is #3770 after all and not this path.

I will go through the mirror and outbox delivery path meanwhile, since a loop that never converges is what I would expect to find there. Sorry for the noise — the diagnosis, not the bug report, was mine.

wahllllll avatar Nov 07 '26 23:11 wahllllll