Repository navigation
fix(runner): preserve session ordering when queued runs are cancelled - #1929
zhangxiangnan wants to merge 1 commit into
Conversation
|
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
left a comment
There was a problem hiding this comment.
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(() -> |
There was a problem hiding this comment.
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(...);There was a problem hiding this comment.
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.
| 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); | ||
| })); | ||
| }); |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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.
| 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); | ||
| })); | ||
| }); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| @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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
3c17479 to
42eba47
Compare
42eba47 to
f489352
Compare
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
RunnerTest: 136 tests passed, no failures, errors or skips.Runner.javabaseline (1bb1a7f8).3c17479e(before this follow-up), passes before the scheduler change (7ca56638), and passes with the fix.Runner.builder()with a minimalBaseAgent.CheckReturnValuerejects the old ignored subscription and accepts the updated source.git diff --checkpass.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).