This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-8855-65386d38ba114ba7e25b56e6264b04b066def16b
in repository https://gitbox.apache.org/repos/asf/texera.git

commit 27f37b81bf87358c3f8688d3dfbf5b4d92ec40b8
Author: Eugene Gu <[email protected]>
AuthorDate: Tue Oct 27 03:36:59 2026 +0000

    fix(frontend): reconnect the workflow websocket after a clean server-side 
close (#8855)
    
    ### What changes were proposed in this PR?
    
    `WorkflowWebsocketService` only noticed a lost connection through
    `retryWhen`, which reacts to **errors**:
    
    ```ts
    const wsWithReconnect = this.websocket.pipe(
      retryWhen(errors =>
        errors.pipe(
          tap(_ => this.updateConnectionStatus(false)),
          tap(_ => console.log(`websocket connection lost, reconnecting in 3 
seconds`)),
          delayWhen(_ => timer(WS_RECONNECT_INTERVAL_MS)),
          tap(_ => this.send("HeartBeatRequest", {}))
        )
      )
    );
    ```
    
    When the server closes the socket with a close frame, the browser
    reports the close as `wasClean: true`, and rxjs's `WebSocketSubject`
    then **completes** the subject instead of erroring it
    (`WebSocketSubject.js`, `socket.onclose`: `e.wasClean ?
    observer.complete() : observer.error(e)`). A completion passes straight
    through `retryWhen`, so the subscription simply ended:
    
    - `updateConnectionStatus(false)` never ran, so `isConnected` stayed
    `true`: the connection badge stayed green, the run button stayed
    enabled, the kill button stayed enabled mid-run, and the Form View's
    Stop from #7944 stayed enabled;
    - nothing redialed;
    - every later `send()`, including the 10 s heartbeat, went into the
    subject's buffer, which is only flushed on a reconnect that never came,
    so the heartbeat could not expose the dead socket either;
    - `ComputingUnitStatusService` refreshes the unit list only on a
    connection-status change, so that did not happen either.
    
    A server goes away cleanly whenever it is stopped gracefully: a restart
    or redeploy of the service behind `/wsapi` (Jetty sends a 1001 close
    frame on shutdown), or a Kubernetes computing-unit pod being deleted,
    evicted or drained. An unclean close (code 1006, process killed) already
    took the retry path, so only the graceful case was broken.
    
    **The change** adds a `concatWith` immediately before `retryWhen`.
    `concatWith` does nothing while the socket is live; when the socket
    completes after the server has sent something on it, it appends an
    error, so a server-side close now takes the existing retry path: report
    the drop, wait `WS_RECONNECT_INTERVAL_MS`, redial, and deliver the
    buffered requests on the new socket. `closeWebsocket()` unsubscribes the
    chain before completing the subject, so a client-initiated close still
    does not redial, and `openWebsocket()` starts with `closeWebsocket()`,
    so re-opening during the reconnect gap cancels the pending redial.
    
    **A close before the server sent anything is not redialed.** That is how
    the master refuses a session it cannot open:
    `WorkflowWebsocketResource.myOnOpen` reads `wid` and `cuid` before it
    sends anything and throws on a missing or malformed one, which Jetty
    turns into a 1011 close. The admin execution page hits this on every
    Kill, Pause and Resume click, since it opens the socket without `cuid`,
    and redialing would retry every 3 s, one loop per click. So the error is
    appended only if a message arrived on that connection, which is also
    when the service marks itself connected; otherwise the chain completes
    and logs "websocket closed by the server before it sent anything, not
    reconnecting". The flag is created inside a `defer`, so each redial
    starts with its own. On Kubernetes the gateway rejects the admin page's
    handshake with 403 instead, which the browser reports as an unclean 1006
    close, so there it is still retried every 3 s, as before this PR.
    
    Checked against the local master: a missing or non-numeric `wid` or
    `cuid` was closed with 1011 within about 20 ms and nothing sent; a
    nonexistent `wid` or `cuid` was accepted and got messages; a request
    that failed was answered with a `WorkflowErrorEvent` and the socket
    stayed open; a request over the 1 MB payload limit on a live session was
    closed with 1009 after messages, which still redials. The rule assumes
    the server refuses before it sends anything; a server that sent
    something and then refused would still be redialed every 3 s.
    
    `retryWhen` is deprecated in rxjs 7 and is deliberately left untouched
    here; replacing it with `retry({ delay })` is a separate change.
    
    #### Before: the socket is closed, the UI says connected
    
    The black panel is a debugging overlay injected into the page for the
    reproduction (it records every workflow socket created and every close
    event, and reads the badge colour from the DOM); it is not part of
    Texera.
    
    Normal state: one `/wsapi/workflow-websocket` socket is OPEN and the
    badge is green.
    
    <img width="1568" height="562"
    alt="bug2-01-normal-socket-OPEN-badge-green"
    
src="https://github.com/user-attachments/assets/9d8477e2-1040-4a1a-9181-676708cbd96c";
    />
    
    The socket is closed cleanly. Eleven seconds later it is CLOSED, no
    second socket has been created (the reconnect delay is 3 s), the badge
    is still green, and the "websocket connection lost, reconnecting" line
    never appeared.
    
    <img width="1568" height="562"
    alt="bug2-02-clean-close-11s-socket-CLOSED-badge-green-no-redial"
    
src="https://github.com/user-attachments/assets/67d9d633-1470-4ef0-9123-6ac31a6d4479";
    />
    
    34 seconds later, unchanged.
    
    <img width="1568" height="562"
    alt="bug2-03-clean-close-34s-still-CLOSED-still-green-BUG"
    
src="https://github.com/user-attachments/assets/35d8d779-09d5-480e-9b54-6229c659e495";
    />
    
    Toolbar close-up while the socket is closed: the green dot and the
    enabled unit picker.
    
    <img width="1018" height="84"
    alt="bug2-04-toolbar-zoom-green-dot-while-socket-closed"
    
src="https://github.com/user-attachments/assets/3cdcd344-95e7-4c97-a225-71f77542e20d";
    />
    
    
    #### After: the same clean close, on this branch
    
    Same workspace and overlay, served from this branch. Two seconds after
    the clean close the socket is CLOSED and the connection badge has turned
    red; the console shows "websocket connection lost, reconnecting in 3
    seconds".
    
    <img width="1568" height="562"
    alt="fixed-bug2-02-clean-close-2s-socket-CLOSED-badge-RED"
    
src="https://github.com/user-attachments/assets/6242be86-291a-4cd8-814d-a58b1715c4a4";
    />
    
    
    Nine seconds after the close a new socket has been created (the third in
    this session, after two clean closes) and is OPEN, and the badge is
    green again.
    
    <img width="1568" height="562"
    alt="fixed-bug2-03-clean-close-9s-new-socket-OPEN-badge-green-again"
    
src="https://github.com/user-attachments/assets/e988ed1f-902a-454d-a0f9-48c1770e1d78";
    />
    
    The connection badge itself, before the close, 2 s after it, and 7 s
    after it (the dot at the far right):
    
    <img width="980" height="80"
    alt="fixed-bug2-04-toolbar-before-close-green"
    
src="https://github.com/user-attachments/assets/91f66c70-4a4c-49cf-8e83-d6a3c28efa1f";
    />
    
    <img width="980" height="80"
    alt="fixed-bug2-05-toolbar-2s-after-clean-close-RED"
    
src="https://github.com/user-attachments/assets/e6352d2c-0829-41f0-9ccd-431178aabd9d";
    />
    
    
    <img width="980" height="80"
    alt="fixed-bug2-06-toolbar-7s-after-close-reconnected-green"
    
src="https://github.com/user-attachments/assets/7d2bd38e-9204-4d06-8216-84aca4eb90d4";
    />
    
    
    ### Any related issues, documentation, discussions?
    
    Closes #8853
    
    The reproduction closes the socket from the browser; a server-side close
    frame takes the same `wasClean: true` path in rxjs, and the fix redials
    after a clean close of a live session just as after an unclean one.
    
    ### How was this PR tested?
    
    - **New unit tests** in `workflow-websocket.service.spec.ts` (red before
    the fix where noted): a clean server-side close of a connection the
    server had sent on reports the drop and redials after
    `WS_RECONNECT_INTERVAL_MS`, for close codes 1000, 1001, 1005, 1009, 1011
    and 1012 (red); two consecutive clean closes each redial (red); a
    request sent during the reconnect gap is delivered on the redialed
    socket (red); `closeWebsocket()` does not redial; re-opening with
    another unit during the reconnect gap cancels the pending redial and
    opens only the new socket. For refused sessions: a clean close before
    any message does not redial, ends the chain and logs why; a redial the
    server closes before sending anything ends the retries; an unclean
    failure before any message still redials; a message on a connection that
    dropped uncleanly does not count for the redial that replaces it.
    - **Mutation check**, each restored afterwards: deleting the
    `concatWith`, moving it after `retryWhen`, or dropping the unsubscribe
    in `closeWebsocket()` (first commit); ignoring the flag, never setting
    it, sharing one flag across redials, refusing without the log line,
    leaving a refused chain open instead of completing it, or ending the
    retries on an unclean failure before the first message (second commit).
    Each turns named tests red.
    - **Spec file**: 28 passed. **Full frontend suite** (`ng test
    --watch=false`): 231 files, 6457 passed, 1 skipped (pre-existing), 0
    failed. `prettier --check` and `eslint` clean on both files.
    - **Bug reproduced in a running local instance** (screenshots above):
    Chrome against the Angular dev server and the local computing-unit
    master, with a page-level `WebSocket` wrapper to observe socket creation
    and close events. Server-side variant for reviewers: open a workflow
    with a connected unit, stop the computing-unit master gracefully (IDE
    Stop button) and start it again; before this PR the socket closes and
    never reopens while the badge stays green.
    - **Fixed build exercised in the same local instance** (first commit;
    screenshots in the "After" section): four consecutive clean closes, each
    followed by the badge turning red, the "websocket connection lost,
    reconnecting in 3 seconds" console line, a new socket about 3 to 4 s
    later, and the badge turning green once the new socket was up.
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Yes. Generated-by: Claude Code (claude-fable-5-1). Co-authored with
    Claude; the author reviewed the change before submission.
    
    ---------
    
    Co-authored-by: Kunwoo (Chris) <[email protected]>
---
 .../workflow-websocket.service.spec.ts             | 223 +++++++++++++++++++++
 .../workflow-websocket.service.ts                  |  36 +++-
 2 files changed, 256 insertions(+), 3 deletions(-)

diff --git 
a/frontend/src/app/workspace/service/workflow-websocket/workflow-websocket.service.spec.ts
 
b/frontend/src/app/workspace/service/workflow-websocket/workflow-websocket.service.spec.ts
index 30bfe8fe02..e617676790 100644
--- 
a/frontend/src/app/workspace/service/workflow-websocket/workflow-websocket.service.spec.ts
+++ 
b/frontend/src/app/workspace/service/workflow-websocket/workflow-websocket.service.spec.ts
@@ -283,6 +283,229 @@ describe("WorkflowWebsocketService", () => {
       }
     }));
 
