Skip to content

fix(durable): finish AG-UI runs when a turn waits for interaction - #4255

Closed
chcodex wants to merge 6 commits into
agentscope-ai:mainfrom
chcodex:fix/durable-agui-hitl-interrupt
Closed

chcodex wants to merge 6 commits into
agentscope-ai:mainfrom
chcodex:fix/durable-agui-hitl-interrupt

Conversation

@chcodex

@chcodex chcodex commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.1.0-SNAPSHOT, based on upstream/main at c1d482900.

Fixes #4254.

Why

DurableAguiEventAdapter.committed() mapped run.started, run.ended, step events, message.completed and tool.call.updated, but dropped the committed interaction.requested event. When a native tool needed human input, the Turn parked in WAITING without a terminal AG-UI interrupt:

  1. clients never received RUN_FINISHED with an interrupt outcome, so they could not render the question card or obtain the interruptId needed to resume;
  2. the parked run.ended is not the terminal frame, so the client had no supported way to end the run at the interrupt and continue from it.

WAITING itself is correct and is unchanged: the adapter commits TurnStatus.WAITING, DurableRuntime releases the lease, and readyAt() returns -1 when the waiting deadline is 0. No worker thread or lease is held.

A Turn can wait on multiple interactions at once (for example a confirmation plus an external-execution request). AG-UI 1.0 requires one terminal event per run and allows a non-empty interrupts array, so all pending interactions must be delivered together.

