diff --git a/CHANGELOG.md b/CHANGELOG.md index 5658f9c70f..47f36b79f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 (#2508, #2515) +* `reactive.poll()` and `reactive.file_reader()` no longer call `poll_func` when the decorator is applied; the first value comes from the first poll, in the first reactive flush. Until then, reading the decorated function raises a silent exception. Reading it from inside an output, calc, or effect works as before: the reader waits for the first poll and runs again once it lands. Code that reads it outside the reactive runtime, for example in `reactive.isolate()` while the server function runs, now raises instead of getting the value; move that read into a calc or effect. For `reactive.file_reader()`, a missing file no longer raises when the decorator is applied; the error is raised when the value is read (#2576). + * `near_points(add_dist=True)`, imported from `shiny.plotutils`, now names its distance column `dist_` instead of `dist`. Code reading `df["dist"]` from the result must now read `df["dist_"]` (#2510). ### Lifecycle changes @@ -47,6 +49,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Bug fixes and minor improvements +* `reactive.poll()` now works with an `async` `poll_func` and a custom `equals`; previously every poll failed. (Thanks, @pcbeingused333!) (#2576) + * On Windows, an output's busy indicator now shows while the output renders. Previously, when a synchronous render function blocked the event loop, the message that turns on the indicator reached the browser together with the output's new value, so most outputs never showed it (#1381). * UI updates and custom messages sent outside an output or effect, such as `ui.update_text()` in a `session.on_flushed()` callback or in an `asyncio` task, or `ui.insert_ui()` from a message handler, are now sent to the client right away instead of waiting for the next input change (#1889, #21). diff --git a/examples/model-score/plotly_streaming.py b/examples/model-score/plotly_streaming.py index e18c1439b2..99ecfcd336 100644 --- a/examples/model-score/plotly_streaming.py +++ b/examples/model-score/plotly_streaming.py @@ -82,14 +82,15 @@ def update_plotly_data(): def deduplicate(func): - with reactive.isolate(): - rv = reactive.value(func()) + # Starts unset; the effect below sets it once `func()` has a value. Reading it + # before then raises a silent exception, and readers re-run once it is set. + rv = reactive.value() @reactive.effect def update(): x = func() with reactive.isolate(): - if x != rv(): + if not rv.is_set() or x != rv(): rv.set(x) @reactive.calc diff --git a/shiny/reactive/_poll.py b/shiny/reactive/_poll.py index 0c5d34c598..6c2ade8ac4 100644 --- a/shiny/reactive/_poll.py +++ b/shiny/reactive/_poll.py @@ -98,9 +98,11 @@ def poll( """ with otel.suppress(): - with reactive.isolate(): - last_value: reactive.Value[Any] = reactive.Value(poll_func()) - last_error: reactive.Value[Optional[Exception]] = reactive.Value(None) + # Starts unset: the effect below reads the first value (an async `poll_func` + # can't be awaited here). Until then, `last_value.get()` in the decorated + # function raises a silent exception, and its readers re-run once it is set. + last_value: reactive.Value[Any] = reactive.Value() + last_error: reactive.Value[Optional[Exception]] = reactive.Value(None) @reactive.effect(priority=priority, session=session) async def _(): @@ -111,35 +113,41 @@ async def _(): new = poll_func() with reactive.isolate(): - old = last_value.get() - - try: - is_equal = equals(old, new) - except Exception as e: - # For example, pandas DataFrame throws if you try to compare it to a - # non-comparable object - raise TypeError( - "The reactive.poll polling function returned an object that " - "couldn't be compared with a previously returned object. Try " - "modifying your polling function to return a simpler type, like a " - "str, float, list, or dict." - ) from e - if not isinstance(is_equal, bool): - # Comparison succeeded, but we don't understand the result - if equals is eq: - # We used == but it didn't work + has_old = last_value.is_set() + + if has_old: + with reactive.isolate(): + old = last_value.get() + try: + is_equal = equals(old, new) + except Exception as e: + # For example, pandas DataFrame throws if you try to compare it + # to a non-comparable object raise TypeError( "The reactive.poll polling function returned an object " - "that doesn't implement a simple == operator. Try " - "modifying your polling function to return a simpler type, " - "like a str, float, list, or dict." - ) - else: - # The caller passed in a custom function - raise TypeError( - "The reactive.poll `equals` function returned a non-bool " - "value" - ) + "that couldn't be compared with a previously returned " + "object. Try modifying your polling function to return a " + "simpler type, like a str, float, list, or dict." + ) from e + if not isinstance(is_equal, bool): + # Comparison succeeded, but we don't understand the result + if equals is eq: + # We used == but it didn't work + raise TypeError( + "The reactive.poll polling function returned an " + "object that doesn't implement a simple == operator. " + "Try modifying your polling function to return a " + "simpler type, like a str, float, list, or dict." + ) + else: + # The caller passed in a custom function + raise TypeError( + "The reactive.poll `equals` function returned a " + "non-bool value" + ) + else: + # First poll: nothing to compare with + is_equal = False # If we got here, the comparison succeeded. Need to make sure the error is # cleared, but don't unnecessarily call last_error.set(); at the time of @@ -172,7 +180,8 @@ async def result_async() -> T: if err is not None: raise err - # Take dependency on polling result + # Take dependency on polling result (raises a silent exception + # until the first poll sets it) last_value.get() # Note that we also depend on the main function @@ -195,7 +204,8 @@ def result_sync() -> T: if err is not None: raise err - # Take dependency on polling result + # Take dependency on polling result (raises a silent exception + # until the first poll sets it) last_value.get() # Note that we also depend on the main function diff --git a/tests/pytest/test_poll.py b/tests/pytest/test_poll.py index 69906de88a..837bfcf7c9 100644 --- a/tests/pytest/test_poll.py +++ b/tests/pytest/test_poll.py @@ -93,56 +93,129 @@ def value_func(): mock_time = MockTime() with mock_time(): - # Poll func is invoked once during @poll(), to seed the underlying reactive val - assert (poll_invocations, value_invocations) == (1, 0) + # Poll func is not invoked during @poll(); the polling observer reads the first value + assert (poll_invocations, value_invocations) == (0, 0) await flush() # The observer that updates poll has executed once. # @poll returns a lazy Calc, so value hasn't been invoked yet. - assert (poll_invocations, value_invocations) == (2, 0) + assert (poll_invocations, value_invocations) == (1, 0) @effect() def _(): value_func() await flush() - assert (poll_invocations, value_invocations) == (2, 1) + assert (poll_invocations, value_invocations) == (1, 1) await flush() - assert (poll_invocations, value_invocations) == (2, 1) + assert (poll_invocations, value_invocations) == (1, 1) await mock_time.advance_time(1.01) # poll_invocations advances without a flush() because invalidate_later itself # invokes flush() - assert (poll_invocations, value_invocations) == (3, 1) + assert (poll_invocations, value_invocations) == (2, 1) await flush() - assert (poll_invocations, value_invocations) == (3, 1) + assert (poll_invocations, value_invocations) == (2, 1) # Now change value poll_return1 += 1 await flush() # Nothing changes because no time has passed, poll() has not tried again - assert (poll_invocations, value_invocations) == (3, 1) + assert (poll_invocations, value_invocations) == (2, 1) await mock_time.advance_time(1.01) - assert (poll_invocations, value_invocations) == (4, 2) + assert (poll_invocations, value_invocations) == (3, 2) # When a reactive dependency of poll_func invalidates, there's no need to wait # until the next poll with isolate(): poll_return2.set(poll_return2() + 1) await flush() - assert (poll_invocations, value_invocations) == (5, 3) + assert (poll_invocations, value_invocations) == (4, 3) # When a reactive dependency of value_func invalidates, there's no need to wait # until the next poll with isolate(): value_dep.set(value_dep() + 1) await flush() + assert (poll_invocations, value_invocations) == (4, 4) + + await mock_time.advance_time(1.01) assert (poll_invocations, value_invocations) == (5, 4) + +@pytest.mark.asyncio +async def test_poll_async_poll_func_with_custom_equals(): + async with OnEndedSessionCallbacks(): + poll_invocations = 0 + + async def poll_func(): + nonlocal poll_invocations + poll_invocations += 1 + return {"version": 1} + + @poll(poll_func, equals=lambda old, new: old["version"] == new["version"]) + def value_func(): + return "data" + + mock_time = MockTime() + with mock_time(): + # An async poll_func can't be awaited when @poll() runs, so nothing has + # been polled yet and there is no previous value to compare with. + assert poll_invocations == 0 + + await flush() + assert poll_invocations == 1 + + with isolate(): + assert value_func() == "data" + + await mock_time.advance_time(1.01) + assert poll_invocations == 2 + + with isolate(): + assert value_func() == "data" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_async", [False, True]) +async def test_poll_reader_runs_before_first_poll(is_async: bool): + # A consumer that runs before the polling effect (here, because the polling effect + # has a lower priority) must not cause the expensive read function to run twice. + async with OnEndedSessionCallbacks(): + poll_invocations = 0 + value_invocations = 0 + + def sync_poll_func(): + nonlocal poll_invocations + poll_invocations += 1 + return 1 + + async def async_poll_func(): + return sync_poll_func() + + @poll(async_poll_func if is_async else sync_poll_func, priority=-1) + def value_func(): + nonlocal value_invocations + value_invocations += 1 + return "data" + + seen: list[str] = [] + + @effect() + def _(): + seen.append(value_func()) + + mock_time = MockTime() + with mock_time(): + await flush() + assert (poll_invocations, value_invocations) == (1, 1) + assert seen == ["data"] + await mock_time.advance_time(1.01) - assert (poll_invocations, value_invocations) == (6, 4) + assert (poll_invocations, value_invocations) == (2, 1) + assert seen == ["data"] @pytest.mark.asyncio @@ -213,6 +286,65 @@ def _(): assert invocations == 3 +@pytest.mark.asyncio +async def test_poll_first_poll_raises(): + # When the first poll fails, there is no value yet. Readers must see the real + # error (not a silent exception), and a later successful poll must recover. + async with OnEndedSessionCallbacks(): + should_raise = True + + def poll_func() -> int: + if should_raise: + raise ValueError("boom") + return 1 + + @poll(poll_func) + def value_func() -> str: + return "data" + + mock_time = MockTime() + with mock_time(): + with isolate(): + await flush() + + with pytest.raises(ValueError, match="boom"): + value_func() + + should_raise = False + await mock_time.advance_time(1.01) + + assert value_func() == "data" + + +@pytest.mark.asyncio +async def test_file_reader_missing_file(): + # A missing file doesn't raise when @file_reader() is applied; the error is raised + # to whoever reads the value after the first poll. + with tempfile.TemporaryDirectory() as tmpdir: + path = os.path.join(tmpdir, "missing.txt") + + async with OnEndedSessionCallbacks(): + mock_time = MockTime() + with mock_time(): + + @file_reader(path) + def read_file(): + with open(path, "r") as f: + return f.read() + + with isolate(): + await flush() + + with pytest.raises(FileNotFoundError): + read_file() + + with open(path, "w") as f: + f.write("hello\n") + await mock_time.advance_time(1.01) + + assert read_file() == "hello\n" + + @pytest.mark.asyncio async def test_file_reader(): tmpfile = tempfile.NamedTemporaryFile(delete=False)