Skip to content

Commit 5337104

Browse files
committed
feat: always include func_file in task serialization to support modules not in Python path
1 parent 18dcd64 commit 5337104

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

src/asynctasq/tasks/services/serializer.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,13 @@ def serialize(self, task: BaseTask) -> bytes:
5353
func = task.func # type: ignore[attr-defined]
5454
func_module = func.__module__
5555
func_name = func.__name__
56-
# Store func_file if it's __main__ module
57-
if func_module == "__main__":
56+
# Always store func_file to support modules not in Python path
57+
# This allows workers to load the module from file if import fails
58+
try:
5859
func_file = func.__code__.co_filename
60+
except AttributeError:
61+
# Built-in or C extension functions don't have __code__
62+
pass
5963

6064
# IMPORTANT: For FunctionTask, individual kwargs are stored as instance attributes
6165
# (e.g., self.user = user_value) but they're also in self.kwargs.

tests/unit/core/test_dispatcher.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -582,7 +582,9 @@ def test_func(x: int, y: str) -> str:
582582
assert call_arg["class"] == f"{FunctionTask.__module__}.{FunctionTask.__name__}"
583583
assert call_arg["metadata"]["func_name"] == "test_func"
584584
assert call_arg["metadata"]["func_module"] == test_func.__module__
585-
assert "func_file" not in call_arg["metadata"] # Not __main__ module
585+
# func_file is now always included to support modules not in Python path
586+
assert "func_file" in call_arg["metadata"]
587+
assert call_arg["metadata"]["func_file"].endswith("test_dispatcher.py")
586588

587589
def test_serialize_function_task_handles_main_module_with_file_path(self) -> None:
588590
# Arrange
@@ -673,9 +675,13 @@ def test_serialize_function_task_handles_main_module_type_error(self) -> None:
673675
task._current_attempt = 0
674676
task._dispatched_at = datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC)
675677

676-
# Act & Assert - should raise AttributeError when trying to access __code__
677-
with raises(AttributeError):
678-
dispatcher._task_serializer.serialize(task)
678+
# Act - should handle AttributeError gracefully and not include func_file
679+
dispatcher._task_serializer.serialize(task)
680+
681+
# Assert - func_file should not be present when __code__ is unavailable
682+
mock_serializer.serialize.assert_called_once()
683+
call_arg = mock_serializer.serialize.call_args[0][0]
684+
assert "func_file" not in call_arg["metadata"]
679685

680686
def test_serialize_function_task_excludes_func_from_params(self) -> None:
681687
# Arrange

0 commit comments

Comments
 (0)