Changes

  • TransactionalSessionBackend now adds the Turn's pending interactions array to the committed turn.waiting event, together with the active runId. protocol/schema.json allows the field on turn.* events.
  • DurableAguiEventAdapter maps turn.waiting to exactly one RUN_FINISHED whose RunFinishedInterruptOutcome contains every pending interaction. Individual interaction.requested events are not terminal and are no longer mapped on their own.
  • interrupt.id is the Durable interaction id (hash(turnId, requestId)); interrupt.toolCallId is the interaction request id (the tool call id), so the client can resume with the id it received instead of a regenerated one.
  • Before the terminal event the adapter closes the steps, messages and tool calls the Run opened, including the RUN_ERROR path. Adapter state is reset per Run.
  • Confirmation interrupts declare a boolean responseSchema, matching the payload that TransactionalSessionBackend.control() and AgentScopeAdapter accept, and use the permission_confirm interrupt kind expected by AguiInterruptConstants; external execution keeps its external_execution kind and uses a matching message instead of a confirmation prompt. A waiting Turn without pending interactions (for example waiting on a signal) has no AG-UI interrupt to deliver; its stream follows the Run's own terminal event.
  • AguiEvent gains RunFinishedCancelledOutcome ({"type":"cancelled"}); non-suspended stopped Runs use it instead of being reported as success. A failure after an interrupt is still reported as a late RUN_ERROR.
  • Tests: single and multiple pending interactions, open step/message/tool-call closing, cancelled and successful outcomes, duplicate turn.waiting, suspended run.ended, and failure before/after an interrupt. UserApiContract verifies turn.waiting carries the active runId and every pending interaction id.
  • Docs updated in English and Chinese (docs/dev/*/docs/harness/durable.md).

Follow-up from an end-to-end run

An end-to-end run against a real backend with a tool that requires confirmation showed the committed order for a parked Turn:

run.ended    status=STOPPED  reason=TOOL_SUSPENDED
turn.waiting data.interactions=[...]

run.ended arrives first, and its reason is the native GenerateReason (TOOL_SUSPENDED for a suspended tool such as question; PERMISSION_ASKING appears when a permission hook parks the Turn). The adapter previously suppressed only STOPPED + suspended, so it turned the parked run into RUN_FINISHED(cancelled) and then deduplicated the following turn.waiting. The fix:

  • runEnded treats the parked reasons (suspended, PERMISSION_ASKING, TOOL_SUSPENDED) as non-terminal; only turn.waiting closes the AG-UI run. Host pause (HOST_PAUSED) keeps its reason and still closes as cancelled.
  • The adapter Javadoc and the Durable docs state that a parked Run still reports run.ended first and that the terminal frame is turn.waiting, not run.ended.
  • The runtime ends a parked native Run quietly only when the Turn has pending interactions (InvocationRecords.suspend), so that park does not emit an extra run.ended; the step it closes is still reported. Waits without interactions keep the previous run.ended(host_released) behaviour.
  • Tests cover STOPPED + TOOL_SUSPENDED and STOPPED + PERMISSION_ASKING producing no frames, the following turn.waiting producing exactly one interrupt RunFinished, STOPPED + HOST_PAUSED and STOPPED + host_released still producing the cancelled outcome, the HITL park emitting no run.ended, and a wait without interactions still ending its native Run.

Client note (not part of this repository)

Because the parked run.ended arrives before turn.waiting, a client stream that terminates on every run.ended, or that replays a Turn from its beginning on resume, drops the interrupt. A gateway needs to:

  • skip run.ended(STOPPED, parked reason) when detecting a terminal frame;
  • capture the Turn head cursor before answering and stream after it, so the previous turn.waiting is not replayed.

Testing

Check Result
mvn -B -ntp -pl agentscope-durable/durable-adapters/durable-adapter-agui test 16 passed
mvn -B -ntp -pl agentscope-durable/durable-runtime test 36 passed
mvn -B -ntp -pl agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui test 578 passed
mvn -B -ntp -pl agentscope-extensions/agentscope-extensions-durable-jdbc test 107 passed
mvn -B -ntp -pl agentscope-durable/durable-adapters/durable-adapter-harness-agentscope test 60 passed
mvn -B -ntp -T1C -DskipTests package BUILD SUCCESS
spotless:check on changed modules passed
docs: npm test, npm run validate, npm run broken-links 20 passed / passed / no broken links

Checklist

  • Code has been formatted with mvn spotless:apply
  • Affected module tests pass
  • Javadoc comments follow project conventions
  • English and Chinese documentation updated
  • No unrelated changes
  • Code is ready for review

The committed interaction.requested event was dropped, so AG-UI clients never received a terminal event, the live stream stayed open until timeout, and the application kept a busy conversation handle.

Carry the Turn's pending interactions on turn.waiting and map that event to one RUN_FINISHED with all interrupts. Use the Durable interaction id as interrupt id and the request id as toolCallId, close the steps, messages and tool calls the Run opened, reset adapter state per Run, and map non-suspended stopped Runs to the cancelled outcome.

Add regression tests for single and multiple interactions, open-item closing, cancelled runs, duplicate waiting events and late failures.
@mintlify

mintlify Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 2be2b2a.

Approve preview

A real backend emits run.ended(STOPPED, PERMISSION_ASKING) before turn.waiting. Treat parked run.ended as non-terminal so the following turn.waiting can deliver the interrupt, and end the parked native run quietly so no extra run.ended competes with it.

Add tests for PERMISSION_ASKING suppression, the following interrupt RunFinished, host_released remaining cancelled, and the parked transition emitting no run.ended.
Map Durable confirmation interactions to the permission_confirm interrupt kind that AguiInterruptConstants and AguiMessageConverter expect, so downstream resume handling recognises them. Document that a waiting Turn without pending interactions produces no terminal frame.

Assert both the confirmation and external-execution metadata kinds in the adapter test.
A live suspended tool such as question ends the native run with reason TOOL_SUSPENDED, not PERMISSION_ASKING. Use a named parked-reason set (suspended, PERMISSION_ASKING, TOOL_SUSPENDED) so the following turn.waiting delivers the interrupt, while HOST_PAUSED and host_released still close as cancelled.

Add TOOL_SUSPENDED and HOST_PAUSED adapter tests; keep PERMISSION_ASKING coverage.
private static final Map<String, Object> CONFIRM_RESPONSE_SCHEMA =
Map.of(
"type",
"object",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we align this response schema with what Durable accepts on resume? The schema asks for {"approved": true}, but both TransactionalSessionBackend.control() and AgentScopeAdapter currently require a boolean, so a response following this schema would be rejected. Would a boolean schema be sufficient for this fix? Supporting editedArgs and reason would also need response conversion and a test covering confirmation through successful resume.

@iluv7 iluv7 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left an inline comment with the details.

@iluv7

iluv7 commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

One thing I’d like to clarify: since the adapter already filters out run.ended for parked runs, what case does silently ending the run in the runtime address? This also changes the event sequence seen by other Durable consumers, including waits without human interactions. If handling this in the adapter is sufficient, could we consider preserving the existing runtime behavior to keep this fix more focused?

Declare a boolean confirmation response schema because Durable accepts only a boolean payload. End the native run quietly only when a waiting Turn has pending interactions; waits without interactions keep the previous run.ended(host_released) behaviour.

Add contract coverage for a wait without interactions and assert the boolean schema.
xzxiaoshan added a commit that referenced this pull request Nov 20, 2026
…#4274)

## Background

Swept the last 125 PRs (#4272→#4075) for single-OS CI failures under
`mvn -B -T1C clean verify` (one build OS red, the other green on the
same commit = flake suspect). Cross-PR repeats and main's own red run on
2026-11-19 (ubuntu, run 44516464414) pinpoints four still-broken test
classes; all fixes are test-side only (no `src/main` changes).

## Fixes and evidence

| Test class | Victims | Signature | Fix |
|---|---|---|---|
| `RocketMqExecutionTest` | #4182, #4192, #4103 + main run 44516464414
(2026-11-19, ubuntu) | `turn reaches SUCCEEDED did not become true
within 10s` while the turn kept progressing (modelCalls complete, acks
climbing, lastFailure=none) — deadline breakthrough under starvation,
not a lost turn | shared `waitUntil` deadline 10s→30s (repo tier
#3726/#3774) |
| `AgentScopeAdapterTest` | #4204 (same-commit re-run green = confirmed
flake), #4191, #4246 | `Timed out observing Turn` at 6.7–8.5s elapsed;
resume/recovery one step from terminal | `turn.await(5s)`→30s at all 3
sibling sites via `TURN_DEADLINE`, outer `get` budgets +5s margin |
| `WorkerRuntimeTest` | #4219, #4224, #4255 (windows) | (a) `Worker
lease lost` after 2.4s — 1s claim leases expired between claim and
release; (b) `renewed.await(5s)` missed at 6.5s while the recovery lane
was healthy; (c) `Interrupted sleep interrupted` —
`WorkerRuntime.process()` interrupts the calling thread on lease-renewal
failure and manual `tick()` runs it on the test thread | (a) claim
leases 1s→30s (staleness under test still comes from `release(ZERO)` +
re-claim); (b) latches 5s→30s; (c) raw `Thread.sleep`→interrupt-proof
`pause()` at 5 sites, mirroring the #4176 fix for the same signature in
`ProcessRecoveryTest` |
| `ChatSessionsTest.await` (shared with `ChatControllerTest`) | #4233,
#4182 (stuck-RUNNING at 40.8s/46.4s), #4268, #4163 (poll threw `Durable
database transaction failed`) | two surfaces of one cause: every
snapshot poll opens a writing sqlite transaction contending with the
runtime's own writes, and windows runners starve turns past 30s (same
file already measured 56.6s starvation and uses 120s elsewhere, #3726) |
deadline 30s→120s (aligned tier) + tolerate transient `UNAVAILABLE`
store exceptions while polling; persistent failure rethrows at the
deadline, FAILED-turn fast-fail unchanged |
| `CommandExecutorTest.missingExitCodeIsUnknown` | local -T2C full-repo
stress (2026-11-19; pristine-main baseline of the same class green) |
the 2s network budget fired on scheduler starvation before the instant
fake response was processed, misclassifying the failure as a deadline
miss instead of a missing exit code (2.97s elapsed) | budget 2s→30s for
this non-deadline-semantics test; the two deadline-semantics tests keep
their tight budgets |

## Constraint compliance

- Happy path zero cost: every change only extends failure-path deadlines
or hardens helpers; no new sleeps, no weakened assertions.
- Minimal widening anchored to measured data (each comment cites victims
+ measured values); 30s follows the repo's established deflake tier,
120s follows this file's own previously measured starvation tier.
- Structural hardening preferred: `pause()` helper, transient-lock
retry, lease decoupling from the tested invariant.
- No `src/main` changes.

## Observed but deliberately not fixed here

-
`ProcessRecoveryTest.replacementCollectsOriginalResultWithoutRepeatingEffect`
(#4214: `expected: 2 but was: 3`): recovery-semantics race (model re-run
without effect re-run after abrupt halt) — a product question for the
durable recovery work, not a deadline flake.
-
`JevEvidenceProcessorTest.filterFailureIsWithheldButRankFailureFollowsScoredEvidence`
(#4265: delivered `[]` on a 25×-slowed runner): root cause not
established; single occurrence.
- Already fixed upstream, victims predate the fix:
`AgentScopeAgentExecutorInputRequiredTest` (#4157/#4187/#4152 all
predate #4176's `BaseReActAgentRunner` change), `InboxMiddlewareTest`
(#4093 predates #3738), `HarnessAgentSubagentStreamEventsTest` (#4183
predates #2917).
- `SkillBoxTest$UploadContainment` quartet (#4201/#4202/#4212/#4229):
test does not exist on main (fork stack only); deterministic cross-drive
path bug, not load flakiness.
- #4184/#4185: both-OS compile breaks from dependency major bumps
(dependabot), out of scope.

Also applied during review: sibling sites with the identical measured
mechanism were widened in the same pass — the remaining 1s fixture claim
leases in `WorkerRuntimeTest` (fenced begin/update/release sequences,
same #4219 signature), the start/PAUSED 5s budgets in the same
`AgentScopeAdapterTest` method as the victims, and the 5s/4s observe
budgets in
`completeLocalBackendRunsNativeAgentWhileManagedObserverIsBlocked`.

## Test plan

- [x] Full local `mvn -B -T2C clean verify` green (stricter than CI's
-T1C). Locally excluded, each verified to fail identically on pristine
main on this machine (Windows/git-bash) while passing on CI:
`JsonFileAgentStateStoreTest` (symlink permissions), the
`agentscope-extensions-durable-sandbox` trio plus
`ToolInSandboxExampleTest`/`SandboxRoundTripTest` (sandbox shell heredoc
incompatible with local git-bash python3), and the
`AgentScopeAdapterTest`/`ProcessRecoveryTest`/`HarnessExternalToolProcessRecoveryTest`
trio (durable-adapter classes whose Windows runs are skipped on CI; the
same named tests fail on pristine main locally).
- [ ] CI green on both OS.
xzxiaoshan added a commit that referenced this pull request Nov 26, 2026
…#4435)

## Background

Swept the last 125 PRs (#4434→#4239), every single-OS-failed CI run
since 2026-11-19 and the main-branch push runs for `mvn -B -T1C clean
verify` failures (one build OS red and the other green on the same
commit = flake suspect). Four test classes still fail on current main:
three fail on windows-latest only, and the fourth sits at its deadline
on both OSes. All fixes are test-side only (no `src/main` changes).

## Fixes and evidence

| Test class | Victims | Signature | Fix |
|---|---|---|---|
| `HarnessAgentStructuredOutputStreamEventsTest` | #4296, #4349, #4071,
main run 44879286932 (2026-11-20 to 11-23), all windows-latest |
`streamEvents(...).block(10s)` timed out at 10.2-11.3s per call; the
class takes 3.7-9.6s on windows-latest when green and 1-1.5s on ubuntu |
ephemeral `InMemoryThreadJournalStore` in the three workspace-backed
tests (the fourth already used one) |
| `HarnessAgentOverflowRecoveryTest` | #4042, #4426 (2026-11-26), both
windows-latest; the journal rows were added by #4399 on 11-25 | row
`[3]` (journal=true) crossed `block(30s)` at 36.3-38.1s and row `[4]`
passed with 33.8s; the same rows take 0.4-1.3s on ubuntu, and main's own
run 45595615922 needed 61s for the class on windows-latest | ephemeral
`InMemoryThreadJournalStore` in `newAgent` |
| `DashScopeMultiModalEmbeddingTest` | #4413 (2026-11-25),
windows-latest | the first SDK request in the fork hit the 5s latch
(7.29s elapsed); the class takes 1.4-4.2s on windows-latest even when
green | first-request latch 5s→15s |
| `AnthropicAutoConfigurationTest` | #2363, run 45137197507
(2026-11-23), windows-latest | the first gateway test crossed
`block(10s)` at 15.66s; the other three take under 1s, and this one
already takes 5-11s on windows-latest and 9-12s on ubuntu when green |
block 10s→30s |

The first two share one cause: since #4154 the default workspace journal
is `SqliteJournalStorage` on Windows, which opens a JDBC connection per
storage operation and commits every CAS as a durable transaction (DELETE
journal, synchronous EXTRA). A journaled turn issues about 20 such
writes at roughly 8ms each on a fast local disk. Neither class asserts
journal persistence, so they now use the ephemeral backend the
repository already documents for tests. Locally on Windows the
overflow-recovery class dropped from 17.9s to 5.6s and the
structured-output class from 3.2s to 1.6s.

## Constraint compliance

- Happy path zero cost: the journal swap removes work, the two
relaxations only move failure deadlines, and no sleeps or weakened
assertions were added.
- Structural hardening first: the journal swap is structural. For the
two cold-start waits the structural alternative, a warm-up request
before the timed section, would add a request to every run, so the
deadline was relaxed instead.
- Minimal widening anchored to measured data: each relaxation is 3x the
deadline that was crossed, and every comment cites its victims and
measured values.
- No `src/main` changes.

## Observed but deliberately not fixed here

-
`WorkerRuntimeTest.saturatedStartsDoNotBlockRecoveryAndDrainPreservesActiveLeases`
(#4294, windows-latest, 36.19s at the `renewed` latch): with the test's
4s worker lease a heartbeat delayed by more than 2.7s finds the lease
already expired and fails with `Worker lease lost` instead of arriving
late, so widening the latch (as #4274 did to 30s) cannot help. That
latch is the only place asserting the runtime renews leases, and a
longer lease would delay the first heartbeat by lease/3, so the fix
needs a design decision.
-
`SubagentFactoryDeclarationTest.declaredFactory_persistSessionIsolatesUsers`
(main run 45172445003, 2026-11-23, 31.45s) and
`ChatControllerTest.httpUsesExplicitCreationAndTargetedIdempotentControls`
(main run 44566773929 and #4255, both 2026-11-19): no recurrence since.
- Two windows-latest hangs that ended at the 2h job timeout:
`AgentSpawnToolPermissionTest` (#4305, run 44760439728) and
`AgentSpawnToolPlanModeTest` (main run 45739005058 on the current head).
Both classes wait with unbounded `.block()`; the root cause is not
established, and the 30-minute Surefire fork timeout in the root pom did
not end either run.
- The cost of the Windows default journal itself (one JDBC connection
and one durable transaction per storage operation) is a production
concern that deserves its own `src/main` change.
- Already fixed upstream, victims predate the fix:
`JevEvidenceProcessorTest` (13 runs, fixed by #4346),
`ChatSessionsTest`, `RocketMqExecutionTest` and `AgentScopeAdapterTest`
(fixed by #4274).
@chcodex chcodex closed this Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Durable AG-UI adapter drops HITL interact, leaving the run stream open

3 participants