Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Image worker: record the Python stack of a native crash in the failure report

Bowen Xue55b9d9ed7a78
diff --git a/freevideo_engine/exit_diagnostics.py b/freevideo_engine/exit_diagnostics.py
index e51349c..a7be152 100644
--- a/freevideo_engine/exit_diagnostics.py
+++ b/freevideo_engine/exit_diagnostics.py
@@ -5,6 +5,10 @@ started it takes the readings: once when the request starts and once when the
exit is seen. Only numbers and fixed words leave this module, never text from
the worker, so a diagnostic report stays free of user data.
"""
+import os
+import re
+import tempfile
+
from .system import windows
# Exit codes of a Windows process that the system, not the program, ended.
@@ -99,6 +103,37 @@ def exit_reading(code, *, requested_stop=False, system=None):
return result
+CRASH_FILE_ENV = 'FREEVIDEO_CRASH_FILE'
+_FRAME = re.compile(r'^\s+File "(?P<file>[^"]*)", line (?P<line>\d+) in (?P<name>[A-Za-z0-9_<>.]{1,80})\s*$')
+_FRAME_OUT = re.compile(r'^[A-Za-z0-9_.-]{1,80}:\d{1,7} [A-Za-z0-9_<>.]{1,80}$')
+MAX_FRAMES = 40
+
+
+def new_crash_file():
+ """An empty file the worker's crash handler writes the native crash's Python stack to."""
+ handle, path = tempfile.mkstemp(prefix='freevideo-crash-', suffix='.txt')
+ os.close(handle)
+ return path
+
+
+def read_crash_stack(path):
+ """Frames of the crashed thread as 'file.py:line function': no folder, no other text."""
+ try:
+ with open(path, encoding='utf-8', errors='replace') as stream:
+ text = stream.read(64 * 1024)
+ except (OSError, TypeError):
+ return []
+ frames = []
+ for line in text.splitlines():
+ match = _FRAME.match(line)
+ if match:
+ name = re.split(r'[\\/]', match.group('file'))[-1]
+ frames.append('%s:%s %s' % (name[-80:], match.group('line'), match.group('name')))
+ if len(frames) >= MAX_FRAMES:
+ break
+ return [frame for frame in frames if _FRAME_OUT.match(frame)]
+
+
_SAMPLE_KEYS = _FIELDS + ('process_working_set_bytes', 'process_private_commit_bytes')
_CLASSES = frozenset({'clean', 'stopped_by_us', 'terminated_externally', 'interrupted', 'native_crash',
'error_exit', 'killed_by_signal', 'signal', 'unknown'}
@@ -124,4 +159,9 @@ def clean_reading(value):
memory = clean_sample(value.get('memory'))
if memory:
result['memory'] = memory
+ stack = value.get('native_stack')
+ if isinstance(stack, list):
+ frames = [row for row in stack[:MAX_FRAMES] if isinstance(row, str) and _FRAME_OUT.match(row)]
+ if frames:
+ result['native_stack'] = frames
return result
diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py
index a2d33bb..0558c06 100644
--- a/freevideo_engine/image_gen/service.py
+++ b/freevideo_engine/image_gen/service.py
@@ -4,6 +4,7 @@ from collections import OrderedDict
from copy import deepcopy
import json
import math
+import os
from pathlib import Path
import queue
import re
@@ -85,6 +86,12 @@ class Worker:
for stream in (self.process.stdin, self.process.stdout, self.process.stderr):
if not stream.closed:
stream.close()
+ crash_file = getattr(self.process, 'crash_file', None)
+ if crash_file:
+ try:
+ os.remove(crash_file)
+ except OSError:
+ pass
class Service:
@@ -541,10 +548,20 @@ class Service:
'--device', machine.get('device_backend', 'cuda'),
'--idle-seconds', self.idle_seconds)
command[0] = machine['comfy_python']
+ from ..exit_diagnostics import CRASH_FILE_ENV, new_crash_file
+ crash_file = None
+ try:
+ crash_file = new_crash_file()
+ except OSError:
+ pass
env = dict(env, FREEVIDEO_RUNTIME_LOCK_FD=str(descriptor))
- return processes.popen(command, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
- stderr=subprocess.PIPE, text=True, encoding='utf-8', errors='replace',
- pass_fds=(descriptor,), supervise=True, start_new_session=True)
+ if crash_file:
+ env[CRASH_FILE_ENV] = crash_file
+ process = processes.popen(command, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, text=True, encoding='utf-8', errors='replace',
+ pass_fds=(descriptor,), supervise=True, start_new_session=True)
+ process.crash_file = crash_file
+ return process
def work(self, root, machine):
from ..locking import runtime_lock
@@ -701,8 +718,13 @@ class Service:
code = getattr(error, 'exit_code', None)
if code is not None:
# The worker cannot report its memory once it is gone: read this process's view now.
- from ..exit_diagnostics import exit_reading, memory_sample
- error.exit_reading = dict(exit_reading(code, requested_stop=requested_stop), memory=memory_sample())
+ from ..exit_diagnostics import exit_reading, memory_sample, read_crash_stack
+ reading = dict(exit_reading(code, requested_stop=requested_stop), memory=memory_sample())
+ if reading.get('exit_class') == 'native_crash':
+ stack = read_crash_stack(getattr(session.process, 'crash_file', None))
+ if stack:
+ reading['native_stack'] = stack
+ error.exit_reading = reading
return error
@staticmethod
diff --git a/freevideo_engine/image_gen/worker.py b/freevideo_engine/image_gen/worker.py
index 3ca7012..7c5503c 100644
--- a/freevideo_engine/image_gen/worker.py
+++ b/freevideo_engine/image_gen/worker.py
@@ -181,6 +181,15 @@ def main():
args = parser.parse_args()
if not 0 < args.idle_seconds < float('inf'):
parser.error('--idle-seconds must be positive and finite')
+ # A native crash (access violation, driver fault) leaves no Python error: the crash
+ # handler writes the Python stack to a file the service reads once the worker is gone.
+ crash_file = os.environ.get('FREEVIDEO_CRASH_FILE')
+ if crash_file:
+ try:
+ import faulthandler
+ faulthandler.enable(file=open(crash_file, 'w'), all_threads=False)
+ except (OSError, RuntimeError, ValueError):
+ pass
stream = None
if os.name == 'nt':
from ..win32 import private_stdin