Skip to content

fix(runner): preserve session ordering when queued runs are cancelled - #1929

Open
zhangxiangnan wants to merge 1 commit into
google:mainfrom
zhangxiangnan:fix/session-run-queue
Open

zhangxiangnan wants to merge 1 commit into
google:mainfrom
zhangxiangnan:fix/session-run-queue

Conversation

@zhangxiangnan

@zhangxiangnan zhangxiangnan commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Description of Change

Cancelling a run while it waits for another run in the same session could let later runs start too early. Long queues of synchronous runs could also exhaust the stack.

Cancelled slots now wait for their predecessors, and completion notifications drain iteratively. Waiting runs start on the shared I/O scheduler with their subscribing caller's OpenTelemetry context, separately from that drain; the scheduled task retains its worker until callbacks return, so cancellation cannot strand a callback waiting for a follow-up run. Cancelling an active run releases its successor whether it started immediately or from the queue. Serialization remains scoped to each Runner.

Validation

  • Existing RunnerTest: 136 tests passed, no failures, errors or skips.
  • Both original ordering/long-queue regressions fail with the upstream Runner.java baseline (1bb1a7f8).
  • Three added tests reproduce the old PR's deadlock/cancellation regression and pass with the fix: blocking follow-up with/without an existing successor, and cancellation from another thread.
  • A queued-run context regression fails on 3c17479e (before this follow-up), passes before the scheduler change (7ca56638), and passes with the fix.
  • The long-queue test now uses Runner.builder() with a minimal BaseAgent.
  • Error Prone CheckReturnValue rejects the old ignored subscription and accepts the updated source.
  • Guava collection scan and git diff --check pass.
./mvnw -pl core -Dtest=RunnerTest test-compile surefire:test@basic

Tests use in-memory/test components; no live model or external session backend was used.

Related: #1341 (cooperative cancellation API), #1565 (recursion within an invocation).

@hemasekhar-p

Copy link
Copy Markdown
Contributor

Hi @zhangxiangnan, We greatly appreciate your contribution and the effort you put into this pull request. It is currently under review by our team. We will notify you if any additional details are needed.

@damianmomotgoogle damianmomotgoogle 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.

Thanks for the fix. Both new tests fail without it, so the ordering and stack-depth problems are real. Two issues need changes before this can land: the ignored Disposable (line 759) fails the Error Prone check in the build this PR is imported into, and a cancelled queued run can now deadlock a thread that blocks on a follow-up run for the same session (repro inline). The other comments are smaller cleanups.

