Skip to content

Bad interaction with contextvars #362

@Tinche

Description

@Tinche

Hi!

When do you scheduler.spawn at a certain point in the code, chances are a new task will be spawned from the current task. That new task will inherit the current tasks contextvars.

If you're using contextvars for observability (for example), that's not really what you want. I'd expect the job task to inherit a base context, created when the scheduler is initialized.

The cleanest fix I think would be making a copy of the context when the scheduler is initialized and passing in the context to the new task using https://docs.python.org/3.11/library/asyncio-task.html#asyncio.create_task, but that API is 3.11+ only.

What I've done in the meantime is to spawn a pump task when the scheduler is initialized (so the context is clean), and wrap spawn to pass the given coroutine to the pump task using an asyncio.Queue. The pump task then actually spawns the worker task with the correct context.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions