Skip to content

Rejected query read by derived snapshots can leave the renderer unresponsive #1737

Closed

Description

@domgan-oai

Summary

A rejected asynchronous query can leave the renderer CPU-bound when its value is read by a derived signal whose snapshot is consumed during rendering. The application does not reach the error observation or subsequent interaction.

Environment

Octane 0.9.1, Node.js 26.2.0, Vite 8.1.5, Vitest 4.1.11, Playwright 1.62.1, and Chromium headless shell 151.0.7922.34 on Linux. The fixture uses the Strong compiler option.

Reproduction

Create the following files in an empty directory:

package.json:

{
  "name": "octane-query-fallback-repro",
  "private": true,
  "type": "module",
  "scripts": {
    "test:pending": "vitest run --config vite.config.mts -t 'query control pending'",
    "test:ready": "vitest run --config vite.config.mts -t 'query control ready'",
    "test:abort-skip": "vitest run --config vite.config.mts -t 'query control abort-skip'",
    "test:abort": "vitest run --config vite.config.mts -t 'query control abort$'",
    "test:error": "vitest run --config vite.config.mts -t 'query control error'"
  },
  "dependencies": { "@tsrx/core": "0.4.0", "octane": "0.9.1" },
  "devDependencies": {
    "@vitest/browser-playwright": "4.1.11",
    "playwright": "1.62.1",
    "typescript": "5.9.3",
    "vite": "8.1.5",
    "vitest": "4.1.11"
  }
}

vite.config.mts:

import { octane } from "octane/compiler/vite";
import { playwright } from "@vitest/browser-playwright";
import { defineConfig } from "vitest/config";
const provider = playwright();
export default defineConfig({
  root: import.meta.dirname,
  cacheDir: ".vite-cache",
  plugins: [
    { name: "phase-trace", configureServer(server) {
      server.middlewares.use("/__generic-phase", (request, response) => {
        const chunks: Buffer[] = [];
        request.on("data", (chunk: Buffer) => chunks.push(chunk));
        request.on("end", () => {
          process.stdout.write(`[phase] ${Buffer.concat(chunks).toString()}\n`);
          response.statusCode = 204;
          response.end();
        });
      });
    } },
    octane({ requireDirective: true, strong: true }),
  ],
  resolve: { dedupe: ["octane"] },
  optimizeDeps: { noDiscovery: true, include: [], exclude: ["octane", "octane/signals"] },
  test: {
    include: ["*.browser.test.ts"],
    browser: { enabled: true, headless: true, provider, instances: [{ browser: "chromium", provider }] },
  },
});

query-derived.tsrx:

/** @jsxImportSource octane */
import { useEffectEvent, useLayoutEffect, useState } from "octane";
import { captureSignalOwner, currentSignalOwner, derived$, query$, signal$, skip, type WritableSignal } from "octane/signals";
export type Data = { values: readonly number[] };
export type Fixture = { skipFallback: boolean; enabled$: WritableSignal<boolean>; load: (key: string) => Promise<Data>; fallback: (key: string) => Promise<Data> };
export function Example({ fixture }: { fixture: Fixture }) @{
  const [open, setOpen] = useState(false);
  const active$ = signal$(false);
  const eligible$ = derived$(() => fixture.enabled$.get());
  const request$ = query$(() => active$.get() && eligible$.get() ? "a" : skip, fixture.load);
  const selected$ = derived$(() => {
    if (!active$.get() || !eligible$.get()) return null;
    return request$.get();
  });
  const hasValues$ = derived$(() => {
    if (!active$.get() || !eligible$.get()) return false;
    const result = selected$.snapshot();
    return result.status === "ready" && (result.value?.values.length ?? 0) > 0;
  });
  const empty$ = derived$(() => {
    if (!active$.get() || !eligible$.get()) return false;
    const result = selected$.snapshot();
    return result.status === "error" || (result.status === "ready" && result.value?.values.length === 0);
  });
  const fallback$ = query$(() => !fixture.skipFallback && active$.get() && eligible$.get() && empty$.get() ? "fallback" : skip, fixture.fallback);
  const visible$ = derived$(() => hasValues$.get() || (empty$.get() && fallback$.snapshot().status === "ready" && fallback$.get().values.length > 0));
  const run = captureSignalOwner(currentSignalOwner()!);
  const activate = useEffectEvent(() => run(() => active$.set(true)));
  useLayoutEffect(() => { queueMicrotask(activate); });
  const taskState = active$.get() && eligible$.get() ? request$.snapshot() : undefined;
  const taskResult = active$.get() && eligible$.get() ? request$.latest(undefined) : undefined;
  const fallbackNeeded = empty$.get();
  const visible = visible$.get();
  <section>
    <output id="observation">{`${taskState?.status ?? "none"}:${taskResult?.values.length ?? "none"}:${fallbackNeeded}:${visible}`}</output>
    <button id="open" onClick={() => setOpen(true)}>{"Open"}</button>
    @if (open) { <div id="panel">{"Panel"}</div> }
    @if (visible) { <output id="result">{"Loaded"}</output> }
  </section>
}

query-derived.browser.test.ts:

import { createRoot, delegateEvents, flushSync } from "octane";
import { createScope } from "octane/signals";
import { expect, it, vi } from "vitest";
import { userEvent } from "vitest/browser";
import { Example, type Data } from "./query-derived.tsrx";
const phase = (value: string) => navigator.sendBeacon("/__generic-phase", value);
it.each(["pending", "ready", "abort-skip", "abort", "error"] as const)("query control %s", async (mode) => {
  phase("case:start:" + mode);
  const scope = createScope({ scopeKey: "example" });
  const enabled$ = scope.signal$("enabled", true);
  let resolveLoad!: (value: Data) => void;
  const pending = new Promise<Data>((resolve) => { resolveLoad = resolve; });
  const load = vi.fn(() => {
    phase("loader:start");
    if (mode === "pending") return pending;
    if (mode === "ready") return Promise.resolve({ values: [1] });
    return Promise.resolve().then(() => {
      phase("loader:reject:" + mode);
      throw mode.startsWith("abort") ? new DOMException("Retired", "AbortError") : new Error("Synthetic rejection");
    });
  });
  const fallback = vi.fn(async () => { phase("fallback:start"); return { values: [1] }; });
  const host = document.createElement("div");
  document.body.append(host);
  delegateEvents(["click"]);
  const root = createRoot(host);
  try {
    root.render(Example, { fixture: { enabled$, load, fallback, skipFallback: mode === "abort-skip" } });
    flushSync(() => {});
    phase("after:render");
    await vi.waitFor(() => expect(load).toHaveBeenCalledOnce());
    phase("loader:observed");
    if (mode === "abort" || mode === "error") {
      await vi.waitFor(() => expect(fallback).toHaveBeenCalledOnce());
      phase("fallback:observed");
      expect(host.querySelector("#observation")?.textContent).toContain("error");
    }
    if (mode === "abort-skip") {
      await vi.waitFor(() => expect(host.querySelector("#observation")?.textContent).toContain("error"));
      expect(fallback).not.toHaveBeenCalled();
      phase("error:observed");
    }
    if (mode === "ready") await vi.waitFor(() => expect(host.querySelector("#result")?.textContent).toBe("Loaded"));
    await userEvent.click(host.querySelector<HTMLButtonElement>("#open")!);
    phase("after:click");
    expect(host.querySelector("#panel")).not.toBeNull();
    if (mode === "pending") {
      expect(fallback).not.toHaveBeenCalled();
      resolveLoad({ values: [] });
    }
    if (mode !== "abort-skip") {
      await vi.waitFor(() => expect(host.querySelector("#result")?.textContent).toBe("Loaded"));
      phase("result:observed");
    }
  } finally {
    resolveLoad({ values: [] });
    root.unmount();
    host.remove();
    scope.dispose();
  }
}, 15_000);

Install and run:

npm install --ignore-scripts
npx playwright install chromium
npm run test:ready
timeout 25s npm run test:abort-skip
timeout 25s npm run test:abort
timeout 25s npm run test:error

On systems without timeout, use an external watchdog; the test's 15-second timeout did not fire while the browser renderer was busy.

Expected: A rejected query exposes its error to the snapshot consumers. The browser remains responsive, and the independent button works. Where enabled, the fallback query can complete.

Observed: The ready-result control completes and the button works. The abort-skip case reaches the loader rejection and then times out before observing the error, without starting the fallback. Both abort and error reach the rejection and start the fallback, then time out before it can be observed. Each timed-out command exited with code 124 under the external watchdog. The same behavior occurs for an ordinary Error and an AbortError.

Related reports: #1735 and #1736. This reproduction focuses on a settled rejection read by derived snapshots; it does not establish that the fallback is the cause.

Activity

  1. added a commit that references this issue on Oct 5, 2026
    21e0575
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