return predecessor.andThen(result).doFinally(() -> {
// Cancelled runs still wait for their predecessors. Dispatch completions
// iteratively so long queues cannot exhaust the caller's stack.
predecessor.subscribe(() ->

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.

BUG (HIGH): predecessor.subscribe(...) returns a Disposable that is discarded here. RxJava annotates Completable.subscribe(Action) with @CheckReturnValue, and the build this PR is imported into runs Error Prone's CheckReturnValue check as an error, breaking compilation on import (CI passes because Maven does not run Error Prone). Assign the result, as line 1685 already does:

Disposable unused = predecessor.subscribe(...);

@zhangxiangnan zhangxiangnan Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Assigned the subscription to Disposable unused in 42eba47. Verified with Error Prone CheckReturnValue: the old Runner source is rejected at this call; the updated source passes.

Comment on lines 756 to 764
return predecessor.andThen(result).doFinally(() -> {
// Cancelled runs still wait for their predecessors. Dispatch completions
// iteratively so long queues cannot exhaust the caller's stack.
predecessor.subscribe(() ->
request.completions.execute(() -> {
request.completed.onComplete();
activeSessionRuns.remove(sessionId, request);
}));
});

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.

BREAKING (HIGH): If queued run B starts when its predecessor completes, is cancelled before its subscriber callback runs (for example by firstElement()), and the callback blocks on another same-session run, the thread deadlocks: B's release waits in the session executor behind the drain running that callback. On main, the follow-up runs.

Repro (passes on main, hangs here):

// A's model response is held open by a PublishProcessor.
TestSubscriber<Event> a = runner.runAsync("user", sid, msg("A")).test();
Disposable unused =
    runner.runAsync("user", sid, msg("B"))
        .firstElement()
        .subscribe(e -> runner.runAsync("user", sid, msg("C")).toList().blockingGet());
// Completing A's response on another thread leaves that thread blocked in blockingGet.

Releasing a run immediately when nothing is queued behind it fixes this case (RunnerTest passes):

if (activeSessionRuns.remove(sessionId, request)) {
  request.completed.onComplete();
} else {
  request.completions.execute(request.completed::onComplete);
}

It still deadlocks if another run is already queued behind B, because the drain runs the next run and its subscribers. Keep that work off the drain (for example, hand a waiting run's start to a scheduler)

@zhangxiangnan zhangxiangnan Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 42eba47. Waiting runs now start through a separate I/O task, leaving completion notifications free to drain. The task retains its worker until callbacks return; simply using subscribeOn was insufficient because cancellation could return that worker while the callback was still blocking. Added both variants (with and without an already queued successor): both fail against the old PR and pass with the fix. The full RunnerTest class passes all 136 tests. Follow-up review also caught OpenTelemetry context loss at that scheduler hop. The scheduled start now restores the subscribing caller's context; its regression fails before this follow-up and passes with it.

Comment on lines 756 to 764
return predecessor.andThen(result).doFinally(() -> {
// Cancelled runs still wait for their predecessors. Dispatch completions
// iteratively so long queues cannot exhaust the caller's stack.
predecessor.subscribe(() ->
request.completions.execute(() -> {
request.completed.onComplete();
activeSessionRuns.remove(sessionId, request);
}));
});

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.

EDGE CASE (LOW): Same cause as the deadlock above. If B started on its predecessor's completion and blocks that thread, cancelling B from another thread no longer releases the next run until B's blocking work returns. If B started first, cancellation still releases the next run immediately. On main, both cases released immediately. Please pick one behavior for cancelling the active run and test it.

@zhangxiangnan zhangxiangnan Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Cancellation now releases the successor in both cases, even while the cancelled run's subscriber callback remains blocked. Added a test covering immediate and queued starts, with cancellation from another thread. It reproduces the old PR's queued-start failure and passes in 42eba47.

Comment on lines +741 to +758
SessionRun[] previousHolder = new SessionRun[1];
SessionRun request =
activeSessionRuns.compute(
sessionId,
(key, previous) -> {
previousHolder[0] = previous;
// Dispatch completions for this session without adding a worker thread.
Executor completions =
previous == null
? MoreExecutors.newSequentialExecutor(MoreExecutors.directExecutor())
: previous.completions;
return new SessionRun(completions);
});
SessionRun previous = previousHolder[0];
Completable predecessor = previous == null ? Completable.complete() : previous.completed;
return predecessor.andThen(result).doFinally(() -> {
// Cancelled runs still wait for their predecessors. Dispatch completions
// iteratively so long queues cannot exhaust the caller's stack.

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.

CLEANUP (LOW): SessionRun can store its predecessor directly. That drops the previousHolder array and the previous and predecessor locals, and lets the two-line comment fit on one line:

SessionRun request =
    activeSessionRuns.compute(
        sessionId,
        (key, previous) ->
            previous == null
                ? new SessionRun(
                    Completable.complete(),
                    MoreExecutors.newSequentialExecutor(MoreExecutors.directExecutor()))
                : new SessionRun(previous.completed, previous.completions));
return request.predecessor.andThen(result).doFinally(() -> {
  // A cancelled run waits for its predecessor; the executor keeps long queues off the stack.
  ...
});

Add final Completable predecessor; to SessionRun and its constructor. RunnerTest passes with this change.

@zhangxiangnan zhangxiangnan Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

SessionRun now stores its predecessor directly and constructs the shared completion executor from the previous slot. Removed previousHolder and the previous/predecessor locals in 42eba47. It also records whether the run was queued so only waiting runs need the asynchronous start.

Comment on lines +1048 to +1054
@SuppressWarnings("deprecation") // Exercise Runner serialization through its extension point.
@Test
public void runAsync_releasesSynchronousQueuedRunsInOrderWithoutRecursion() {
CompletableSubject release = CompletableSubject.create();
AtomicInteger calls = new AtomicInteger();
runner =
new Runner(agent, "test", new InMemoryArtifactService(), runner.sessionService(), null) {

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.

CLEANUP (LOW): This test subclasses Runner via a deprecated constructor and suppresses deprecation on the whole method. Instead, pass Runner.builder().agent(...) a minimal BaseAgent whose runAsyncImpl does the same ordering check; that exercises the same queue through the public API with no suppression. That version passes on this PR and overflows the stack on main, so it still guards the fix.

@zhangxiangnan zhangxiangnan Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reworked the long-queue test to use Runner.builder() and a minimal BaseAgent, and removed the deprecation suppression. Both original queue regressions still fail with upstream Runner restored and pass with the fix; the full RunnerTest class passes 136 tests. Updated in 42eba47.

@damianmomotgoogle damianmomotgoogle added waiting on reporter Waiting for reaction by reporter. Failing that, maintainers will eventually closed it as stale. and removed needs review labels Nov 27, 2026
@zhangxiangnan
zhangxiangnan force-pushed the fix/session-run-queue branch 2 times, most recently from 3c17479 to 42eba47 Compare November 27, 2026 12:34
@hemasekhar-p hemasekhar-p added needs review and removed waiting on reporter Waiting for reaction by reporter. Failing that, maintainers will eventually closed it as stale. labels Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants