Skip to content

useOptimistic clears too early or too late when saves overlap Suspense #1348

Closed

Description

@jonkwheeler

Observed behavior

An async save can erase an already-visible useOptimistic result while its own transition is still pending. After the save promise resolves, the real update renders a child that suspends; Octane restores the old saved state but drops the optimistic delta. The screen returns from 1 to 0 until the child resolves, while isPending remains true. React 19.2.7 retains 1 throughout this interval.

A second manifestation appears with a separate root already holding a synchronous Suspense transition. An independent save finishes with saved=1 and isPending=false, but its optimistic result becomes 2 until the unrelated root resolves. React shows 1.

Environment

  • Octane commit 1bebd3b2f3cadd672a772d7f27c444a14e7a0fa5, package version 0.6.0.
  • Node 22.22.2, pnpm 11.15.1, Vitest 4.1.10, jsdom 30.0.1.
  • Matched React/ReactDOM 19.2.7 oracle, same component source and interactions.
  • Client rendering; no SSR or hydration. Browser behavior has not been separately tested.

Reproduction

From the pinned repository checkout, install its locked dependencies with pnpm install --frozen-lockfile. Save the following two files. The test uses the repository's existing compiler loader and public component/root APIs. Its post-await setter explicitly uses startTransition in both renderers.

packages/octane/tests/evidence-optimistic-8505.test.ts
import { describe, expect, it } from 'vitest';
import * as React from 'react';
import { createRoot as createReactRoot } from 'react-dom/client';
import { act as octaneAct } from '../src/index.js';
import { mount } from './_helpers.js';
import { evaluateCompiledFixtureCode, loadPlainHookFixtureSource } from './_server-fixture.js';

const source = `
import { createElement as h, Suspense, useState, useTransition, useOptimistic, startTransition } from 'octane';
function Details(props) {
  return h('span', {id: 'detail'}, props.version === 0 ? 'old' : props.read());
}
export function ActionApp(props) {
  const [saved, setSaved] = useState(0);
  const [pending, start] = useTransition();
  const [optimistic, add] = useOptimistic(saved, (state, delta) => state + delta);
  return h('div', null,
    h('button', {id: 'save', onClick: () => start(async () => {
      add(1);
      await props.save;
      startTransition(() => setSaved(1));
    })}, 'Save'),
    h('output', {id: 'saved'}, String(saved)),
    h('output', {id: 'optimistic'}, String(optimistic)),
    h('output', {id: 'pending'}, pending ? 'pending' : 'idle'),
    h(Suspense, {fallback: h('span', {id: 'fallback'}, 'loading')},
      h(Details, {version: props.suspend ? saved : 0, read: props.read})));
}
export function SuspendedApp(props) {
  const [version, setVersion] = useState(0);
  const [pending, start] = useTransition();
  return h('section', null,
    h('button', {id: 'navigate', onClick: () => start(() => setVersion(1))}, 'Navigate'),
    h('output', {id: 'pending'}, pending ? 'pending' : 'idle'),
    h(Suspense, {fallback: h('span', {id: 'fallback'}, 'loading')},
      h(Details, {version, read: props.read})));
}
`;

type Runtime = 'react' | 'octane';
const fixtures = {
  octane: loadPlainHookFixtureSource(source, {
    id: 'evidence-optimistic-8505.ts',
    inlineHookMemo: false,
    hmr: process.env.OCTANE_TEST_COMPILE_MODE !== 'prod',
  }),
  react: evaluateCompiledFixtureCode(
    source.replace("from 'octane'", "from 'react'"),
    'evidence-optimistic-react-8505.js',
    'client',
    { react: React },
  ),
};
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;

function gate() {
  let ready = false;
  let resolve!: () => void;
  const promise = new Promise<void>((done) => { resolve = done; });
  return {
    promise,
    release() { ready = true; resolve(); },
    read() { if (!ready) throw promise; return 'ready'; },
  };
}

async function turn(runtime: Runtime, action: () => void) {
  const act = runtime === 'react' ? React.act : octaneAct;
  await act(async () => {
    action();
    for (let index = 0; index < 12; index++) await Promise.resolve();
  });
}

async function render(runtime: Runtime, name: 'ActionApp' | 'SuspendedApp', props: any) {
  if (runtime === 'octane') {
    let result!: ReturnType<typeof mount>;
    await turn(runtime, () => { result = mount(fixtures.octane[name], props); });
    return { container: result.container, unmount: result.unmount };
  }
  const container = document.createElement('div');
  document.body.appendChild(container);
  const root = createReactRoot(container);
  await turn(runtime, () => root.render(React.createElement(fixtures.react[name], props)));
  return { container, unmount() { root.unmount(); container.remove(); } };
}

function text(container: HTMLElement, selector: string) {
  return container.querySelector(selector)?.textContent;
}
function snapshot(container: HTMLElement) {
  return {
    saved: text(container, '#saved'),
    optimistic: text(container, '#optimistic'),
    pending: text(container, '#pending'),
    detail: text(container, '#detail'),
    fallback: text(container, '#fallback'),
  };
}
function click(container: HTMLElement, selector: string) {
  (container.querySelector(selector) as HTMLButtonElement).click();
}

describe.each(['react', 'octane'] as const)('%s optimistic Action ownership', (runtime) => {
  it('settles an ordinary optimistic action without a suspended transition', async () => {
    const save = gate();
    const app = await render(runtime, 'ActionApp', {save: save.promise, suspend: false});
    try {
      expect(snapshot(app.container)).toEqual({saved: '0', optimistic: '0', pending: 'idle', detail: 'old', fallback: undefined});
      await turn(runtime, () => click(app.container, '#save'));
      expect(snapshot(app.container)).toEqual({saved: '0', optimistic: '1', pending: 'pending', detail: 'old', fallback: undefined});
      await turn(runtime, save.release);
      const completed = snapshot(app.container);
      console.info(runtime, 'ordinary save completed', completed);
      expect(completed).toEqual({saved: '1', optimistic: '1', pending: 'idle', detail: 'old', fallback: undefined});
    } finally {
      await turn(runtime, save.release);
      await turn(runtime, app.unmount);
    }
  });

  it('keeps visible optimistic state while the completed save waits on its Suspense child', async () => {
    const save = gate();
    const detail = gate();
    const app = await render(runtime, 'ActionApp', {save: save.promise, read: detail.read, suspend: true});
    try {
      await turn(runtime, () => click(app.container, '#save'));
      expect(snapshot(app.container)).toEqual({saved: '0', optimistic: '1', pending: 'pending', detail: 'old', fallback: undefined});
      await turn(runtime, save.release);
      const held = snapshot(app.container);
      console.info(runtime, 'save completed, detail still pending', held);
      expect.soft(held).toEqual({saved: '0', optimistic: '1', pending: 'pending', detail: 'old', fallback: undefined});
      await turn(runtime, detail.release);
      expect(snapshot(app.container)).toEqual({saved: '1', optimistic: '1', pending: 'idle', detail: 'ready', fallback: undefined});
    } finally {
      await turn(runtime, () => { save.release(); detail.release(); });
      await turn(runtime, app.unmount);
    }
  });

  it('removes a settled optimistic delta while an unrelated root remains suspended', async () => {
    const save = gate();
    const detail = gate();
    const unrelated = await render(runtime, 'SuspendedApp', {read: detail.read});
    const app = await render(runtime, 'ActionApp', {save: save.promise, read: detail.read, suspend: false});
    try {
      await turn(runtime, () => click(unrelated.container, '#navigate'));
      expect(text(unrelated.container, '#pending')).toBe('pending');
      expect(text(unrelated.container, '#detail')).toBe('old');
      await turn(runtime, () => click(app.container, '#save'));
      expect(text(app.container, '#optimistic')).toBe('1');
      await turn(runtime, save.release);
      const settled = snapshot(app.container);
      console.info(runtime, 'save completed, unrelated root still pending', settled);
      expect(text(unrelated.container, '#pending')).toBe('pending');
      expect.soft(settled).toEqual({saved: '1', optimistic: '1', pending: 'idle', detail: 'old', fallback: undefined});
      await turn(runtime, detail.release);
      expect(text(app.container, '#optimistic')).toBe('1');
      expect(text(unrelated.container, '#pending')).toBe('idle');
      expect(text(unrelated.container, '#detail')).toBe('ready');
    } finally {
      await turn(runtime, () => { save.release(); detail.release(); });
      await turn(runtime, () => { app.unmount(); unrelated.unmount(); });
    }
  });
});
evidence-8505.config.mjs
import { defineConfig } from 'vitest/config';
import { octane } from './packages/octane/src/compiler/vite.js';
export default defineConfig({ plugins: [octane({ hmr: process.env.EVIDENCE_MODE !== 'production' })], test: { cache: false, environment: 'jsdom', include: ['packages/octane/tests/evidence-optimistic-8505.test.ts'], setupFiles: ['packages/octane/tests/_per-test-setup.ts'] } });

Run only the primary save-then-suspend reproduction:

pnpm exec vitest run --config evidence-8505.config.mjs --reporter=verbose --testNamePattern 'keeps visible optimistic'

Run all three scenarios against both renderers:

pnpm exec vitest run --config evidence-8505.config.mjs --reporter=verbose
EVIDENCE_MODE=production OCTANE_TEST_COMPILE_MODE=prod pnpm exec vitest run --config evidence-8505.config.mjs --reporter=verbose

Expected and actual

Both renderers initially show saved 0, optimistic 0, idle. Starting the save shows saved 0, optimistic 1, pending.

Intermediate observation Expected / React Octane
Save resolved; its detail child still suspends saved 0, optimistic 1, pending saved 0, optimistic 0, pending
Save resolved; only an unrelated root still suspends saved 1, optimistic 1, idle saved 1, optimistic 2, idle

The detail child retains its previous old content with no fallback in both cases. The failure is the public optimistic value, not an internal count or render-frequency difference.

The deferred-commit design explicitly requires optimistic values to remain visible through rollback. The documented async-action model also treats useOptimistic as the visible in-flight surface.

Verification

  • Development compiler: both failures reproduced in two runs. In the final six-case run, all three React scenarios and the ordinary Octane save control passed; the existing async-action conformance suite also passed all 10 tests.
  • Production compiler: the full six-case suite produced the same two Octane failures and four passes. Both renderers passed the ordinary save control (0/idle → optimistic 1/pending → saved and optimistic 1/idle).
  • The failure assertions are soft so the tests continue: after the suspended details resolve, both renderers pass the final convergence checks in both scenarios. The defect lasts for the pending interval; the tests do not indicate permanent state corruption.
  • Each failure reproduced in 3/3 executions: two development compiler runs and one production compiler run. These are compiler-mode checks under jsdom, not a production-browser claim.

Likely cause from source

The apparent common cause is that optimistic cleanup subscribes to the process-global transition count rather than the lifetime of the relevant transition commit:

The shared global lifetime is explicit in the source; the precise scheduling sequence above is the likely explanation, without instrumentation or a fix comparison. No last-good revision was established and no production code was changed.

Duplicate review: reviewed open/closed issues and relevant PRs, including #943 and #946. #967 concerns async priority-window leakage; these cases explicitly wrap the post-await setter in startTransition, and the unrelated pending work is synchronous Suspense. #1341 concerns an external-store selector. Neither reproduces this optimistic queue lifetime failure.

Activity

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