Skip to content

fix: run_task(), run_thread() and PubSub subscriber exceptions lost or logged outside the flet logger - #7110

Open
ndonkoHenri wants to merge 6 commits into
mainfrom
fix/background-error-logging
Open

ndonkoHenri wants to merge 6 commits into
mainfrom
fix/background-error-logging

Conversation

@ndonkoHenri

@ndonkoHenri ndonkoHenri commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #7109.

Exceptions raised in background work were lost, or logged under a logger apps don't watch:

Raised in Before After
A page.run_task() task nothing awaits Logged by concurrent.futures, under its own logger Logged on flet: Unhandled error in run_task() task <name> with the traceback
A page.run_task() task that is awaited Raised at the await, and logged by concurrent.futures, even when the caller handles it Raised at the await only
A page.run_thread() function Not reported by Flet; only asyncio's Future exception was never retrieved Logged on flet
An async PubSub subscriber Lost Logged on flet
A sync PubSub subscriber asyncio's generic message (pool), or raised into the publisher, which stopped delivery to the other subscribers (inline) Logged on flet; the others still get the message

They're logged only. Unlike a handler error, a failed background job doesn't replace the UI with an error screen.

How

  • run_task(): TaskFuture.__await__ runs a small coroutine that marks the outcome handled once the awaiter resumes with it. The completion callback logs the exception when nothing is awaiting the future. If an awaiter never gets it, e.g. it was cancelled just as the task failed, it's logged when the future is discarded (__del__). The previous callback re-raised the exception for concurrent.futures to log, for every failed task.
    • Trade-off, stated in the TaskFuture docstring: an exception raised while nothing awaits the future is logged right away, even if the future is awaited later. Deferring all logging to garbage collection would avoid that, but a future kept in an attribute (self._task = page.run_task(...) in a control) would then hide a crash until the control goes away.
  • run_thread(): the page-context wrapper catches and logs the function's exception.
  • PubSub: a single __publish() collects subscribers under the hub lock and calls them after releasing it. Async subscribers run in a wrapper coroutine that logs their exception, including a wrong-signature TypeError. Sync subscribers are wrapped the same way.
  • Names in log messages come from a new flet.utils.object_model.callable_name(). It unwraps functools.partial and falls back to the type's name, so a partial's arguments (e.g. a token) and a raising __repr__ never reach the log.

Testing

  • tests/test_background_errors.py (11 tests):
    • run_task(): an unawaited failure is logged with its name; an awaited one only raises; a cancelled one isn't logged; a partial's arguments stay out of the message; an exception handed to an awaiter cancelled before it resumes is logged on discard (reproduced for real, not simulated).
    • run_thread(): a failure is logged with its name.
    • PubSub: async, wrong-signature, sync (pool and inline) and raising-repr() subscribers are logged, and the other subscriber still receives the message.
  • tests/test_pubsub_hub.py: a subscriber called inline can unsubscribe without blocking the publish.
  • The new tests fail on main. flet suite: 570 passed, flet-web: 51 passed. Reviewed twice by Codex (gpt-6.2-sol); its findings are addressed in the second and third commits.

Summary by Sourcery

Report unhandled background-work and PubSub subscriber exceptions consistently through the flet logger while preserving expected task and message-delivery behavior.

Bug Fixes:

  • Ensure exceptions from background tasks, threads, and PubSub subscribers are reported through the flet logger without disrupting normal UI behavior or message delivery.

Enhancements:

  • Prevent awaited task failures from being logged redundantly while retaining reporting for unhandled or abandoned task exceptions.
  • Keep PubSub publishing resilient so subscriber failures do not stop delivery to other subscribers.
  • Use safe callable names in background-error messages without exposing callable arguments or relying on potentially failing representations.

Tests:

  • Add coverage for unhandled and awaited task failures, thread exceptions, PubSub subscriber failures, safe callable naming, cancellation, and subscriber delivery behavior.

…orted on the `flet` logger

Exceptions raised in background work were lost or logged under the wrong
logger (#7109):

- `page.run_task()` re-raised a task's exception in the future's done
  callback, so `concurrent.futures` logged it, under its own logger, and for
  every failed task, even one whose future was awaited and whose error was
  handled there. `TaskFuture` now records whether it is awaited, and the
  done callback logs the exception on the `flet` logger, with the task's
  name, only when nothing awaits the future. It no longer re-raises.
- `page.run_thread()` didn't report an exception its function raised: only
  asyncio logged it later as "Future exception was never retrieved". The
  page-context wrapper now logs it on the `flet` logger with the function's
  name. On Pyodide, where the function runs inline, it is logged instead of
  raised to the caller.
- PubSub lost async subscribers' exceptions entirely, and sync ones only
  reached asyncio's generic log. Async subscribers get a done callback and
  sync ones a wrapper that log the exception on the `flet` logger with the
  subscriber's name. A sync subscriber called inline (no executor) that
  raises no longer stops delivery to the other subscribers.

Exceptions are logged, not shown in the app, so a failed background job
doesn't replace the UI with an error screen.

Changelog: 1.1.3 Bug fixes entry.

Tests (tests/test_background_errors.py, 7): an unawaited failing run_task()
task is logged on `flet` with its name; an awaited one raises there and
nothing is logged at ERROR; a cancelled task isn't logged; a failing
run_thread() function is logged with its name; failing async and sync
(pool and inline) PubSub subscribers are logged and the other subscriber
still receives the message. 6 of them fail without the fix. flet (565
passed, 9 skipped) and flet-web (45) suites pass.
Follow-up to review findings on the background error logging change.

run_task():
- `TaskFuture` tracked only whether something started awaiting it, so an
  exception an awaiter never received (the awaiter was cancelled as the task
  failed, or its event loop closed) was neither logged nor retrieved.
  `TaskFuture` now also records retrieval: its `result()` and `exception()`
  overrides mark the outcome retrieved, which `asyncio.wrap_future()` does
  when it hands the outcome to an awaiter. `__del__` logs an awaited task's
  exception that was never retrieved on the `flet` logger. The completion
  callback reads the exception through the base `Future.exception()`, so
  checking it doesn't count as retrieving it, and marks a logged exception
  as handled so `__del__` doesn't log it twice.
- The `TaskFuture` docstring says when an exception is logged: right away if
  nothing awaits the future when the task fails, even if it is awaited
  later, so await the future itself before the task can fail to handle the
  exception; and when the future is discarded if an awaiter never got it.

PubSub:
- The send methods collect their subscribers under the hub lock and deliver
  after releasing it, so a subscriber called inline, or the logging of its
  error, can subscribe and unsubscribe without blocking or changing the set
  being iterated.
- Creating an async subscriber's coroutine is guarded: a subscriber that
  can't take the message's arguments is logged instead of raising into the
  publisher and stopping delivery to the remaining subscribers.

Tests (tests/test_background_errors.py, now 10): wait for the log record
with a bounded timeout instead of a fixed 200 ms sleep; the async subscriber
test checks that the other subscriber still receives the message. New: an
awaited task's exception that is never retrieved is logged when the future
is discarded; an async subscriber with the wrong arguments is logged and
others still receive the message; a subscriber called inline can
unsubscribe while receiving. The 3 new tests fail without this change. flet
(568 passed, 9 skipped) and flet-web (45) suites pass.
Second review round on the background error logging change.

run_task():
- An awaiter cancelled right after a task's exception was handed to it, but
  before it resumed, never received the exception, yet `asyncio.wrap_future()`
  had already called `exception()`, which counted as retrieval, so nothing
  was logged. `TaskFuture.__await__` now runs a small `__wait()` coroutine
  that marks the outcome handled only after the awaiter resumes with it (a
  value or an exception, not its own cancellation). The `result()` and
  `exception()` overrides are removed, which also removes a race where a
  timed-out `result()` call could mark the outcome retrieved.
- The completion callback and `__del__` share `TaskFuture._log_exception()`.

Callable names in log messages:
- Names came from `__qualname__` or `repr()`. The `repr()` of a
  `functools.partial` includes its arguments, such as a token, and a raising
  `__repr__` made `run_task()` raise after scheduling the task, or masked a
  subscriber's error and stopped inline delivery. New
  `flet.utils.object_model.callable_name()` unwraps partials and falls back to
  the type's name, never calling `repr()`; `run_task()` and PubSub use it.

PubSub:
- One `__publish(args, topic=None, exclude=None)` helper collects the
  subscribers under the lock and calls them after releasing it, replacing
  the snapshot code in the four send methods.
- Async subscribers run inside `_call_async_subscriber()`, which awaits the
  subscriber and logs its exception, replacing the done callback, the
  separate wrong-signature handling and the `Future` import. A subscriber
  that can't take the message's arguments is logged from the hub's loop.

Tests (tests/test_background_errors.py, now 12):
- The discard test reproduces the race for real instead of setting
  `_awaited` by hand: it cancels the awaiter in a done callback that runs
  right after the exception is handed to it, inside a helper coroutine, and
  yields once before `gc.collect()` so the loop's current callback releases
  the cancelled awaiter.
- New: a task given as a `functools.partial` is logged with its function's
  name and without its arguments; a failing subscriber whose `repr()` raises
  is logged by its type's name and the others still get the message.
- The 3 changed or new tests fail on the previous commit. flet (570 passed,
  9 skipped) and flet-web (45) suites pass.
The docstring of test_subscriber_can_unsubscribe_while_receiving fits within the line limit, so it no longer wraps.
test_subscriber_can_unsubscribe_while_receiving checks that PubSubHub calls
its subscribers after releasing its lock; no error or logging is involved,
so it didn't belong in test_background_errors.py. It moves unchanged into a
new tests/test_pubsub_hub.py, in a TestPubSubDelivery class, which is the
home for further PubSubHub tests. test_background_errors.py keeps only the
error-logging tests.
Add the PR link next to the issue link in the 1.1.3 Bug fixes entry for background error logging.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Deploying flet-website-v2 with  Cloudflare Pages  Cloudflare Pages

Latest commit: eac3935
Status: ✅  Deploy successful!
Preview URL: https://5cc0baf0.flet-website-v2.pages.dev
Branch Preview URL: https://fix-background-error-logging.flet-website-v2.pages.dev

View logs

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

run_task() background-task exceptions are logged under the concurrent.futures logger, not the flet logger (follow-up to #7102)

1 participant