Skip to content

Conversation

@MadLittleMods
Copy link
Contributor

@MadLittleMods MadLittleMods commented Oct 22, 2025

Fix lost logcontext when using timeout_deferred(...) and things actually timeout.

Fix #19087 (our HTTP client times out requests using timeout_deferred(...)
Fix #19066 (/sync uses notifier.wait_for_events() which uses timeout_deferred(...) under the hood)

When/why did these lost logcontext warnings start happening?

synapse.logging.context - 107 - WARNING - sentinel - Expected logging context call_later but found POST-2453

synapse.logging.context - 107 - WARNING - sentinel - Expected logging context call_later was lost

In #18828, we switched timeout_deferred(...) from using reactor.callLater(...) to clock.call_later(...) under the hood. This meant it started dealing with logcontexts but our time_it_out() callback didn't follow our Synapse logcontext rules.

Dev notes

SYNAPSE_TEST_LOG_LEVEL=DEBUG poetry run trial tests.util.test_async_helpers.TimeoutDeferredTest.test_logcontext_is_not_lost_when_awaiting_on_timeout_cancellation
SYNAPSE_TEST_LOG_LEVEL=INFO poetry run trial tests.rest.client.sliding_sync.test_sliding_sync.SlidingSyncTestCase_new.test_wait_for_new_data_timeout

Pull Request Checklist

  • Pull request is based on the develop branch
  • Pull request includes a changelog file. The entry should:
    • Be a short description of your change which makes sense to users. "Fixed a bug that prevented receiving messages from other servers." instead of "Moved X method from EventStore to EventWorkerStore.".
    • Use markdown where necessary, mostly for code blocks.
    • End with either a period (.) or an exclamation mark (!).
    • Start with a capital letter.
    • Feel free to credit yourself, by adding a sentence "Contributed by @github_username." or "Contributed by [Your Name]." to the end of the entry.
  • Code style is correct (run the linters)

Comment on lines +910 to +918
if current_context() != calling_context:
logcontext_error(
"run_in_background(%s): deferred already completed but the function did not maintain the calling logcontext %s (found %s)"
% (
instance_id,
calling_context,
current_context(),
)
)
Copy link
Contributor Author

@MadLittleMods MadLittleMods Oct 22, 2025

Choose a reason for hiding this comment

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

Extra protection when our assumption is wrong.

This did happen for the case we're fixing.

Comment on lines +815 to +816
with PreserveLoggingContext():
deferred.cancel()
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is the main fix!

See the Deferred callbacks section of our logcontext docs for more info (specifically using solution 2).

Heads-up, I wrote the docs too so it's my assumptions/understanding all the way down. Apply your own scrutiny.

# logcontext from finishing as soon as we exit this function, in case `f`
# returns an awaitable/deferred which would continue running and may try to
# restore the `loop_call` context when it's done (because it's trying to
# restore the `call_later` context when it's done (because it's trying to
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Copy/paste typo

Comment on lines +348 to +349
# Log so we can still see it in the logs like normal
logger.warning(msg)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Quality of life so these the logcontext errors appear in the logs (_trial_temp/test.log) just like if we never used @logcontext_clean to patch it.

logger.warning(...) is the same as what we're doing in the actual thing:

# a hook which can be set during testing to assert that we aren't abusing logcontexts.
def logcontext_error(msg: str) -> None:
logger.warning(msg)


Perhaps it would be even better if we just called the original implementation alongside raising the AssertionError but the implementation is simple enough for now so just going to duplicate.

Comment on lines +279 to +281
async def test_logcontext_is_not_lost_when_awaiting_on_timeout_cancellation(
self,
) -> None:
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This test reproduces the Expected logging context call_later was lost problem with timeout_deferred(...)

And now passes with the fix introduced in this PR.

Comment on lines +815 to +816
with PreserveLoggingContext():
deferred.cancel()
Copy link
Contributor Author

@MadLittleMods MadLittleMods Oct 22, 2025

Choose a reason for hiding this comment

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

In an ideal world, I think it should be possible to call the deferred callback/errbacks/cancel with some logcontext. I spent too much time trying to figure out the intricacies here and trying to use solution 3 from the Deferred callbacks docs but wasn't successful.

It makes me question if what I wrote there is correct in the first place 🤔


The problem is that calling deferred.cancel() can change the logcontext but it's also complete at that point. Because the deferred is already complete, run_in_background(lambda: (deferred.cancel(), deferred)[1]) assumes that the logcontext was unchanged and returns it as-is which leaves the logcontext is messed up for the caller.

I can't tell if the problem is a) our function just isn't following logcontext rules (and how to resolve that well) or b) we should set_current_context(calling_context) regardless of whether the deferred is already complete.

Instead of banging my head against this more, I've opted to go for the simple route with PreserveLoggingContext():. Which also matches what we do elsewhere in the codebase. Something to improve in the future ⏩

@MadLittleMods MadLittleMods marked this pull request as ready for review October 22, 2025 16:16
@MadLittleMods MadLittleMods requested a review from a team as a code owner October 22, 2025 16:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Lost logcontext with antispam module Losting logging context on sync request

1 participant