tap: a nested flushTapSync drains the enclosing flush's queued work

Author: samdickson22Created Sep 25, 2026Updated Sep 25, 2026
Labelsbug

flushTapSync swaps in a fresh flush state, so a nested flush runs only the schedulers marked inside its callback. But that state holds only the scheduler set. The task queue (scheduledTasks), the notification queue (pendingNotifies) and the shared taskScheduler's dirty bit are module-global. A nested flush therefore drains, and clears, work that belongs to the enclosing flush.

A nested flush is common: the first subscribe to a mountOnSubscribe root commits through flushTapSync(() => scheduleTask(commit)) (packages/tap/src/core/createTapRoot.ts:53), and so does every createTapRoot call. Each queue gives one symptom.

Symptom 1: notifications (#8265)

Called from a listener, the nested flush's drain also delivers the notifications still queued behind that listener. Another root's listener runs inside subscribe(). If it throws, subscribe() reads the error as a failed commit, unmounts the root it just mounted and rethrows.

typescript
import { createTapRoot, flushTapSync } from "@assistant-ui/tap";
import { useEffect, useState } from "react";

const counter = () => {
  let set!: (v: number) => void;
  const root = createTapRoot(function Counter() {
    const [s, setS] = useState(0);
    set = setS;
    return s;
  });
  return { root, set: (v: number) => set(v) };
};

const events: string[] = [];
const lazy = createTapRoot(
  function Lazy() {
    useEffect(() => {
      events.push("setup");
      return () => events.push("cleanup");
    }, []);
    return 1;
  },
  { mountOnSubscribe: true },
);
const a = counter();
const c = counter();

a.root.subscribe(() => {
  try {
    lazy.subscribe(() => {});
  } catch (error) {
    console.log("subscribe failed:", error); // runs
  }
});
c.root.subscribe(() => {
  throw new Error("listener");
});

flushTapSync(() => {
  a.set(1);
  c.set(1);
}); // does not throw: the error went to lazy.subscribe()
console.log(events.at(-1)); // "cleanup": the mount was rolled back

Symptom 2: tasks (#8312)

Releasing a lazy root's last subscriber queues its unmount for the next flush, so a resubscribe in the same tick keeps it mounted. A nested flush in between runs that queued unmount while the root has no subscriber, and the resubscribe mounts it again: its effects run cleanup and setup.

typescript
import { createTapRoot } from "@assistant-ui/tap";
import { useEffect } from "react";

const events: string[] = [];
const lazyRoot = (name: string) =>
  createTapRoot(
    function Lazy() {
      useEffect(() => {
        events.push(`${name}:mount`);
        return () => events.push(`${name}:unmount`);
      });
      return 1;
    },
    { mountOnSubscribe: true },
  );
const tick = () => new Promise((r) => setTimeout(r, 0));

const x = lazyRoot("x");
const z = lazyRoot("z");
const unsubscribeX = x.subscribe(() => {});
await tick();
events.length = 0;

unsubscribeX();
z.subscribe(() => {}); // or: createTapRoot(function Other() { return 1; });
x.subscribe(() => {});
await tick();
console.log(events.filter((e) => e.startsWith("x:")));
// ["x:unmount", "x:mount"] in production, twice in development; expected []

Where it came from

  • The task queue became global in #5857 (8e77515ce), which replaced the per-root commit and unmount schedulers, which lived in the flush state, with one shared queue. The symptom 2 repros pass at 8e77515ce^.
  • The notification queue came in #5833 (5c092efb8), a few commits earlier. The symptom 1 repros still fail at 8e77515ce^ and pass at 5c092efb8^.
  • #6171 already hands schedulers stranded in the temporary state back to the restored one. The two queues never got the same treatment.

Proposed fix

Put both queues on the flush state, so the swap that already scopes the schedulers scopes them too:

  • GlobalFlushState gets tasks and notifies, and the drain and taskScheduler read flushState.tasks and flushState.notifies.
  • The flushTapSync hand-back appends any tasks stranded in the temporary state to the restored one. It also re-marks taskScheduler when the restored state has tasks, because running the singleton inside the nested flush cleared the dirty bit the enclosing flush relies on.

That is one file, scheduler.ts, about +23/-12, and no public surface. It replaces #8268 and #8322, which each patched one queue.

Two behaviour changes:

  1. A flushTapSync called from a listener delivers its own notifications before the ones queued behind that listener. Today it delivers the queued ones first, re-entrantly.
  2. A task queued before a flushTapSync waits for its own flush instead of running inside it. createTapRoot is the only scheduleTask caller, and the store's destroy relies only on tasks queued inside its callback, which still run synchronously.

Open questions

  1. Is "a nested flush delivers its own notifications first" the order you want, or should the enclosing drain own delivery?
  2. Should taskScheduler stay a singleton, so the update-depth guard from #5857 keeps counting it as one scheduler, with the re-mark on hand-back? Or should each flush state get its own, so there is no shared dirty bit?
  3. flushScheduled drains notifications only when activeDrainRuns === null. Since #5833 made flushTapSync inside a drain a plain callback, that is always true there. Should the check be dropped in the same PR or left alone?

Track in Rupic

Source: assistant-ui/assistant-ui