Repository navigation
Conversation
hirosassa
left a comment
There was a problem hiding this comment.
Thanks, the approach looks sound (pickling in the child so a bad exception can't drop the result, fallback in the parent, no double FAILURE). Three small points inline.
|
|
||
| if exception_from_child is not None and self._on_child_process_failure is not None: | ||
| try: | ||
| self._on_child_process_failure(task, exception_from_child.load()) |
There was a problem hiding this comment.
Question on the guard above: when the result is for a task that is no longer in _running_tasks, the loop does continue before this call, so its exception never reaches raised_exceptions. task itself is always valid here, so there is no crash risk. I think dropping it is fine (the task was already removed), but is that intended? A one-line WHY near the continue would make it explicit.
There was a problem hiding this comment.
Yes, that's intended. A result for a task that is no longer in _running_tasks belongs to a run that was already handled. For example, _purge_children reports a timeout and the terminated child's own result arrives later. The status of that result is dropped as well, so dropping its exception with it keeps raised_exceptions consistent with what the scheduler was told. I added a one-line WHY above the continue in 093f3f7.
|
|
||
| if exception_from_child is not None and self._on_child_process_failure is not None: | ||
| try: | ||
| self._on_child_process_failure(task, exception_from_child.load()) |
There was a problem hiding this comment.
Type mismatch: on_child_process_failure is typed Callable[[Task, Exception], None], but load() returns BaseException (the child catches BaseException, so e.g. KeyboardInterrupt / SystemExit can come through). pyright passes only because of the unpickled Any. Either type the callback with BaseException, or have from_exception / the call site handle non-Exception explicitly. when_failure in build.py is also annotated Exception.
There was a problem hiding this comment.
Good catch, thanks. Fixed in 093f3f7:
on_child_process_failure(inWorkerandWorkerSchedulerFactory) andwhen_failure/when_child_process_failureinbuild.pyare now typed withBaseException.- The behavior matches
workers=1: there, aSystemExitfromrun()already reaches the FAILURE handler and goes intoraised_exceptionsas is.KeyboardInterruptis re-raised inTaskProcess.run, so it never gets here. A new test checksSystemExitwith bothworkers=1andworkers=2. - I kept the public type of
GokartBuildError.raised_exceptionsasdict[str, list[Exception]]. Widening it toBaseExceptionwould break typed callers, becauselistis invariant. Sowhen_failurecasts when it appends, with a WHY comment. If we want the honest type, it could be a 2.0.0 change.
| fallback = ChildProcessTaskError(f'{type(ex).__module__}.{type(ex).__qualname__}', message, tb) | ||
| fallback.add_note(note) | ||
| try: | ||
| ex.add_note(note) |
There was a problem hiding this comment.
ex.add_note(note) mutates the original exception in the child before pickling. That is what makes the traceback visible in the parent, but with workers=1 the exception has no note (it keeps __traceback__ instead), so raised_exceptions[...][0].__notes__ differs between the two modes. Could a test pin this (e.g. assert the note exists with workers=2 and that workers=1 still has the same exception object with its traceback)? Also, if a user's FAILURE handler or __str__ ran earlier in the child, they will not see the note, which seems fine; worth a comment if intended.
There was a problem hiding this comment.
Thanks. While looking into this, I found one more problem with adding the note in the child: an exception whose __reduce__ rebuilds it from args alone (common in libraries) drops __dict__, so __notes__ was lost in the parent. So in 2140750, the worker process no longer modifies the exception at all. It sends the formatted traceback and pid next to the pickled exception, and the parent adds the note after unpickling, or to the ChildProcessTaskError fallback.
This also answers your second point: FAILURE handlers, on_failure() and __str__ in the child always see the exception as raised, the same as with workers=1. The comment on the note explains why it is added in the parent.
Tests now pin both modes:
workers=2: the note has the child's traceback, and__traceback__isNone(test_raised_exceptions_has_exception_of_failed_task).workers=1: the same object as raised inrun(), with__traceback__and no__notes__(test_single_worker_keeps_the_raised_exception_without_note).- The note is kept when
__reduce__drops the state (test_traceback_note_is_kept_when_reduce_drops_the_exception_state).
docs/intro_to_gokart.rst also describes the difference now.
With workers > 1, a task runs in a forked process and the FAILURE event fires there, so build() appended the exception to the child's copy of raised_exceptions and the parent raised GokartBuildError with an empty dict. The worker process now sends the exception back through the result queue, and the parent passes it to build() through a callback on the worker. FAILURE is not fired again in the parent, so user handlers still run once. An exception that can't make a pickle round trip becomes ChildProcessTaskError with its type name, message and traceback, so the queue does not drop the result. Closes #703 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CdA6RRuAhGPHPwCmTEgJGv
The parent may fail to unpickle an exception that the worker process can pickle, for example when its class is importable only there. Then Queue.get raised and the whole result was lost. The worker process now sends the pickled bytes with a ChildProcessTaskError fallback, and the parent falls back when unpickling fails. This also pickles the exception only once. Also, only TaskOnKart failures go to raised_exceptions as with the FAILURE handler, and an error in the callback no longer stops the worker loop. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CdA6RRuAhGPHPwCmTEgJGv
- Type the child process failure callback with BaseException, since a task run can fail with SystemExit, and keep it in raised_exceptions as with workers=1. - Explain why a result for a task that is not running is dropped, and why the note is added after the FAILURE handlers. - Pin the difference in __notes__ / __traceback__ between workers=1 and workers > 1 with tests. - Document raised_exceptions with workers > 1 and ChildProcessTaskError. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An exception whose __reduce__ rebuilds it from args alone drops __notes__, so a note added in the worker process was lost. The worker process now sends the traceback with the pickled exception, and the parent adds the note after unpickling. The worker process no longer changes the original exception, and the traceback is sent only once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
b6bdb75 to
2140750
Compare
- Package the exception for the parent even when on_failure() raises, since the FAILURE handlers have already seen it. - Fall back to ChildProcessTaskError if unpickling returns something that is not an exception. - Say in the docs that a worker timeout or force_multiprocessing also runs tasks in worker processes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Closes #703
What
With
workers > 1,gokart.buildraisedGokartBuildErrorwith an emptyraised_exceptions. Each task runs in a forked process, and theFAILUREevent fires there. Sobuild()'s handler appended the exception to the child's copy of the dict, and only strings went back to the parent through the worker's result queue.This PR sends the exception of a failed task from the worker process back to the parent, and
build()adds it toraised_exceptions. This needs no change in luigi, becausegokart.buildalways uses gokart's own worker (gokart/worker.py).Design
Child (
TaskProcess.run): when the task runs in a separate process (use_multiprocessing, which also coversworker_timeout), the result tuple gets one more element,_ExceptionFromChildProcess. It holds:pickled: the exception pickled in the child. This isNoneif pickling fails.module.qualname), message, formatted traceback and pid, as strings and an int.The exception is pickled in the child, not left to the queue. If the queue's feeder thread fails to pickle a result, it drops the whole tuple, and the parent would wait for that task forever.
Parent (
Worker._handle_next_task): unpicklespickled. If that fails, for example because the exception class is importable only in the child, it builds aChildProcessTaskErrorfrom the strings and logs a warning. It then callson_child_process_failure(task, exception), a new optionalWorkerargument thatWorkerSchedulerFactorypasses through. An error in the callback is logged and does not stop the worker loop, as luigi does for event callbacks.gokart.build: passes a callback that calls the existingwhen_failureforTaskOnKarttasks only, the same as theFAILUREhandler. Soraised_exceptionsand theTaskLockExceptionflag are handled the same way as withworkers=1.Traceback: pickling drops
__traceback__, so the parent adds the child's formatted traceback withadd_note()after unpickling (Traceback in the worker process (pid N): ...). It is added in the parent, not the child, because an exception whose__reduce__rebuilds it fromargsalone drops__notes__. This way the child never changes the original exception, so FAILURE handlers andon_failure()see it as raised.ChildProcessTaskErroralso has the traceback as.traceback.With
workers=1(no separate process), nothing changes:raised_exceptionshas the same exception object, with its__traceback__and no note. Tests pin this difference.A task can also fail with a
BaseExceptionsuch asSystemExit(KeyboardInterruptis re-raised). As withworkers=1, it goes intoraised_exceptionsas is. The callback is typed withBaseException. The public type ofGokartBuildError.raised_exceptionsstaysdict[str, list[Exception]], because widening it would break typed callers.New public class
gokart.errors.ChildProcessTaskError(type_name, message, traceback).str(e)is"<type_name>: <message>". All fields are inargs, so it can be pickled itself.Alternatives considered
FAILUREagain in the parent instead of a gokart-internal callback. Not done: userFAILUREhandlers already ran in the child, so they would run twice (for example, a second notification). A test checks that a handler runs only once.ChildProcessTaskErrorinstead of the original exception. Not done: the original type is kept whenever possible, soisinstancechecks onraised_exceptionswork the same as withworkers=1.build(), likeTaskLockExceptionRaisedFlag. Not done: the result queue already orders the exception before the task's status, so there is no race withluigi.buildreturning. A separate queue would also have the same pickling problems.TaskLockExceptionRaisedFlagwith the callback. Left out to keep this PR small. The flag still works as before, and it is now also set from the parent.Tests
In
test/test_build.py,TestBuildRaisedExceptionsWithMultipleWorkers(all withworkers=2):raised_exceptions, with the child's traceback in__notes__.__init__argument) becomesChildProcessTaskError.ChildProcessTaskError, and the build still raisesGokartBuildError.__str__raises is still sent back.__reduce__drops its state.workers=1keeps the same exception object, with its traceback and no note.SystemExitgoes intoraised_exceptionswith bothworkers=1andworkers=2.luigi.Taskdependency still givesGokartBuildError, with an emptyraised_exceptions, as withworkers=1.FAILUREhandler runs only once.test/test_build.py,test/test_worker.py,test/test_run.py,test/in_memoryandtest/conflict_prevention_lockpass locally.Relation to other PRs
GokartBuildErrorpickling). A nestedGokartBuildErrorthat can't be pickled before fix: make GokartBuildError picklable #702 falls back toChildProcessTaskError. The two PRs touch different parts ofbuild.py.docs/intro_to_gokart.rstnow explainsraised_exceptionswithworkers > 1andChildProcessTaskError.🤖 Generated with Claude Code
https://claude.ai/code/session_01CdA6RRuAhGPHPwCmTEgJGv