Skip to content

[Bug]: A crash inside the reconnect loop stops it for good, and nothing is logged #39418

Closed

Description

@viktorce

Before submitting

  • I searched existing issues and did not find a duplicate.
  • I included enough detail to reproduce or investigate the problem.

Area

apps/web

Steps to reproduce

The app keeps each connection alive with one loop in packages/client-runtime/src/connection/supervisor.ts: try to connect, wait, try again. Web, desktop and mobile share it. If anything in that loop fails in a way nobody planned for, the loop stops and never restarts.

I could not cause that by hand. Both reproductions below inject one fault from the page and leave everything after it to the app. Each is a scenario per docs/operations/scenarios.md.

1. The config stream fails while interrupted

  1. Open a thread in the web client.
  2. Deliver one server frame on the app's WebSocket that ends the subscribeServerConfig stream with a typed failure and an interruption in the same cause.
  3. Wait five seconds, type a message and press Enter.

#39420 carries this as scripts/scenarios/reconnect-survives-config-stream-failing-while-interrupted.e2e.ts.

2. The network-status read throws

  1. Open a thread in the web client.
  2. Close the app's socket from the page, as a network drop would, and make the next read of navigator.onLine throw once.
  3. Wait ten seconds, then press Retry now.

The scenario for this one is in the details block at the end.

Expected behavior

The app reconnects, and the failure is logged.

Actual behavior

The loop is dead and nothing is logged.

In the first reproduction the app shows no sign of it. There is no banner and no error. The message stays in the composer after Enter.

In the second the banner says "is reconnecting" and stays. Retry now does nothing, because no loop is left to hear it.

Why it happens. The loop is forked once, yield* run().pipe(Effect.forkScoped), with nothing around it, and Effect does not log the failure of a forked fiber. Two things reach it:

  • A defect outside the part of an attempt that already catches defects. The network-status read an attempt makes while it waits to be interrupted is one.
  • An interruption that is not a shutdown. exitUnlessInterrupted turns any cause that holds an interruption into an interruption of the loop's own fiber. rpc/session.ts fails a session's closed with whatever cause ended the config subscription, unless that cause holds interruptions only. So a failure mixed with an interruption ends the loop.

How likely it is. I have not seen it happen to a user. No real browser throws from navigator.onLine, and I found no way to make a real server send the frame in the first reproduction. What the code does have is the route in the second bullet above.

#33089 looks similar from the outside. That report says the client sometimes recovers after a long wait. A dead loop never does, so I have no evidence they are the same.

Impact

Minor bug or occasional failure

Version or commit

main at 57db750b8f. The supervisor files are unchanged on 2bba2564ca.

Environment

Web client in Chromium on macOS, against the dev server. Desktop and mobile run the same loop through packages/client-runtime.

Logs or stack traces

$ vp run scenarios:prove scripts/scenarios/reconnect-survives-config-stream-failing-while-interrupted.e2e.ts --base origin/main

base 57db750b8f
  ASSERTION_FAILED: expect.toBeVisible failed
  locator: getByText("The command printed one JSON line.").nth(1)
  observed: no node (match count 0)

$ vp run scenarios:prove scripts/scenarios/reconnect-survives-network-status-defect.e2e.ts --base origin/main

base 57db750b8f
  ASSERTION_FAILED: expect.toBeHidden failed
  locator: getByText("is reconnecting")
  observed: visible (match count 1)

The page's console has no error in either run on main.

Screenshots, recordings, or supporting files

Reproduction 1 on main, three seconds after Enter. No banner, and the message is still in the composer:

Main: no banner, and the message is still in the composer

main on the left, the fix on the right:

real-route-before-after.mp4

Reproduction 2 on main, five seconds after Retry now:

Main: still reconnecting five seconds after Retry now

main on the left, the fix on the right. The red ring is the press on Retry now:

network-status-before-after.mp4

A control run of the second scenario with no injected throw reconnected on main. So the stuck state comes from the thrown read and not from the dropped socket.

Workaround

Reload the page or restart the app.

The scenario for reproduction 2
import { expect } from "e2e";
import * as Effect from "effect/Effect";

import { runPromise, test, WEB } from "./t3.ts";

interface Fault {
  readonly dropConnectionAndFailNextStatusRead: () => void;
  readonly throwsLeft: () => number;
  readonly thrownAt: () => string | null;
  readonly logs: () => ReadonlyArray<string>;
}