+    /** A frame from the server, which is what marks the connection up. */
+    const serverSends = (socket: FakeWebSocket) =>
+      socket.onmessage?.(
+        new MessageEvent("message", { data: JSON.stringify({ type: 
"WorkflowStateEvent", state: "RUNNING" }) })
+      );
+
+    /** A server-side close frame as the browser reports it: already CLOSED, 
wasClean true. */
+    const serverCloses = (socket: FakeWebSocket, code: number) => {
+      socket.readyState = FakeWebSocket.CLOSED;
+      socket.onclose?.(new CloseEvent("close", { wasClean: true, code, reason: 
"" }));
+    };
+
+    /**
+     * Clean close of a connection the server has already sent on, shared by 
the per-close-code tests below;
+     * runs inside the caller's fakeAsync zone.
+     */
+    const expectCleanCloseRedials = (code: number) => {
+      const statuses: boolean[] = [];
+      const statusSubscription = 
service.getConnectionStatusStream().subscribe(value => statuses.push(value));
+
+      try {
+        service.openWebsocket(1, 1, 1);
+        flushMicrotasks();
+        serverSends(openedSockets[0]);
+        expect(statuses).toEqual([false, true]);
+
+        serverCloses(openedSockets[0], code);
+
+        expect(statuses).toEqual([false, true, false]);
+        expect(service.isConnected).toBe(false);
+
+        tick(WS_RECONNECT_INTERVAL_MS - 1);
+        expect(openedSockets.length).toBe(1);
+        tick(1);
+        flushMicrotasks();
+        expect(openedSockets.length).toBe(2);
+      } finally {
+        statusSubscription.unsubscribe();
+        service.closeWebsocket();
+      }
+    };
+
+    // fakeAsync bodies cannot be wrapped by it.each (no ProxyZone), so one it 
per close code.
+    it("a clean server-side close after a message reports the drop and redials 
after WS_RECONNECT_INTERVAL_MS (code 1000)", fakeAsync(() =>
+      expectCleanCloseRedials(1000)));
+    it("a clean server-side close after a message reports the drop and redials 
after WS_RECONNECT_INTERVAL_MS (code 1001)", fakeAsync(() =>
+      expectCleanCloseRedials(1001)));
+    it("a clean server-side close after a message reports the drop and redials 
after WS_RECONNECT_INTERVAL_MS (code 1005)", fakeAsync(() =>
+      expectCleanCloseRedials(1005)));
+    it("a clean server-side close after a message reports the drop and redials 
after WS_RECONNECT_INTERVAL_MS (code 1012)", fakeAsync(() =>
+      expectCleanCloseRedials(1012)));
+    it("a clean server-side close after a message reports the drop and redials 
after WS_RECONNECT_INTERVAL_MS (code 1009)", fakeAsync(() =>
+      expectCleanCloseRedials(1009)));
+    it("a clean server-side close after a message reports the drop and redials 
after WS_RECONNECT_INTERVAL_MS (code 1011)", fakeAsync(() =>
+      expectCleanCloseRedials(1011)));
+
+    it("closeWebsocket() does not redial", fakeAsync(() => {
+      service.openWebsocket(1, 1, 1);
+      flushMicrotasks();
+      // Up first, so the close below would redial if closeWebsocket() left 
the retry chain subscribed.
+      serverSends(openedSockets[0]);
+
+      service.closeWebsocket();
+      tick(WS_RECONNECT_INTERVAL_MS * 5);
+      flushMicrotasks();
+
+      expect(openedSockets.length).toBe(1);
+      expect(openedSockets[0].readyState).toBe(FakeWebSocket.CLOSED);
+    }));
+
+    it("redials after each of two consecutive clean server-side closes", 
fakeAsync(() => {
+      try {
+        service.openWebsocket(1, 1, 1);
+        flushMicrotasks();
+        serverSends(openedSockets[0]);
+        expect(service.isConnected).toBe(true);
+
+        serverCloses(openedSockets[0], 1001);
+        expect(service.isConnected).toBe(false);
+        tick(WS_RECONNECT_INTERVAL_MS);
+        flushMicrotasks();
+        expect(openedSockets.length).toBe(2);
+
+        serverSends(openedSockets[1]);
+        expect(service.isConnected).toBe(true);
+
+        // The redialed chain has to carry the same completion handling as the 
first dial.
+        serverCloses(openedSockets[1], 1001);
+        expect(service.isConnected).toBe(false);
+        tick(WS_RECONNECT_INTERVAL_MS);
+        flushMicrotasks();
+        expect(openedSockets.length).toBe(3);
+      } finally {
+        service.closeWebsocket();
+      }
+    }));
+
+    it("re-opening during the reconnect gap cancels the pending redial", 
fakeAsync(() => {
+      try {
+        service.openWebsocket(1, 1, 1);
+        flushMicrotasks();
+        serverSends(openedSockets[0]);
+        serverCloses(openedSockets[0], 1001);
+        // Re-open halfway through the reconnect delay, before the pending 
redial fires.
+        tick(WS_RECONNECT_INTERVAL_MS / 2);
+
+        service.openWebsocket(1, 1, 2);
+        flushMicrotasks();
+        // Run past the moment the cancelled redial would have fired.
+        tick(WS_RECONNECT_INTERVAL_MS * 2);
+        flushMicrotasks();
+
+        // Only the explicit re-open dials; the cancelled redial never opens a 
cuid=1 socket.
+        expect(openedSockets.length).toBe(2);
+        expect(openedSockets[1].url).toContain("cuid=2");
+      } finally {
+        service.closeWebsocket();
+      }
+    }));
+
+    it("a clean close before any message is a refused session and does not 
redial", fakeAsync(() => {
+      const logSpy = vi.spyOn(console, "log");
+      const statuses: boolean[] = [];
+      const statusSubscription = 
service.getConnectionStatusStream().subscribe(value => statuses.push(value));
+
+      try {
+        service.openWebsocket(1, 1, 1);
+        flushMicrotasks();
+        // How the master closes a session it cannot open, e.g. a handshake 
without cuid.
+        serverCloses(openedSockets[0], 1011);
+
+        tick(WS_RECONNECT_INTERVAL_MS * 5);
+        flushMicrotasks();
+
+        expect(openedSockets.length).toBe(1);
+        // The connection was never up, so no false is published either.
+        expect(statuses).toEqual([false]);
+        expect(service.isConnected).toBe(false);
+        expect(logSpy).toHaveBeenCalledWith("websocket closed by the server 
before it sent anything, not reconnecting");
+        
expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining("reconnecting 
in"));
+        // the retry chain completes instead of staying subscribed
+        expect((service as any).wsWithReconnectSubscription.closed).toBe(true);
+      } finally {
+        statusSubscription.unsubscribe();
+        service.closeWebsocket();
+      }
+    }));
+
+    it("a redial the server closes before sending anything ends the retries", 
fakeAsync(() => {
+      try {
+        service.openWebsocket(1, 1, 1);
+        flushMicrotasks();
+        serverSends(openedSockets[0]);
+        serverCloses(openedSockets[0], 1001);
+        tick(WS_RECONNECT_INTERVAL_MS);
+        flushMicrotasks();
+        expect(openedSockets.length).toBe(2);
+
+        serverCloses(openedSockets[1], 1011);
+        tick(WS_RECONNECT_INTERVAL_MS * 5);
+        flushMicrotasks();
+
+        expect(openedSockets.length).toBe(2);
+        expect(service.isConnected).toBe(false);
+      } finally {
+        service.closeWebsocket();
+      }
+    }));
+
+    it("an unclean failure before any message still redials", fakeAsync(() => {
+      try {
+        service.openWebsocket(1, 1, 1);
+        flushMicrotasks();
+        openedSockets[0].onerror?.(new Event("error"));
+
+        tick(WS_RECONNECT_INTERVAL_MS);
+        flushMicrotasks();
+        expect(openedSockets.length).toBe(2);
+      } finally {
+        service.closeWebsocket();
+      }
+    }));
+
+    it("a message on a connection that dropped uncleanly does not count for 
the redial that replaces it", fakeAsync(() => {
+      try {
+        service.openWebsocket(1, 1, 1);
+        flushMicrotasks();
+        serverSends(openedSockets[0]);
+        openedSockets[0].onerror?.(new Event("error"));
+        tick(WS_RECONNECT_INTERVAL_MS);
+        flushMicrotasks();
+        expect(openedSockets.length).toBe(2);
+
+        // The redial is refused before it receives anything of its own.
+        serverCloses(openedSockets[1], 1011);
+        tick(WS_RECONNECT_INTERVAL_MS * 5);
+        flushMicrotasks();
+
+        expect(openedSockets.length).toBe(2);
+      } finally {
+        service.closeWebsocket();
+      }
+    }));
+
+    it("a request sent during the reconnect gap is delivered once the socket 
redials", fakeAsync(() => {
+      try {
+        service.openWebsocket(1, 1, 1);
+        flushMicrotasks();
+        serverSends(openedSockets[0]);
+        serverCloses(openedSockets[0], 1001);
+
+        service.send("RetryRequest", { workers: ["worker-a"] });
+
+        tick(WS_RECONNECT_INTERVAL_MS);
+        flushMicrotasks(); // the redialed fake socket reaches OPEN on a 
microtask
+
+        expect(openedSockets.length).toBe(2);
+        expect(openedSockets[1].sent).toContain(JSON.stringify({ type: 
"RetryRequest", workers: ["worker-a"] }));
+      } finally {
+        service.closeWebsocket();
+      }
+    }));
+
     it("merges the request payload into the frame it puts on the wire", async 
() => {
       service.openWebsocket(1, 1, 1);
       await Promise.resolve(); // the fake socket reaches OPEN on a microtask
diff --git 
a/frontend/src/app/workspace/service/workflow-websocket/workflow-websocket.service.ts
 
b/frontend/src/app/workspace/service/workflow-websocket/workflow-websocket.service.ts
index 4e52d3fa09..9aba41d253 100644
--- 
a/frontend/src/app/workspace/service/workflow-websocket/workflow-websocket.service.ts
+++ 
b/frontend/src/app/workspace/service/workflow-websocket/workflow-websocket.service.ts
@@ -18,7 +18,18 @@
  */
 
 import { Injectable } from "@angular/core";
-import { BehaviorSubject, interval, Observable, Subject, Subscription, timer } 
from "rxjs";
+import {
+  BehaviorSubject,
+  concatWith,
+  defer,
+  EMPTY,
+  interval,
+  Observable,
+  Subject,
+  Subscription,
+  throwError,
+  timer,
+} from "rxjs";
 import { webSocket, WebSocketSubject } from "rxjs/webSocket";
 import {
   TexeraWebsocketEvent,
@@ -114,9 +125,28 @@ export class WorkflowWebsocketService {
       (isDefined(cuId) ? `&cuid=${cuId}` : "") +
       (AuthService.getAccessToken() !== null ? "&access-token=" + 
AuthService.getAccessToken() : "");
     console.log("websocketUrl", websocketUrl);
-    this.websocket = webSocket<TexeraWebsocketEvent | 
TexeraWebsocketRequest>(websocketUrl);
+    const websocket = webSocket<TexeraWebsocketEvent | 
TexeraWebsocketRequest>(websocketUrl);
+    this.websocket = websocket;
     // setup reconnection logic
-    const wsWithReconnect = this.websocket.pipe(
+    const wsWithReconnect = defer(() => {
+      // one flag per connection; each redial starts over
+      let receivedMessage = false;
+      return websocket.pipe(
+        tap(() => (receivedMessage = true)),
+        // A server-side close with a close frame completes the socket instead 
of erroring. If the
+        // server had sent something, turn the completion into an error so the 
retry below reports the
+        // drop and redials; a close before the server sent anything is a 
refused session and ends here.
+        concatWith(
+          defer(() => {
+            if (receivedMessage) {
+              return throwError(() => new Error("websocket closed by the 
server"));
+            }
+            console.log("websocket closed by the server before it sent 
anything, not reconnecting");
+            return EMPTY;
+          })
+        )
+      );
+    }).pipe(
       retryWhen(errors =>
         errors.pipe(
           tap(_ => this.updateConnectionStatus(false)), // update connection 
status

Reply via email to