Skip to content

feat(computing-unit): surface failed/unhealthy computing units instead of an endless "Connecting" - #7944

Merged
kunwp1 merged 8 commits into
apache:mainfrom
eugenegujing:feat/cu-failure-states
Sep 26, 2026
Merged

kunwp1 merged 8 commits into
apache:mainfrom
eugenegujing:feat/cu-failure-states

Conversation

@eugenegujing

@eugenegujing eugenegujing commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

What changes were proposed in this PR?

When a computing unit becomes unhealthy (the pod is OOM-killed into a crash loop, evicted for disk pressure, stuck on an image pull, or its node becomes unreachable), the UI used to show "Connecting" with a "starting up" tooltip forever because status resolution only looked at pod.status.phase and the frontend did not represent the complete backend status vocabulary.

This PR follows the decisions settled in #7670: mirror Kubernetes for the status vocabulary, expose actionable failure reasons only to authorized viewers, and perform no automatic recovery—users delete and recreate unhealthy units, using the existing termination flow that already handles dead pods.

Because a status the UI refuses to act on is only worth as much as the refusal, the change also closes the paths that ignored it: every run entry point now declines to start work on a unit in a terminal state, and a dropdown row the list already greys out can no longer be selected by clicking it.

Before → after

Before: unhealthy unit → Pending/Connecting forever → no actionable explanation
After:  unhealthy unit → Failed/Unknown + Unit Unavailable → authorized reason in the row tooltip

Before: terminating unit → frontend Pending fallback → Connecting
After:  terminating unit → explicit Terminating state → Shutting Down

Before: run on a dead unit → results cleared, request dropped on a closed socket, no feedback
After:  run on a dead unit → refused with an actionable toast, previous results left on screen

Before: click a greyed-out row → unit selected anyway, and remembered for next time
After:  click a greyed-out row → ignored, as the row's own "Cannot select." tooltip says

Screenshots

Every frame below is the running application with the computing-unit status rewritten in flight, the automated equivalent of the DevTools response-override recipe. The workflow held one operator, so no "Invalid" or "Empty" state could mask the unit state.

Before. An unhealthy pod could only be reported as Pending, so the run button said Connecting for ever and the tooltip claimed the unit was starting up. This one frame is the counterpart to both "after" frames, because every unhealthy or terminating unit used to collapse into this same state.

01-before-connecting

After, an unreachable node. Red badge, a disabled Unit Unavailable run button, and the authorized owner-facing reason on the row tooltip.

02-after-unit-unavailable

After, a unit being deleted. Gold transient-state badge and a disabled Shutting Down, instead of falling through to Pending.

03-after-shutting-down

After, a crash loop caused by an OOM kill. The reason names what happened and what to do about it.

04-after-failed-crashloop-oom

After, the Form View run button with the socket still connected. This is the second entry point, which has its own run-button logic. In this exact state it previously fell through to an enabled Run; it is now a disabled Unavailable.

05-after-form-view-unavailable

A recovered OOM-killed unit stays green and runnable, but the tooltip carries the out-of-memory warning with the restart count:

Screenshot 2026-08-23 at 1 05 13 AM

Status vocabulary and reasons

ComputingUnitState now explicitly represents Running, Pending, Failed, Unknown, and Terminating; truly unrecognized future status strings retain the existing Pending fallback.

The full mapping from observed pod state to status and authorized statusReason is:

Observed pod state Status Authorized statusReason
deletionTimestamp set Terminating —
phase Failed + reason Evicted, message mentions ephemeral/disk Failed "The computing unit was evicted because it ran out of local disk storage. Consider storing less data on the unit's local file system, or recreate it with more storage."
phase Failed + reason Evicted, other Failed "The computing unit was evicted by the cluster (<first sentence of the cluster message, capped at 120 chars>). Consider recreating it."
container waiting ImagePullBackOff / ErrImagePull / InvalidImageName Failed "The computing unit's image could not be pulled. Please recreate the unit or contact an administrator."
container waiting CrashLoopBackOff, last termination OOMKilled Failed "The computing unit keeps crashing because it runs out of memory. Please terminate it and recreate it with a higher memory limit."
container waiting CrashLoopBackOff, other Failed "The computing unit is repeatedly crashing (restarted N times). Please terminate and recreate it, or contact an administrator."
phase Failed, not evicted Failed "The computing unit stopped unexpectedly. Please terminate and recreate it, or contact an administrator."
phase Unknown Unknown "The state of the computing unit cannot be determined (its node may be unreachable)."
phase Pending + PodScheduled=False/Unschedulable condition Pending "The computing unit is waiting for cluster resources to become available."
phase Running + a container's last termination OOMKilled Running "The last run was terminated because the computing unit ran out of memory (restarted N times). Consider recreating the unit with a higher memory limit before running the same workload."
phase Running, healthy Running —
anything else / pod absent / local unit Pending / Running (unchanged) —

Precedence is top-to-bottom; in particular, a CrashLoopBackOff failure wins over the recovered-OOM warning, and Terminating wins over everything.

statusReason visibility is independent of ownership: owners receive it through the regular list and direct lookup, administrators receive it for every row from the dedicated admin-list endpoint without those rows being marked as owned, and ordinary shared users receive null and therefore see generic frontend text.

Frontend fallbacks when statusReason is absent are Running → "Ready to use", Pending → "Computing unit is starting up", Failed/Unknown → "This computing unit is unavailable.", Terminating → "Computing unit is shutting down", and any other value → the status word itself.

