Skip to content

A crash inside the reconnect loop stops it for good, and nothing is logged #16

Closed

Description

@viktorce

The app keeps its connection to the server alive with a loop: try to connect, wait, try again.

The problem. If anything inside that loop fails in a way nobody planned for, the loop stops and never restarts. Nothing is logged. The app stays on "connecting", and pressing Retry does nothing, because there is no loop left to hear it.

Proof. A test on main makes the platform's network-status read throw once during a connection attempt. Twenty simulated minutes and one explicit retry later:

× keeps reconnecting after an unexpected error inside the loop
AssertionError: expected 'connecting' to be 'connected'
state: phase=connecting stage=preparing attempt=1 sessions=0

The thrown error's text appears nowhere in the test output.

How likely it is. We know of no real trigger today. Failures while connecting are already caught and retried. The gap is everything else the loop touches, such as the network-status read used in the test.

Why there is no recording. It needs an internal error we can't cause from the app.

What to do. Where the loop is started (yield* run().pipe(Effect.forkScoped) in supervisor.ts), catch an unexpected failure, log its cause, and start the loop again.

The failing test
  it.effect("keeps reconnecting after an unexpected error inside the loop", () =>
    Effect.gen(function* () {
      const harness = yield* makeHarness({
        prepare: (attempt) =>
          attempt === 1
            ? Effect.sleep("5 seconds").pipe(Effect.as(PREPARED_CONNECTION))
            : Effect.succeed(PREPARED_CONNECTION),
      });
      const reads = yield* Ref.make(0);
      const flaky = Connectivity.Connectivity.of({
        status: Ref.updateAndGet(reads, (count) => count + 1).pipe(
          Effect.flatMap((count) =>
            count === 1
              ? Effect.succeed("online" as const)
              : Effect.die(new Error("platform connectivity threw")),
          ),
        ),
        changes: Stream.never,
      });
      const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
        initiallyDesired: true,
      }).pipe(
        Effect.provideService(Connectivity.Connectivity, flaky),
        Effect.provide(harness.dependencies),
      );
      yield* TestClock.adjust("10 minutes");
      yield* supervisor.retryNow;
      yield* TestClock.adjust("10 minutes");
      const state = yield* SubscriptionRef.get(supervisor.state);
      expect(state.phase).toBe("connected");
    }).pipe(Effect.provide(TestClock.layer())),
  );

Add it to packages/client-runtime/src/connection/supervisor.test.ts.

Activity

  1. changed the title [-]XState POC: a missing actor in provide() compiles and fails silently[/-] [+]XState trial: forgetting to join a worker compiles, then fails silently[/+] on Nov 19, 2026
  2. changed the title [-]XState trial: forgetting to join a worker compiles, then fails silently[/-] [+]A crash inside the reconnect loop stops it for good, and nothing is logged[/+] on Nov 19, 2026
  3. added
    readyReproduced in the app, with a recording
    and removed on Nov 19, 2026
  4. viktorce commented on Nov 19, 2026

    @viktorce
    OwnerAuthor

    Reproduced in the running app

    The issue says there is no recording because the error can't be caused from the app. It can. Two scenarios now cause it in the web client on main 57db750b8f. Each injects one fault from the page and leaves everything after that to the app. The fix is #41.

    1. The issue's own example: the network-status read throws

    The scenario opens a thread, closes the app's socket from the page, as a network drop would, and makes the next read of navigator.onLine throw once. No real browser throws there, so this is an injected fault.

    On main the reconnect loop dies on that read. The banner says "is reconnecting" and stays. Ten seconds later the scenario presses Retry now. Five seconds after that, nothing has changed, and the page has logged nothing about the error:

    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
    $ vp run scenarios:prove scripts/scenarios/reconnect-survives-network-status-defect.e2e.ts --base origin/main
    
    Proven: the scenario fails on base 57db750b8f and passes on head 89017c15a0.
    
    base 57db750b8f
      ASSERTION_FAILED: expect.toBeHidden failed
      locator: getByText("is reconnecting")
      observed: visible (match count 1)
    

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

    The scenario
    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 #41, because no real browser throws from navigator.onLine.

    2. A route real code has: the config stream fails while interrupted

    The issue says no real trigger is known. Reading the code found one. rpc/session.ts fails a session's closed with whatever cause ended the config subscription, unless that cause holds interruptions only. A cause that holds a failure and an interruption gets through, and exitUnlessInterrupted in the supervisor turns any cause holding an interruption into an interruption of the loop.

    The scenario opens a thread and hands the app one server frame that ends the config subscription with a typed failure and an interruption in the same cause. The frame is injected from the page. I found no way to make a real server send it.

    On main the loop dies and the app shows no sign of it. There is no banner and no error. Five seconds later the scenario types a message and presses Enter, and the message stays 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
    $ vp run scenarios:prove scripts/scenarios/reconnect-survives-config-stream-failing-while-interrupted.e2e.ts --base origin/main
    
    Proven: the scenario fails on base 57db750b8f and passes on head 89017c15a0.
    

    This scenario is part of #41.

    What this changes in the issue

    • "Why there is no recording" no longer holds. The two recordings are above.
    • "We know of no real trigger today" needs a caveat. The code has a route to the dead loop, shown in the second scenario. What is still unknown is whether a real server ever sends that frame.
  5. viktorce commented on Nov 19, 2026

    @viktorce
    OwnerAuthor

    Filed upstream as pingdotgg#39418. The fix, #41 here, is upstream as pingdotgg#39420.

  6. viktorce commented on Nov 20, 2026

    @viktorce
    OwnerAuthor

    Fixed upstream by pingdotgg#39420, merged as 38bac7091a. The upstream issue, pingdotgg#39418, closed with it. The three other background tasks are still open as #39.

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

    readyReproduced in the app, with a recordingseverity: lowMinor problemvalue: mediumWorth doing when nearby

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions