Skip to content

fix: collect task exceptions in gokart.build with workers > 1 - #704

Open
kitagry wants to merge 7 commits into
masterfrom
fix/build-error-workers-exceptions
Open

kitagry wants to merge 7 commits into
masterfrom
fix/build-error-workers-exceptions

Conversation

@kitagry

@kitagry kitagry commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Closes #703

What

With workers > 1, gokart.build raised GokartBuildError with an empty raised_exceptions. Each task runs in a forked process, and the FAILURE event fires there. So build()'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 to raised_exceptions. This needs no change in luigi, because gokart.build always uses gokart's own worker (gokart/worker.py).

Design

  1. Child (TaskProcess.run): when the task runs in a separate process (use_multiprocessing, which also covers worker_timeout), the result tuple gets one more element, _ExceptionFromChildProcess. It holds:

    • pickled: the exception pickled in the child. This is None if pickling fails.
    • The original type name (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.

  2. Parent (Worker._handle_next_task): unpickles pickled. If that fails, for example because the exception class is importable only in the child, it builds a ChildProcessTaskError from the strings and logs a warning. It then calls on_child_process_failure(task, exception), a new optional Worker argument that WorkerSchedulerFactory passes through. An error in the callback is logged and does not stop the worker loop, as luigi does for event callbacks.

  3. gokart.build: passes a callback that calls the existing when_failure for TaskOnKart tasks only, the same as the FAILURE handler. So raised_exceptions and the TaskLockException flag are handled the same way as with workers=1.

  4. Traceback: pickling drops __traceback__, so the parent adds the child's formatted traceback with add_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 from args alone drops __notes__. This way the child never changes the original exception, so FAILURE handlers and on_failure() see it as raised. ChildProcessTaskError also has the traceback as .traceback.

With workers=1 (no separate process), nothing changes: raised_exceptions has the same exception object, with its __traceback__ and no note. Tests pin this difference.

A task can also fail with a BaseException such as SystemExit (KeyboardInterrupt is re-raised). As with workers=1, it goes into raised_exceptions as is. The callback is typed with BaseException. The public type of GokartBuildError.raised_exceptions stays dict[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 in args, so it can be pickled itself.

Alternatives considered

  • Fire FAILURE again in the parent instead of a gokart-internal callback. Not done: user FAILURE handlers already ran in the child, so they would run twice (for example, a second notification). A test checks that a handler runs only once.
  • Always send a ChildProcessTaskError instead of the original exception. Not done: the original type is kept whenever possible, so isinstance checks on raised_exceptions work the same as with workers=1.
  • Collect the exceptions in shared memory or a separate queue in build(), like TaskLockExceptionRaisedFlag. Not done: the result queue already orders the exception before the task's status, so there is no race with luigi.build returning. A separate queue would also have the same pickling problems.
  • Also replace TaskLockExceptionRaisedFlag with 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 with workers=2):

  • The failed task's exception is in raised_exceptions, with the child's traceback in __notes__.
  • An exception that can't be unpickled (a required __init__ argument) becomes ChildProcessTaskError.
  • An exception that unpickles in the child but not in the parent becomes ChildProcessTaskError, and the build still raises GokartBuildError.
  • An exception whose __str__ raises is still sent back.
  • The traceback note is kept for an exception whose __reduce__ drops its state.
  • workers=1 keeps the same exception object, with its traceback and no note.
  • SystemExit goes into raised_exceptions with both workers=1 and workers=2.
  • A failed plain luigi.Task dependency still gives GokartBuildError, with an empty raised_exceptions, as with workers=1.
  • A FAILURE handler runs only once.

test/test_build.py, test/test_worker.py, test/test_run.py, test/in_memory and test/conflict_prevention_lock pass locally.

Relation to other PRs

🤖 Generated with Claude Code

https://claude.ai/code/session_01CdA6RRuAhGPHPwCmTEgJGv

@kitagry kitagry self-assigned this Nov 23, 2026
@kitagry
kitagry marked this pull request as ready for review November 23, 2026 14:12

@hirosassa hirosassa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Comment thread gokart/worker.py

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())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread gokart/worker.py

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())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch, thanks. Fixed in 093f3f7:

  • on_child_process_failure (in Worker and WorkerSchedulerFactory) and when_failure / when_child_process_failure in build.py are now typed with BaseException.
  • The behavior matches workers=1: there, a SystemExit from run() already reaches the FAILURE handler and goes into raised_exceptions as is. KeyboardInterrupt is re-raised in TaskProcess.run, so it never gets here. A new test checks SystemExit with both workers=1 and workers=2.
  • I kept the public type of GokartBuildError.raised_exceptions as dict[str, list[Exception]]. Widening it to BaseException would break typed callers, because list is invariant. So when_failure casts when it appends, with a WHY comment. If we want the honest type, it could be a 2.0.0 change.

Comment thread gokart/worker.py Outdated
fallback = ChildProcessTaskError(f'{type(ex).__module__}.{type(ex).__qualname__}', message, tb)
fallback.add_note(note)
try:
ex.add_note(note)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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__ is None (test_raised_exceptions_has_exception_of_failed_task).
  • workers=1: the same object as raised in run(), 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.

kitagry and others added 4 commits November 24, 2026 08:31
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>
@kitagry
kitagry force-pushed the fix/build-error-workers-exceptions branch from b6bdb75 to 2140750 Compare November 23, 2026 23:36
kitagry and others added 3 commits November 25, 2026 21:05
Resolve the conflict with #702 in test/test_build.py by keeping both
sets of tests. With #702, a GokartBuildError raised in a task now
reaches the parent as is with workers > 1, with its raised_exceptions
and status; add a test for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- 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>
@kitagry
kitagry enabled auto-merge (squash) November 25, 2026 12:08
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.

gokart.build(workers>1) raises GokartBuildError with an empty raised_exceptions

2 participants