Backend

  • The existing single namespace-level pod listing now yields a PodStatusSnapshot per pod (phase, deletion timestamp, pod reason/message, Unschedulable condition, and each container's waiting reason, last termination reason, and restart count) via a pure, unit-testable transform, with no additional Kubernetes round trips.
  • With restartPolicy: Always, an OOM-killed container restarts in place and the pod phase never leaves Running, so OOM kills are detected through containerStatuses[].lastState.terminated.reason; a recovered unit stays Running with a warning, while a unit that cannot recover and enters CrashLoopBackOff is reported as Failed.
  • Vanished-pod reconciliation (refactor(computing-unit-managing-service): share CU listing helpers and batch k8s calls #6853/feat(computing-unit-managing-service): add admin endpoint to list all computing units #6854) remains keyed only on pod presence, so a present but Failed pod is not treated as vanished.
  • local units remain always Running; local liveness remains outside this PR's scope, as settled in What should Texera do when a computing unit dies? #7670.
  • Dashboard-row construction now receives canViewStatusReason separately from isOwner, which lets the admin endpoint expose actionable reasons while preserving truthful ownership and ordinary shared-user suppression.
  • The unused getComputingUnitStatus wrapper was removed, and the two equivalent Running branches were collapsed without changing status precedence or OOM-warning behavior.

Frontend

  • The dashboard DTO status union and the internal ComputingUnitState enum both contain all five states, and the status service maps Terminating explicitly while preserving Pending as the fallback for genuinely unrecognized future values.
  • One shared unavailableComputingUnitReason utility answers whether a unit can never accept work, distinguishing Terminating from Failed/Unknown. Both run buttons and the execution service read the terminal states from it, so the three cannot drift apart.
  • A selected Terminating unit shows a disabled Shutting Down run-button state with a loading icon before WebSocket connectivity is considered; invalid and empty workflow messages retain precedence, Pending still shows Connecting, and Failed/Unknown still show Unit Unavailable.
  • The Form View run button, which is a second entry point with its own state logic, gained the same terminal states in the same relative position, shortened to Shutting Down and Unavailable to match its siblings. Its "connecting" condition now excludes terminal units, which would otherwise have spun there for ever, and its Stop branch is offered only while the socket can actually deliver the kill.
  • Failed/Unknown use a red dropdown badge, while Pending/Terminating use gold because both are transient rather than failed states.
  • No state adds a text suffix next to the unit name; status is conveyed consistently through badge color, row tooltip, and run-button behavior without truncating labels at normal dropdown widths.
  • Each dropdown row has one status-tooltip surface: a Running row shows its status or recovered-OOM warning, while every non-running row appends "Cannot select." without duplicating a trailing period.
  • Row-tooltip composition is now the pure getComputingUnitRowTooltip utility instead of three component methods, and its punctuation/status matrix is tested in the utility spec.
  • The unreferenced .unit-disconnected and .unit-terminating selectors were removed; the live .unit-connecting selector remains bound to Pending rows.
  • statusReason is typed string | null on the DTO, which is what Option[String] through DefaultScalaModule actually puts on the wire; the previous optional-only type could not represent it.

Refusing work a unit cannot do

Naming a terminal state is not enough on its own, because three of the four run entry points never looked at the unit status: run-up-to from the operator menu, the Time Travel replay, and the Form View run button all call ExecuteWorkflowService directly, and only the canvas button was gated, by its disabled state alone. On a terminal unit the old flow reset the execution state, clearing the results already on screen, and then handed the request to a WebSocket that has no delivery check and no error path, so the user silently lost their previous results and no run started.

  • ExecuteWorkflowService gained a guard modelled on the existing warehouse refusal: it is checked at both public entry points, before the warehouse guard and before resetExecutionState(), so a refused click leaves the screen as it was. The unit is checked first because picking a warehouse cannot rescue a dead unit.
  • The guard reads the same shared utility the two run buttons use, so it never refuses a click that either button allows.
  • In the dropdown, a row the list marks unselectable is no longer selectable by clicking it. ng-zorro greys such a row out and calls preventDefault/stopPropagation, but neither cancels the (click) binding on the same <li>, so a click still selected the unit. Since the per-workflow selection is now remembered, that stray selection was also written to storage and restored on every later load, because the recall path only checks that the remembered cuid still exists, never its status. The guard lives in a row-only handler rather than in the shared selection method, which the creation flow also calls with a freshly created and therefore Pending unit.

Any related issues, documentation, discussions?

Closes #7669.

The status vocabulary, reason visibility, and no-auto-recovery policy were discussed in #7670; administrator reason visibility and the review cleanups address feedback on this PR. The run-entry-point guard and the Form View run button address the Copilot review on this PR, which observed that the new states reached only MenuComponent.

How was this PR tested?

  • TDD covers every backend decision-table row with PodBuilder-built pods through the pure snapshot and mapping functions, including both eviction wordings, all three image-pull reasons, crash loops with and without OOM history, crash-loop precedence over recovered OOM, multi-container pods, authorization gating, and the absent-pod path used by creation polling; fabric8 null guards for status, conditions, containerStatuses, state, lastState, and terminated have dedicated coverage.
  • Additional edge cases cover Terminating precedence over eviction and status-less pods, eviction-message truncation/whitespace/case-insensitivity, mixed multi-container pods, stale/malformed Unschedulable conditions, image-pull precedence over crash loops, empty statusReason fallback behavior, and the pinned Succeeded → Pending behavior.
  • The refusal guard is pinned per entry point: a terminating, Failed or Unknown unit is refused, nothing reaches the WebSocket, and the execution state is not reset, so a test fails if the guard is ever moved after the reset. Running and Pending units still run, and a workflow with no unit selected at all still runs and keeps the existing warning.
  • The Form View button is pinned for both terminal labels with the socket up and down, for invalid and empty workflows keeping precedence over a terminal unit, for a terminal unit being named ahead of a missing warehouse, for Pending still saying Connecting, and for Stop being withheld when it could not be delivered.
  • The dropdown row is pinned for a refused click on a Failed, Unknown, Terminating and Pending row, and for a Running row still being selected and remembered; creating a unit, which arrives Pending, is pinned as still being selected.
  • Mutation checks confirmed that swapping precedence, mapping Evicted to Pending, removing wording branches, hardcoding restart counts, bypassing reason authorization, mapping absent pods to Unknown, or removing run-button terminal-state branches causes tests to fail. A further twenty mutations on the shared utility, the refusal guard, the Form View branch, the Stop condition and the row handler were each killed by at least one test, with no survivors.
  • Backend: ComputingUnitManagingService / Test passes 238/238.
  • Frontend: the five affected specs pass 626/626 with NODE_OPTIONS="--no-experimental-webstorage" npx ng test --watch=false --include src/app/common/util/computing-unit.util.spec.ts --include src/app/workspace/service/execute-workflow/execute-workflow.service.spec.ts --include src/app/workspace/component/workflow-form/workflow-form.component.spec.ts --include src/app/workspace/component/menu/menu.component.spec.ts --include src/app/workspace/component/power-button/computing-unit-selection.component.spec.ts. The whole frontend suite is green under the same flag; without it, local Node 25 shadows jsdom's localStorage and the suite is both noisy and non-deterministic, which CI does not hit because it pins Node 24.
  • Type checking passed with tsc --noEmit, Scala and frontend formatting checks passed, scoped frontend ESLint passed, and git diff --check passed.
  • Manual verification in Chrome with response overrides on both computing-unit polling endpoints: switching a unit's status between Running, Pending, Terminating, Failed and Unknown produces the badge colour, row tooltip and run-button state described above. Click path: open a workflow in the workspace, open the computing-unit picker in the toolbar, override the array response for the dropdown rows and the single-unit response for the run button, then observe both within one polling interval.

Option[String] → null serialization relies on DefaultScalaModule registered on the service's Dropwizard ObjectMapper; there is no end-to-end JSON serialization test for the field, though the DTO type now admits null and both consumers treat it as absent.

A bare pod in phase Succeeded still maps to Pending, which is pinned by a test and practically unreachable under restartPolicy: Always.

Follow-ups intentionally outside this PR's scope remain a frontend timeout for the "pod Running but engine unreachable" zombie case, UX for silent vanish reconciliation, and local computing-unit liveness.

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

Co-authored by: Claude Code (Claude Fable 5)

…d of an endless "Connecting"

Add Failed, Unknown, and Terminating to ComputingUnitState, extract a PodStatusSnapshot per pod from the same single namespace-level pod listing as before, and map real pod state (eviction, image-pull failures, crash loops, OOM kills, unschedulable pods, deletion timestamps) to a status plus an owner-only, actionable statusReason on the DTO; shared users receive null and vanish-reconciliation semantics are unchanged.

On the frontend, widen the status union and add statusReason, render Failed/Unknown as a red badge, replace the endless "Connecting" spinner with a disabled "Unit Unavailable" run button for dead units, and make each dropdown row a single reason-aware tooltip surface (removing the nested badge and name-URI tooltips and fixing a doubled period in the ". Cannot select." concatenation).

Closes apache#7669
Remove the last text suffix next to a unit's name in the computing-unit dropdown: a Pending unit already shows the gold badge, the row tooltip explains the state (starting up, or waiting for cluster resources), and the run button shows the "Connecting" spinner for the selected unit, so the suffix was redundant and truncated to "(Co..." at real dropdown widths; status is now uniformly conveyed by badge color plus the row tooltip for every state.
@github-actions github-actions Bot added feature frontend Changes related to the frontend GUI platform Non-amber Scala service paths labels Aug 24, 2026
@github-actions

github-actions Bot commented Aug 24, 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: @mengw15, @Neilk1021, @kunwp1
    You can notify them by mentioning @mengw15, @Neilk1021, @kunwp1 in a comment.

@codecov-commenter

codecov-commenter commented Aug 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.96774% with 14 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.77%. Comparing base (43f2649) to head (1850e96).
⚠️ Report is 33 commits behind head on main.

Files with missing lines Patch % Lines
...che/texera/service/util/ComputingUnitHelpers.scala 87.09% 1 Missing and 7 partials ⚠️
...rvice/resource/ComputingUnitManagingResource.scala 0.00% 3 Missing ⚠️
...apache/texera/service/util/PodStatusSnapshot.scala 92.30% 1 Missing and 2 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #7944      +/-   ##
============================================
- Coverage     92.80%   92.77%   -0.04%     
- Complexity     4898     4924      +26     
============================================
  Files          1239     1243       +4     
  Lines         52254    52545     +291     
  Branches       6425     6498      +73     
============================================
+ Hits          48494    48747     +253     
- Misses         2183     2194      +11     
- Partials       1577     1604      +27     
Flag Coverage Δ *Carryforward flag
access-control-service 77.38% <ø> (+5.59%) ⬆️
agent-service 99.16% <ø> (ø) Carriedforward from 830f261
amber 88.59% <ø> (-0.01%) ⬇️ Carriedforward from 830f261
computing-unit-managing-service 60.41% <86.91%> (+5.21%) ⬆️
config-service 87.37% <ø> (ø)
file-service 81.53% <ø> (ø)
frontend 96.52% <100.00%> (-0.13%) ⬇️
notebook-migration-service 83.73% <ø> (ø)
pyamber 98.48% <ø> (ø) Carriedforward from 830f261
workflow-compiling-service 74.09% <ø> (ø)

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

@eugenegujing

Copy link
Copy Markdown
Contributor Author

/request-review @kunwp1

@github-actions
github-actions Bot requested a review from kunwp1 August 24, 2026 21:22

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

Left some minor comments!

- Map Terminating explicitly and show a disabled Shutting Down run state while preserving the Pending fallback for genuinely unrecognized future statuses.

- Allow the dedicated admin list to expose status reasons without marking other users' units as owned, while keeping regular shared-user endpoints owner-gated.

- Remove the unused status wrapper and dead dropdown state selectors, collapse the equivalent Running branches, and centralize row-tooltip composition in the common utility.

- Add backend authorization coverage and frontend tests for Terminating mapping, WebSocket-independent shutdown behavior, workflow-state precedence, and tooltip punctuation.
# Conflicts:
#	frontend/src/app/workspace/component/menu/menu.component.spec.ts
@eugenegujing

Copy link
Copy Markdown
Contributor Author

@kunwp1 PTAL!

renovate-bot pushed a commit to renovate-bot/apache-_-texera that referenced this pull request Aug 30, 2026
…ds (apache#8101)

### What changes were proposed in this PR?

Extends `computing-unit-selection.component.spec.ts` over the
virtual-environment
block the issue lists — creating an environment, reconciling saved
packages,
installing user packages, streaming pip output, and the unit-rename
handlers —
with 22 tests. Measured locally with `--coverage`:

| `computing-unit-selection.component.ts` | Before | After |
| --- | --- | --- |
| lines | 321/370 (86.76 %) | **363/370 (98.11 %)** |
| statements | 342/393 | **386/393** |
| branches | 136/187 (72.73 %) | **173/187 (92.51 %)** |
| functions | 114/127 | **127/127 (100 %)** |

**`createVirtualEnvironment`** — the duplicate-name guard now fires:
three cards,
one of them nameless so the scan has to survive `(pve.name ??
"").trim()` before
it reaches the clash, and nothing is created.

**`installUserPackages`** — all three paths. A package with a name but
no operator,
and one with no version, each stop at *"Please specify an operator and
version…"*.
A batch with a blank name, a name that collides with a system package
under a
different case (`NumPy` vs `numpy`), and one already installed in the
environment
is filtered down to nothing: both skip notices fire, no socket opens,
and the draft
rows are cleared. A card with no draft rows at all exercises the
optional chain.
A surviving package opens an install socket with the trimmed spec
(`["numpy==1.26.0"]`) and, on `__DONE__`, reloads the package list.

**`applySavedPveAsUpdate`** — the `?? ""` fallbacks on both sides of the
version
comparison: a card package with no version against a blank database
version (no
diff), against a pinned one (replaced), and one the database no longer
lists
(deleted with an empty version). The `db.version ?? ""` side is only
reachable by
calling the method directly, since `parseDbPackages` always produces a
string; that
test says so.

**Also covered:** `parseDbPackages` with a null spec; `getPVEs` with a
system
package carrying no `==`; `togglePackageDelete` on a versionless
package;
`updatePrettyPipOutput` and both socket handlers starting from a card
with no
output; `refreshUserPackages` on success and on failure;
`deleteUserPackages`
draining its queue one package at a time and logging a failure without
stopping;
`confirmUpdateUnitName` for a unit that is neither listed nor selected;
`startEditingUnitName` focusing and selecting the rename box once it is
in the
document; the metadata subscription's unsaved-workflow and
no-running-unit arms;
and `onClickOpenShareAccess`.

**What is left, and why.** Seven lines and fourteen branch arms remain:

- 537-549, 569, 573 — the resource-formatting getters, which the issue
puts out of
  scope (apache#6745 proposed exactly those and was closed as not planned).
- 998 — `(pkg.version ?? "").trim()` inside the install `map`. The guard
above it
rejects any package whose trimmed version is empty, so nothing reaching
the map
  can have a nullish version.
- 1064, 1074 — `this.pves[index].pipOutput ?? ""` in the delete
callbacks. Line 1043
  always seeds `pipOutput` with a string before the first callback runs.
- **1000-1004 is dead code.** `skippedMessages` is declared at 978, read
at 1000 and
1001, and never written to anywhere in the repository — the skip notices
go through
`notificationService.error` at 987 and 992 instead.
`skippedMessages.length > 0` is
therefore always false. Left in place here since this PR changes no
production code;
  it is worth removing separately.

No production code was changed.

### Any related issues, documentation, discussions?

Closes apache#8100.

apache#7752 and apache#7944 also touch this spec; the three sets of additions land
in different
places in the file, so whichever merges second is a mechanical rebase.

### How was this PR tested?

`ng test --watch=false --include
src/app/workspace/component/power-button/computing-unit-selection.component.spec.ts`
— 131 passed (109 before, 22 new), repeated 3× for stability. `yarn
format:ci` clean.
Failure path verified by breaking one assertion in each of the 22 new
tests: 22
failed / 109 passed, non-zero exit, no pre-existing test disturbed, then
restored to
green.

Determinism: the block's existing `FakeSocket` double is reused and its
`onmessage` / `onerror` are invoked by hand, so no connection is opened
and no timer
is waited on; every service call resolves through `of(...)` /
`throwError(...)`;
environment and package fixtures are rebuilt per test because these
handlers mutate
them in place; and the two tests that need a timer use
`vi.useFakeTimers()` with a
`finally` that restores the real clock.

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

Generated-by: Claude Code (Opus 4.8 [1M context])
@kunwp1
kunwp1 requested a balanced review from Copilot September 22, 2026 06:12

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 was unable to review this pull request because the user who requested the review has reached their quota limit.

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

🟡 Changes recommended

Terminal-state handling, DTO nullability, tooltip punctuation, and required UI evidence remain unresolved.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 2 Medium severity · 1 Low severity

Open (3)

…ccept work

- Add a shared unavailableComputingUnitReason helper that maps Terminating to "terminating" and Failed or Unknown to "unavailable". The canvas run button, the Form View run button and the new run guard all read it, so they share one definition of a terminal unit. The canvas button's labels, icons and order are unchanged.

- Refuse to start a run on a terminal unit in ExecuteWorkflowService, checked at both public entry points before the warehouse check and before the execution state is reset. Run-up-to and the Time Travel replay called the service directly without looking at the unit, so a run on a dead unit cleared the results on screen and was then dropped on a closed socket with no feedback.

- Give the Form View run button the terminal states the canvas already had, with shorter labels, and stop it from counting a terminal unit as connecting. Stop is offered only while the socket can deliver the kill, which also covers a unit that disappears from the list mid-run.

- Ignore clicks on dropdown rows the list marks unselectable. nzDisabled only greys the row out, so a click still selected the unit and saved it for later loads. The check lives in a row-only handler because creating a unit selects the new, Pending unit through the shared method.

- Type statusReason as string | null, which is what the backend sends to viewers without access.

- Add tests for both run entry points, both run buttons, the dropdown row and a null status reason.
@eugenegujing
eugenegujing requested a review from kunwp1 September 25, 2026 00:50

@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!

Form View now shows Stop only while the socket is connected. If the unit dies mid-run, the button shows Unavailable, Shutting Down or Computing Unit instead of staying on a disabled Stop.
@kunwp1
kunwp1 added this pull request to the merge queue Sep 26, 2026
Merged via the queue into apache:main with commit 33bd07b Sep 26, 2026
34 checks passed
renovate-bot pushed a commit to renovate-bot/apache-_-texera that referenced this pull request Oct 27, 2026
… failed request (apache#8854)

### What changes were proposed in this PR?

`ComputingUnitStatusService` keeps the computing-unit list and the
selected unit's status fresh through two RxJS pipelines: the list
refresh (`refreshComputingUnitListSignal → switchMap(listComputingUnits)
→ subscribe`) and the selected-unit poll (`interval(2000) →
switchMap(getComputingUnit) → subscribe`). Neither inner HTTP observable
had any error handling. In RxJS an error is a terminal notification:
`switchMap` forwards an inner error downstream unchanged, and a
subscriber that receives it is closed for good. Both subscriptions are
created once, in the constructor of this root-provided service, and
nothing ever re-creates them.

So a single failed request (a 500, a 502/504 from the proxy while the
computing-unit managing service restarts, a network blip) killed the
pipeline for the rest of the page's life. The refresh signal kept being
pushed every second by the dashboard, into a `Subject` with no
subscriber left. The only trace was one `ERROR HttpErrorResponse` in the
console; the UI showed nothing.

What users saw until they reloaded the page:

- the dashboard's Computing Units list froze: units created elsewhere
never appeared, terminated ones never disappeared;
- the workspace's computing-unit dropdown stopped refreshing;
- the selected unit's status never changed again, so the Failed /
Terminating states from apache#7944 could not reach the UI;
- the canvas run button could stay on "Connecting" after the socket was
actually up, because its state is recomputed on poll emissions.

**The change** wraps the inner HTTP observable of both `switchMap`s in
`catchError(this.swallowFetchError(...))`. The helper completes the
failed fetch without emitting, which `switchMap` treats as "this round
is over, wait for the next signal"; the stream stays subscribed and the
next refresh signal or poll tick fetches again. Completing with `EMPTY`
rather than an empty list keeps the cached list and the selected unit
untouched during the failed round, so nothing flickers.

The helper distinguishes two kinds of failure. An `HttpErrorResponse`,
which is what `HttpClient` delivers for every transport-level failure
(non-2xx status, dropped connection, timeout, unparsable body) and what
both app interceptors rethrow, is dropped without logging: it is
expected while the backend is unavailable, it would otherwise print once
a second during a restart, and the failed requests remain visible in the
browser's Network panel. Anything else, for example an exception thrown
inside the managing service's `map(parseDashboardUnit)` step, is a bug
rather than an environment condition, so it is written to
`console.error` with the pipeline name before being dropped. Before this
PR such a bug surfaced once as an uncaught error and then froze the
page; now it is reported on every tick and the page keeps working.

#### Before: one failed request freezes the dashboard

The black panel in the top-right corner is a debugging overlay injected
into the page for the reproduction (it counts `GET api/computing-unit`
requests and can make exactly one of them fail); it is not part of
Texera.

Normal state: the dashboard requests the list once a second.

<img width="1568" height="562"
alt="bug1-01-normal-list-refreshing-every-second"
src="https://github.com/user-attachments/assets/ab652efb-eebe-47a2-9d25-d136733275eb"
/>


One request is made to fail. Eight seconds later no further request has
been sent, although the page still asks for a refresh every second.

<img width="1568" height="562"
alt="bug1-02-one-injected-failure-no-requests-for-8s"
src="https://github.com/user-attachments/assets/9ae568da-292c-405f-b419-f8fc2fa9ae04"
/>

From a second tab, a computing unit is terminated; that tab shows one
unit immediately.

<img width="1568" height="562"
alt="bug1-03-other-tab-unit-4-removed-shows-1-unit"
src="https://github.com/user-attachments/assets/dececa82-2f90-4131-a933-d80b0b42e33c"
/>

87 seconds after the failure the first tab still shows two units and has
sent no request. Reloading the page restores the list at once, so the
backend was healthy the whole time.

<img width="1568" height="562"
alt="bug1-04-this-tab-frozen-87s-still-shows-2-units-BUG"
src="https://github.com/user-attachments/assets/fe9b6f68-f54e-4ab0-baf0-ae208a41d56b"
/>

#### After: the same failure, on this branch

Same page, same overlay, served from this branch. One request (45) is
made to fail; eight seconds later eight more requests have gone out and
the list is still refreshing.

<img width="1568" height="562"
alt="fixed-bug1-02-one-injected-failure-requests-keep-flowing-8-since"
src="https://github.com/user-attachments/assets/d9c8efe1-f014-488f-abfe-8f02027002da"
/>

A unit created from a second tab appears on this page within a second
(78 requests since the failure), and disappears again when it is
terminated from the other tab (138 requests since the failure), all
without a reload.

<img width="1568" height="562"
alt="fixed-bug1-03-unit-created-in-other-tab-appears-here"
src="https://github.com/user-attachments/assets/775fc80e-7b3e-487c-8fab-8df660d4fbcd"
/>

<img width="1568" height="562"
alt="fixed-bug1-04-unit-removed-in-other-tab-disappears-here-138-since-fail"
src="https://github.com/user-attachments/assets/4dd8495c-fc35-40c3-9a67-c4d9ca899d6a"
/>

### Any related issues, documentation, discussions?

Closes apache#8850

Related follow-ups that depend on this fix landing first (not part of
this PR): a selected unit whose pod vanishes polls back to Pending
forever, and dropdown rows do not refresh while the dropdown is open.
Both of their fixes call `refreshComputingUnitList()`, which only works
if this pipeline is alive.

### How was this PR tested?

- **New unit tests** in `computing-unit-status.service.spec.ts`, four in
total, all red before the fix. Failures are modelled as
`HttpErrorResponse` (status 500), which is what `HttpClient` delivers.
`keeps refreshing the list through failed fetches` sends two failures
then a success and asserts three fetches, no list emission for a
failure, and the good list on the next success. `keeps polling the
selected unit through a failed fetch` asserts that after a failed tick
the selected unit object is untouched, the poll subscription is still
open and `stopPollingSelectedUnit` was not called, and that the
following four ticks all fetch and the next good result replaces the
selection. `logs a non-HTTP list failure ...` and `logs a non-HTTP poll
failure ...` feed a `TypeError`, then an `HttpErrorResponse`, then a
success, and assert `console.error` is called exactly once, with the
pipeline name and the `TypeError`, while the stream keeps going.
- **Mutation check**, each mutation restored afterwards: removing the
`catchError` from either pipeline, dropping the `instanceof
HttpErrorResponse` check, or swapping the two pipeline labels each turns
exactly the two tests for that pipeline or branch red. Replacing `EMPTY`
with `of(null)` is a compile error, because the helper is typed
`Observable<never>`; with the type loosened to let it compile, it turns
three tests red, the two survival tests through their emission-count and
selection assertions and the poll logging test.
- **Spec file**: 34 passed. **Full frontend suite** (`ng test
--watch=false`): 231 files, 6447 passed, 1 skipped (pre-existing), 0
failed. `prettier --check` clean on both files.
- **Bug reproduced in a running local instance** (screenshots above):
Chrome against the Angular dev server and the local computing-unit
managing service, with a page-level `XMLHttpRequest` wrapper that fails
exactly one list request. Reproducible without instrumentation by
stopping the computing-unit managing service for a few seconds while the
dashboard's Compute page is open, starting it again, and changing a unit
from another tab.
- **Fixed build exercised in the same local instance** (screenshots in
the "After" section): after one injected failure the request counter
kept increasing once a second (138 requests over the following two
minutes), a unit created from another tab appeared within a second, and
the same unit disappeared within a second after being terminated from
the other tab. No reload. The logging branch does not change what the
page does, so those screenshots still apply.

### 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]>
renovate-bot pushed a commit to renovate-bot/apache-_-texera that referenced this pull request Oct 27, 2026
…side close (apache#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 apache#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 apache#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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature frontend Changes related to the frontend GUI platform Non-amber Scala service paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Surface failed/unhealthy computing units instead of showing "Connecting" indefinitely

4 participants