Skip to content

fix(frontend): reconnect the workflow websocket after a clean server-side close - #8855

Merged
kunwp1 merged 3 commits into
apache:mainfrom
eugenegujing:fix/websocket-clean-close-reconnect
Oct 27, 2026
Merged

kunwp1 merged 3 commits into
apache:mainfrom
eugenegujing:fix/websocket-clean-close-reconnect

Conversation

@eugenegujing

@eugenegujing eugenegujing commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What changes were proposed in this PR?

WorkflowWebsocketService only noticed a lost connection through retryWhen, which reacts to errors:

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 feat(computing-unit): surface failed/unhealthy computing units instead of an endless "Connecting" #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.

bug2-01-normal-socket-OPEN-badge-green

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.

bug2-02-clean-close-11s-socket-CLOSED-badge-green-no-redial

34 seconds later, unchanged.

bug2-03-clean-close-34s-still-CLOSED-still-green-BUG

Toolbar close-up while the socket is closed: the green dot and the enabled unit picker.

bug2-04-toolbar-zoom-green-dot-while-socket-closed

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".

fixed-bug2-02-clean-close-2s-socket-CLOSED-badge-RED

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.

fixed-bug2-03-clean-close-9s-new-socket-OPEN-badge-green-again

The connection badge itself, before the close, 2 s after it, and 7 s after it (the dot at the far right):

fixed-bug2-04-toolbar-before-close-green fixed-bug2-05-toolbar-2s-after-clean-close-RED fixed-bug2-06-toolbar-7s-after-close-reconnected-green

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.

…side close

Add concatWith(throwError(...)) before retryWhen in WorkflowWebsocketService, so the completion rxjs emits on a clean server-side close goes through the existing retry path (report the drop, wait, redial) instead of ending the subscription.

Add spec tests for clean closes (several close codes, before and after the first message, twice in a row), a request sent during the reconnect gap, and the client-initiated close and re-open paths.
@github-actions github-actions Bot added fix frontend Changes related to the frontend GUI labels Oct 5, 2026
@Yicong-Huang Yicong-Huang added the release/v1.3 back porting to release/v1.3 label Oct 5, 2026
@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Automated Reviewer Suggestions

Based on the git blame history of the changed files, we recommend the following reviewers:

  • Contributors with relevant context: @aglinxinyuan, @kunwp1
    You can notify them by mentioning @aglinxinyuan, @kunwp1 in a comment.

@Yicong-Huang Yicong-Huang added the release/v1.2 back porting to release/v1.2 label Oct 5, 2026
@github-actions
github-actions Bot requested review from mengw15 and xuang7 October 5, 2026 08:40
@github-actions

github-actions Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Backport auto-label report

This fix: PR was checked against each actively-supported release branch. A release/* label nominates a backport target; the branch's release manager approving this PR is what sends the fix there. The required Backport Approvals check stays red until every label below is approved, so each manager either approves or removes their own label — which is why the labels left on a merged PR are exactly the branches it reached.

Release branch Analysis
✅ release/v1.3 Already labeled — this fix is queued to backport here. @mengw15 decides: approving sends the fix here, removing this label declines it. The merge waits on one or the other.
✅ release/v1.2 Already labeled — this fix is queued to backport here. @xuang7 decides: approving sends the fix here, removing this label declines it. The merge waits on one or the other.

Auto-label run.

@eugenegujing

Copy link
Copy Markdown
Contributor Author

/request-review @kunwp1

Copilot AI 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.

Copilot review overview

🟢 Approval recommended

No unresolved blocking issues were identified.

Review effort: Lite
Findings: None

What changed in this PR

Fixes workflow WebSocket reconnection after clean server-side closes.

Changes:

  • Converts clean WebSocket completion into a retryable error.
  • Adds tests for reconnects, cancellation, repeated closes, and buffered requests.
File Description
frontend/​src/​app/​workspace/​service/​workflow-websocket/​workflow-websocket.service.ts Handles clean socket completion through existing retry logic.
frontend/​src/​app/​workspace/​service/​workflow-websocket/​workflow-websocket.service.spec.ts Adds comprehensive reconnection and lifecycle tests.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

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

LGTM!

A clean close now redials only if the server had sent something on that connection, so a socket the master refuses on open, such as the one the admin execution page opens without a cuid, makes a single attempt instead of redialing every 3 s.

The waits in "re-opening during the reconnect gap cancels the pending redial" are now half and twice WS_RECONNECT_INTERVAL_MS instead of the literal 1000 ms and 5000 ms.
@codecov-commenter

codecov-commenter commented Oct 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.56%. Comparing base (bc4f3c8) to head (de5f4f3).

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #8855      +/-   ##
============================================
+ Coverage     91.95%   92.56%   +0.61%     
+ Complexity     5081     5074       -7     
============================================
  Files          1280     1283       +3     
  Lines         55622    63127    +7505     
  Branches       7048     8829    +1781     
============================================
+ Hits          51147    58436    +7289     
- Misses         2733     2873     +140     
- Partials       1742     1818      +76     
Flag Coverage Δ *Carryforward flag
access-control-service 77.44% <ø> (ø) Carriedforward from d70fc72
agent-service 99.16% <ø> (ø) Carriedforward from d70fc72
amber 85.89% <ø> (-0.48%) ⬇️ Carriedforward from d70fc72
computing-unit-managing-service 61.71% <ø> (-0.10%) ⬇️ Carriedforward from d70fc72
config-service 87.50% <ø> (ø) Carriedforward from d70fc72
file-service 82.29% <ø> (ø) Carriedforward from d70fc72
frontend 96.92% <100.00%> (+0.40%) ⬆️
notebook-migration-service 83.77% <ø> (ø) Carriedforward from d70fc72
pyamber 98.54% <ø> (ø) Carriedforward from d70fc72
workflow-compiling-service 74.25% <ø> (ø) Carriedforward from d70fc72

*This pull request uses carry forward flags. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@kunwp1

kunwp1 commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

@eugenegujing I already approved the PR. Please ask one of the release managers for the approval.

@kunwp1
kunwp1 enabled auto-merge October 27, 2026 02:56
@kunwp1

kunwp1 commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

This PR is blocked by @xuang7. @mengw15 Should we remove the release labels?

@xuang7 xuang7 removed the release/v1.2 back porting to release/v1.2 label Oct 27, 2026
@xuang7

xuang7 commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

Removing the release/v1.2 label since this is a long-standing issue with a page-reload workaround, and the change alters reconnect semantics.

@kunwp1
kunwp1 added this pull request to the merge queue Oct 27, 2026
Merged via the queue into apache:main with commit 27f37b8 Oct 27, 2026
56 of 64 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

Backport PR opened: draft #9165 (#9165) to release/v1.3, assigned to @eugenegujing — needs manual work because the backported tree failed its pre-merge build.

mengw15 pushed a commit to PG1204/texera that referenced this pull request Oct 29, 2026
…erver-side close (apache#9165)

### What changes were proposed in this PR?

Automated backport of apache#8855 to `release/v1.3`.

Source: 27f37b8 · [automation
run](https://github.com/apache/texera/actions/runs/40448223973)

### Any related issues, documentation, discussions?

Backport of apache#8855. Originally linked apache#8853.

### How was this PR tested?

Release-branch CI runs on this branch once the build is fixed and this
PR is marked ready for review.

### Was this PR authored or co-authored using generative AI tooling?

No.

Co-authored-by: Eugene Gu <[email protected]>
Co-authored-by: Kunwoo (Chris) <[email protected]>
github-merge-queue Bot pushed a commit that referenced this pull request Nov 16, 2026
### What changes were proposed in this PR?

**Root cause.** The frontend learns that a run has ended only from the
engine, over the selected unit's websocket. When the selected unit is
terminated from the unit dropdown, drops out of the unit list, or stays
selected but reports Failed, as an evicted or crash-looping Kubernetes
unit does, that message can never arrive and nothing resets the
execution state, so the run keeps being reported as running. On top of
that, the Kill button's gate exempted `NoComputingUnit` from its socket
check, so Kill stayed enabled although its request could no longer be
delivered. #3400 (a910bcf) added the socket check to Kill together
with that exemption, copying the Run button's translation of the old
single-mode flag `!environment.computingUnitManagerEnabled`; that mode
no longer exists.

```
Before:  unit terminated mid-run -> no end-of-run message -> state stays Running: clock counts, Form View says "Running", Kill enabled but dead
After:   unit terminated mid-run -> socket down, selection drops to none -> run reset: clock stopped, Form View idle, Kill disabled; console and results kept
```

Both screenshots: a run was in flight on "Analytics Unit", which was
then terminated from the unit dropdown.

| Before | After |
| --- | --- |
| <img width="1512" height="805"
alt="kill-button-2-after-terminate-kill-still-enabled"
src="https://github.com/user-attachments/assets/e0919b87-0c2b-4138-a30b-12295b749175"
/> | <img width="1456" height="829"
alt="kill-button-4-after-fix-terminated-kill-disabled-canvas-relocked"
src="https://github.com/user-attachments/assets/729eb0df-d01a-4e4c-90e4-e2c4ac684398"
/> |
| Kill is still enabled, and clicking it does nothing; the clock keeps
counting. | Kill is greyed out; the clock is back at 0:00:00. The info
message comes from the separate check described under "Scope boundary".
|

Form View after the same steps no longer reports a run:

<img width="1456" height="829"
alt="kill-button-6-after-fix-form-view-not-running"
src="https://github.com/user-attachments/assets/bd68cdd3-161c-4479-a2c2-889a74b5d2d8"
/>


**Changes.**

1. `ExecuteWorkflowService` calls its existing
`resetExecutionAndWorkers()` when an execution is in flight, the
workflow websocket is down, and the selected unit is either gone or
reports Failed. It combines the selected-unit stream with the
websocket's connection-status stream, so the reset fires on whichever of
the two happens last. That puts the execution back to Uninitialized,
which Form View and the canvas lock already follow, clears the worker
ids and stops the clock. It is the narrower of the two existing resets:
console messages and results stay, unlike the `connectionReset` path a
manual unit switch takes.
2. The Kill button is disabled whenever the websocket is down, without
the `NoComputingUnit` exemption. This is defense in depth: with change
1, a run that is still in flight with no unit and no socket should not
occur any more, and if it does, Kill no longer looks usable.
3. `isExecutionInFlight` takes the state and `updateWorkflowActionLock`
calls it, so the reset and the canvas lock share one list of in-flight
states.

What does and does not trigger the reset in change 1:

| Situation | Selected unit | Socket | Reset by this check |
| --- | --- | --- | --- |
| Unit terminated from the dropdown | gone | down | yes |
| Kubernetes unit evicted or crash-looping | still selected, Failed |
down | yes |
| Another tab disconnects a local unit | gone | still up | no: the
shared engine is still running it and Kill still works over this tab's
socket; yes once that socket drops |
| Socket drops and reconnects on a healthy unit | Running | down, then
up | no |
| Direct switch from one unit to another | the new unit | down, then up
| no; the existing `connectionReset` path handles the switch |
| Unit reports Pending, Unknown or Terminating | still selected | down |
no |

**Scope boundary.** The canvas can be locked again right away by a
second, independent check, which this PR leaves unchanged. Whenever the
selected unit changes, including when it drops to none,
`ComputingUnitSelectionComponent.updateWorkflowModificationStatus` asks
the database for Running or Initializing executions of the workflow. If
it finds any, it disables modification and shows "There are ongoing
executions on this workflow. Modification of the workflow is currently
disabled." At that moment the lost unit's execution row is still
RUNNING, because disconnecting a local unit does not stop the shared
engine, which keeps running the execution. The lock is accurate, and the
check passes again on the first reload or unit selection after that
execution finishes.

Also not changed here: on a dropdown terminate, the existing
`clearStatus()` call in
`ComputingUnitStatusService.terminateComputingUnit` resets the
operators' colors, while their port row counts keep the last values.
When the unit is lost any other way, for example an evicted unit that
reports Failed or a terminate from another tab, nothing resets the
colors, so the operators keep their last state after the reset.

Not covered: a unit that is lost without reporting Failed or leaving
this tab's unit list. A unit whose pod state cannot be determined
reports Unknown, and a pod deleted outside Texera is polled as Pending
until this tab next refreshes its unit list; in both the run keeps
showing as running.

### Any related issues, documentation, discussions?

Closes #8934

Related:

- #8618: a stuck non-terminal execution row keeps its unit off the idle
sweep.
- #8853, fixed by #8855: a clean websocket close never marks the socket
disconnected; the Kill gate and the reset both rely on `isConnected`
being accurate.

### How was this PR tested?

New tests in
`frontend/src/app/workspace/service/execute-workflow/execute-workflow.service.spec.ts`:

- keeps the run when the socket drops on a healthy unit, then ends it
once the selection empties
- keeps the run when the selection empties with the socket still up,
then ends it once the socket drops
- ends the run when the selected unit reports Failed with the socket
down
- keeps the run when the selected unit reports Failed with the socket
still up
- ends a later run as well when its unit is lost too
- ends a run that is Initializing, Running, Pausing, Paused, Resuming or
Recovering when its unit is lost, one case per state
- leaves a run that is Uninitialized, Completed, Terminated, Failed or
Killed untouched when its unit is lost, one case per state
- keeps the run with the socket down when switching straight from one
unit to another, when a unit is first selected, and when the selected
unit is still Running or reports Pending, Unknown or Terminating, one
case each

New tests in
`frontend/src/app/workspace/component/menu/menu.component.spec.ts`, one
table for the Kill button:

| Execution | Unit status | Socket | Kill |
| --- | --- | --- | --- |
| Running | No Computing Unit | down | disabled |
| Running | No Computing Unit | up | enabled |
| Running | Running | down | disabled |
| Running | Running | up | enabled |
| Completed | Running | down | disabled |
| Completed | Running | up | disabled |

The shared `beforeEach` of the service spec now installs a
`BehaviorSubject` for the selected-unit stream and one for the
connection-status stream before the service is constructed, since the
service subscribes in its constructor. Form View needs no test of its
own: it reads `isRunning` from the execution state stream that
`resetExecutionAndWorkers()` already broadcasts.
`ExecuteWorkflowService` does not inject the console or result services,
so this change cannot clear them.

```
cd frontend
npx ng test --watch=false --include src/app/workspace/service/execute-workflow/execute-workflow.service.spec.ts
# 79 passed
npx ng test --watch=false --include src/app/workspace/component/menu/menu.component.spec.ts
# 150 passed
npx ng test --watch=false
# 253 files, 7206 passed | 1 skipped
npx tsc --noEmit -p tsconfig.json               # clean
npx eslint <changed files>                      # clean
npx prettier --check <changed files>            # clean
```

Mutation check: each of these makes at least one test fail: restoring
the `NoComputingUnit` exemption, dropping the socket condition, dropping
the Failed condition, dropping the empty-selection condition, resetting
regardless of the execution state, resetting on any non-Running unit
status, reading the socket state only when the selection changes,
reading the selection only when the socket state changes, using
`resetExecutionState()` instead of `resetExecutionAndWorkers()`, a reset
that forgets to clear the worker ids, letting only the first lost unit
reset, moving any one of the eleven states across the in-flight split,
and swapping the enable and disable branches of the canvas lock.

Manual check in Chrome, 1512x861 viewport, against a build of this
branch on the local-dev stack with local computing units:

1. Workflow: Text Input -> Python UDF whose `process_tuple` does
`time.sleep(900)`.
2. Select a unit and a warehouse, click Run, and wait until the UDF
operator is running.
3. Open the unit dropdown, click the trash icon of the selected unit,
confirm "Disconnect", then click Kill.
4. Before: Kill stays enabled and does nothing; the clock keeps
counting; Form View keeps saying "Running"; operators cannot be moved.
After: the execution is back to Uninitialized, the clock reads 0:00:00,
Kill is disabled, and Form View no longer reports a run; console and
results stay. The canvas is locked again right away with the info
message quoted under "Scope boundary", because the shared local engine
is still running the execution.

### Was this PR authored or co-authored using generative AI tooling?

Yes. Generated-by: Claude Code (claude-fable-5-1, claude-fable-5-2,
claude-opus-5-5). Co-authored with Claude; the author reviewed the
change before submission.

---------

Co-authored-by: Kunwoo (Chris) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fix frontend Changes related to the frontend GUI release/v1.3 back porting to release/v1.3

Projects

None yet

Development

Successfully merging this pull request may close these issues.

a clean server-side websocket close leaves the workspace marked connected and never reconnects

7 participants