// The bug is an app that stays stuck, so the scenario lets real time pass before it looks.
const pause = (seconds: number) => runPromise(Effect.sleep(`${seconds} seconds`));

test(
  "The app reconnects after its network-status read throws during a reconnect",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("demo");
    const thread = await t3.thread({
      project,
      title: "Earlier work",
      messages: ["Print the JSON"],
      model: "command-output",
    });
    // Injected faults: the page can close the app's socket, as a network drop would, and
    // make the next read of navigator.onLine throw. No real browser throws there.
    await browser.addInitScript(() => {
      const sockets: Array<WebSocket> = [];
      const NativeWebSocket = window.WebSocket;
      window.WebSocket = class extends NativeWebSocket {
        constructor(url: string | URL, protocols?: string | Array<string>) {
          super(url, protocols);
          if (protocols !== "vite-hmr" && new URL(String(url), location.href).pathname === "/ws") {
            sockets.push(this);
          }
        }
      };
      let throwsLeft = 0;
      let thrownAt: string | null = null;
      const onLine = Object.getOwnPropertyDescriptor(Navigator.prototype, "onLine")!;
      Object.defineProperty(Navigator.prototype, "onLine", {
        configurable: true,
        get() {
          if (throwsLeft > 0) {
            throwsLeft -= 1;
            const error = new Error("Injected: navigator.onLine threw.");
            thrownAt = error.stack ?? "";
            throw error;
          }
          return onLine.get!.call(this);
        },
      });
      // A ring where the scenario clicks, so the recording shows the press on Retry now.
      document.addEventListener(
        "pointerdown",
        (event) => {
          const ring = document.createElement("div");
          ring.style.cssText = `position:fixed;left:${event.clientX - 20}px;top:${event.clientY - 20}px;width:40px;height:40px;box-sizing:border-box;border:3px solid #ff5252;border-radius:50%;pointer-events:none;z-index:2147483647;transition:opacity 1.5s ease-in 0.5s`;
          document.documentElement.append(ring);
          requestAnimationFrame(() => {
            ring.style.opacity = "0";
          });
          ring.addEventListener("transitionend", () => ring.remove());
        },
        true,
      );
      const logs: Array<string> = [];
      for (const level of ["log", "info", "warn", "error"] as const) {
        const native = console[level].bind(console);
        console[level] = (...parts: Array<unknown>) => {
          logs.push(parts.map(String).join(" "));
          native(...parts);
        };
      }
      (window as unknown as { __fault: Fault }).__fault = {
        dropConnectionAndFailNextStatusRead: () => {
          throwsLeft = 1;
          for (const socket of sockets.splice(0)) socket.close();
        },
        throwsLeft: () => throwsLeft,
        thrownAt: () => thrownAt,
        logs: () => logs,
      };
    });
    await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" });
    await t3.open(thread);

    const reply = screen.getByText("The command printed one JSON line.");
    await expect(reply.first()).toBeVisible();
    await app.screenshot("1-connected");

    await browser.evaluate(() => {
      (window as unknown as { __fault: Fault }).__fault.dropConnectionAndFailNextStatusRead();
      return null;
    });
    // The reconnect banner waits out a 2 s grace period, and a fixed loop retries within 4 s.
    await pause(10);
    await app.screenshot("2-ten-seconds-after-the-drop");

    const retry = screen.getByRole("button", "Retry now");
    if (await retry.isVisible()) {
      await retry.tap();
      await pause(5);
      await app.screenshot("3-after-retry-now");
    }

    const report = await browser.evaluate(() => {
      const fault = (window as unknown as { __fault: Fault }).__fault;
      return {
        injectedThrowUsed: fault.throwsLeft() === 0,
        thrownAt: fault.thrownAt(),
        defectLogs: fault.logs().filter((line) => line.includes("unexpected defect")),
      };
    });
    expect(report.injectedThrowUsed).toBe(true);
    expect(report.thrownAt).toContain("currentNetworkStatus");

    await expect(screen.getByText("is reconnecting", { exact: false })).toBeHidden();
    await screen.getByRole("textbox").fill("Are you still there?");
    await screen.getByRole("textbox").press("Enter");
    await expect(reply.nth(1)).toBeVisible();
    await app.screenshot("4-second-turn-answered");
    expect(report.defectLogs.length).toBeGreaterThan(0);
  },
);

Save it as scripts/scenarios/reconnect-survives-network-status-defect.e2e.ts. It is not part of #39420, because no real browser throws from navigator.onLine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions