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.
Precompile status: preserve write order and responsive cancellation
Bowen Xuea104e97e9818
diff --git a/freevideo_engine/background_compile.py b/freevideo_engine/background_compile.pyindex 377c09a..a2aa765 100644--- a/freevideo_engine/background_compile.py+++ b/freevideo_engine/background_compile.py@@ -12,7 +12,8 @@ always did.It runs only before the session's first generation. After that, the residentencoder holds GPU memory that a request would release, so the plan would no-longer be the request's. An interrupted run writes no receipt. When the run+longer be the request's. An interrupted run leaves the cache receipt intact+and records diagnostic status separately. When the runwas stopped or found no room (background_room), the session waits twice aslong before the next try, up to MAX_DELAY; the next start tries again too."""@@ -24,6 +25,7 @@ import timefrom . import processesfrom .long_paths import io_path+from .precompile_state import read, recordSTART_DELAY = 30.# A compile that is owed (nothing compiled yet for this code, driver or GPU)@@ -70,6 +72,7 @@ class BackgroundCompile:self.thread = Noneself.lock = Noneself.attempts = []+ self.root = Nonedef start(self, command, *, environment, cwd, log, lock, busy, delay=START_DELAY):"""Run `command` once the session is quiet; False when this session already did.@@ -80,6 +83,7 @@ class BackgroundCompile:if self.thread is not None or self.closed.is_set():return Falseself.lock = Path(lock)+ self.root = Path(log).parentself.thread = threading.Thread(target=self._work, args=(command, environment, cwd, Path(log), busy, delay),name='FreeVideo background compile', daemon=True)self.thread.start()@@ -96,12 +100,15 @@ class BackgroundCompile:with self.guard:process, self.process = self.process, Noneif process is None:+ if final and self.thread is not None and self.thread.is_alive():+ record(self.root, 'not_started', reason='foreground_work', final=True)return Nonerow = self.attempts[-1]if process.poll() is None:# Marked before the signal: the worker thread then retries# instead of reading the exit as a finished run.row['stopped'] = True+ record(self.root, 'not_started', reason='foreground_work', final=final)processes.stop(process, grace=STOP_GRACE)row['stop_seconds'] = time.monotonic() - tick# Every process of the tree holds the lease; once it is free the@@ -129,20 +136,30 @@ class BackgroundCompile:def _quiet(self, busy, delay):"""True after `delay` seconds without work; False once closed."""since = time.monotonic()+ postponed = Falsewhile time.monotonic() - since < delay:if self.closed.wait(1.):return Falseif busy():since = time.monotonic()+ if not postponed:+ record(self.root, 'not_started', reason='session_busy')+ postponed = True+ else:+ postponed = Falsereturn Truedef _work(self, command, environment, cwd, log, busy, delay):# The first wait may be shorter than the retry backoff, which always# starts from START_DELAY: a stopped or crowded-out run is not hammered.pause = START_DELAY+ self.root = log.parentfor attempt in range(ATTEMPTS):if attempt:pause = delay = min(2 * pause, MAX_DELAY)+ # A retry retains the actual pressure/stop reason from its last+ # attempt instead of replacing it with the backoff mechanism.+ record(self.root, 'not_started', reason=None if attempt else 'idle_delay')if not self._quiet(busy, delay):returnwith self.guard:@@ -152,12 +169,19 @@ class BackgroundCompile:'a generation request stops it.')row = dict(started=time.time())self.attempts.append(row)- with io_path(log).open('ab') as stream:- from .triton_compat import temporary_environment- environment = temporary_environment(environment.get('FREEVIDEO_HOME') or self.lock.parent, environment)- process = self.process = processes.popen(- command, env=environment, cwd=cwd, stdin=subprocess.DEVNULL, stdout=stream,- stderr=subprocess.STDOUT, start_new_session=True, supervise=True)+ try:+ with io_path(log).open('ab') as stream:+ from .triton_compat import temporary_environment+ environment = temporary_environment(environment.get('FREEVIDEO_HOME') or self.lock.parent,+ environment)+ process = self.process = processes.popen(+ command, env=environment, cwd=cwd, stdin=subprocess.DEVNULL, stdout=stream,+ stderr=subprocess.STDOUT, start_new_session=True, supervise=True)+ except BaseException:+ record(self.root, 'unknown')+ raise+ # Only a started process is running, with its own identity.+ record(self.root, 'running', started_at=row['started'], shapes=[], pid=process.pid)while process.poll() is None:if busy():self.stop()@@ -178,7 +202,14 @@ class BackgroundCompile:row.update(returncode=process.poll(), seconds=time.time() - row['started'])from .precompile import BUSY_EXITif not stopped and row['returncode'] != BUSY_EXIT:+ receipt, _ = read(self.root / 'precompile.json', 2 * 2**20)+ record(self.root, 'complete' if row['returncode'] == 0 and receipt.get('success') is True+ else 'unknown')return # Compiled, or failed with a receipt that says why.+ if not stopped:+ # The child normally wrote the resource reason. Keep it even+ # if the child exited before publishing diagnostic status.+ record(self.root, 'not_started')COMPILE = BackgroundCompile()diff --git a/freevideo_engine/diagnostic_resources.py b/freevideo_engine/diagnostic_resources.pyindex d819861..ea57cff 100644--- a/freevideo_engine/diagnostic_resources.py+++ b/freevideo_engine/diagnostic_resources.py@@ -156,6 +156,50 @@ def encoder_prewarm(value):return result+PRECOMPILE_REASONS = ('idle_delay', 'session_busy', 'foreground_work',+ 'ram_pressure', 'gpu_busy', 'gpu_memory_pressure', 'gpu_processes_unavailable',+ 'gpu_in_use', 'lease_busy', 'unknown')+++def precompile_shape(value):+ """Allowlisted request shape only, never cache/conditioning/model paths."""+ value = mapping(value)+ result = {key: value[key] for key in ('width', 'height', 'frames', 'base_steps', 'refine_steps')+ if type(value.get(key)) is int and value[key] > 0}+ if not all(key in result for key in ('width', 'height', 'frames')):+ return {}+ if value.get('task') in ('t2va', 'fl2va', 'ref2va'):+ result['task'] = value['task']+ if type(value.get('two_pass')) is bool:+ result['two_pass'] = value['two_pass']+ result.update({key: number for key, number in numbers(value, ('upscale_factor',)).items() if number > 0})+ tokens = sequence(value.get('text_tokens'))[:8]+ if tokens and all(type(n) is int and n > 0 for n in tokens):+ result['text_tokens'] = list(tokens)+ return result+++def precompile(value):+ """Fresh bounded structure for local and uploaded precompile evidence."""+ value = mapping(value)+ state = value.get('state')+ result = dict(state=state if state in ('complete', 'running', 'not_started', 'unknown') else 'unknown',+ covered_shapes=[], scope='installation_snapshot')+ for row in sequence(value.get('covered_shapes'))[:16]:+ shape = precompile_shape(row)+ if shape and shape not in result['covered_shapes']:+ result['covered_shapes'].append(shape)+ result.update(numbers(value, ('updated_at', 'started_at')))+ if value.get('receipt') in ('available', 'missing', 'invalid'):+ result['receipt'] = value['receipt']+ last = mapping(value.get('last_postpone'))+ at = numbers(last, ('at',))+ if at:+ result['last_postpone'] = dict(at, reason=last.get('reason')+ if last.get('reason') in PRECOMPILE_REASONS else 'unknown')+ return result++def embedding(value):"""Tensor metadata only: no indices, tensor values, prompt or media content."""value = mapping(value)@@ -323,7 +367,14 @@ def kernel_receipt(value):def numbers(value, keys):value = mapping(value)return {k: value[k] for k in keys if type(value.get(k)) in (int, float)- and math.isfinite(value[k]) and value[k] >= 0}+ and finite(value[k]) and value[k] >= 0}+++def finite(number):+ try:+ return math.isfinite(number)+ except OverflowError: # An int beyond the float range, e.g. 10**400.+ return Falsedef weight_placement(value):diff --git a/freevideo_engine/diagnostic_summary.py b/freevideo_engine/diagnostic_summary.pyindex cac5df2..3433864 100644--- a/freevideo_engine/diagnostic_summary.py+++ b/freevideo_engine/diagnostic_summary.py@@ -32,6 +32,7 @@ def summary_report(report):result = dict(kind='generation', status=summary.get('status') if summary.get('status') in('complete', 'reused', 'retrying', 'running') else 'incomplete',version=__version__, hardware={}, config={}, geometry={}, memory={}, stages=[], steps=[], errors=[])+ result['precompile'] = diagnostic.precompile(summary.get('precompile'))for k in ('gpu_name', 'system', 'architecture', 'driver_version', 'torch_version', 'cuda_version'):if _label(hardware.get(k)):result['hardware'][k] = hardware[k]diff --git a/freevideo_engine/precompile.py b/freevideo_engine/precompile.pyindex 99d6cc6..11da79b 100644--- a/freevideo_engine/precompile.py+++ b/freevideo_engine/precompile.py@@ -53,7 +53,7 @@ OWNER_ENV = 'FREEVIDEO_BACKGROUND_OWNER'class GiveWay(BlockingIOError):- """The user's other programs need the memory or the GPU: stop without a receipt."""+ """The user's other programs need memory/GPU: leave the cache receipt intact."""# Set when the interactive session stops a background run. A signal can land@@ -184,6 +184,8 @@ def run(machine, *, environment=None, timeout=TIMEOUT_SECONDS, background=False,own_temporary_environment(root)environment = temporary_environment(root, environment)receipt = dict(success=False, started=time.time(), shapes=[])+ from .precompile_state import record+ record(root, 'running', started_at=receipt['started'], shapes=[])if machine.get('gpu_vendor') == 'amd':# Not measured on AMD GPUs yet; their first request compiles as before.return dict(receipt, skipped=True, reason='AMD GPU')@@ -208,6 +210,7 @@ def run(machine, *, environment=None, timeout=TIMEOUT_SECONDS, background=False,and previous.get('caches') == receipt['caches'] and marked(receipt['caches'], previous.get('started'))):# Same code, packages, GPU, request shapes, plan inputs and compiler# caches, which still hold what that run wrote: nothing to compile.+ record(root, 'complete', shapes=previous.get('shapes'))return dict(previous, skipped=True)checkpoint()room = None@@ -365,6 +368,8 @@ def compile_shapes(machine, shapes, history, identity, receipt, environment, timfor sample in row.get('worker', {}).get('passes', ()):if 'conditioning' in sample:sample['conditioning'] = launch_view.value(sample['conditioning'], back)+ from .precompile_state import record+ record(root, 'running', started_at=receipt['started'], shapes=receipt['shapes'])# A stop arriving after the last worker finished finds the work done; the# receipt records it, so the next start does not compile it again.receipt['success'] = all(row.get('returncode') == 0 for row in receipt['shapes'])@@ -374,6 +379,8 @@ def compile_shapes(machine, shapes, history, identity, receipt, environment, timif receipt['success']:mark(receipt['caches'], receipt['started'])save(root / 'precompile.json', receipt)+ from .precompile_state import record+ record(root, 'complete' if receipt['success'] else 'unknown', shapes=receipt['shapes'])return receipt@@ -539,7 +546,7 @@ def main(argv=None):def stopped(signum, frame):# Stopped by the interactive session: give way at the next# checkpoint, stopping the children and removing temporary folders- # on the way out, without a receipt.+ # on the way out, leaving the cache receipt intact.CANCELLED.set()termination_handler(stopped)try:@@ -553,12 +560,19 @@ def main(argv=None):receipt = run(machine, background=args.background, owner=int(owner) if owner else None)except Exception as error:if args.background and isinstance(error, BlockingIOError):- # The GPU or memory is in use: no receipt, so the next idle start tries again.+ # Only diagnostic status changes; the next idle start still tries again.+ from .precompile_state import flush, record, reason_code+ record(machine['root'], 'not_started', reason=reason_code(error)+ if isinstance(error, GiveWay) else 'lease_busy')+ flush(cancelled=CANCELLED) # A stop must not wait for diagnostic I/O.print(json.dumps(dict(event='give_way', reason=str(error), at=time.time())), flush=True)return BUSY_EXIT# FreeVideo works either way; record why.receipt = dict(success=False, error=repr(error))save(Path(machine['root']) / 'precompile.json', receipt)+ from .precompile_state import flush, record+ record(machine['root'], 'complete' if receipt.get('success') else 'unknown', shapes=receipt.get('shapes', []))+ flush(cancelled=CANCELLED)print(json.dumps({key: receipt.get(key) for key in ('success', 'skipped', 'seconds')}))return 0diff --git a/freevideo_engine/precompile_state.py b/freevideo_engine/precompile_state.pynew file mode 100644index 0000000..3690fca--- /dev/null+++ b/freevideo_engine/precompile_state.py@@ -0,0 +1,211 @@+"""Best-effort precompile observations, separate from cache-validity receipts.++Nothing in the scheduler reads this file to decide whether or what to compile.+Only fixed states, reason codes, numeric shape keys and process identity live+here. Process identity stays local and prevents a crashed run looking active.+"""+import collections+import json+import os+from pathlib import Path+import threading+import time+from time import monotonic++from . import diagnostic_resources as diagnostic+from .diagnostics import read_bounded+from .locking import runtime_lock+from .long_paths import io_path+from .monitoring import save++FILENAME = 'precompile_state.json'+++def read(path, limit):+ try:+ raw, truncated = read_bounded(path, limit)+ value = json.loads(raw) if not truncated else None+ return (value, 'available') if isinstance(value, dict) else ({}, 'invalid')+ except FileNotFoundError:+ return {}, 'missing'+ except Exception:+ return {}, 'invalid'+++def reason_code(error):+ """Classify existing GiveWay messages; never persist their free text."""+ text = str(error)+ if text == 'stopped by FreeVideo':+ return 'foreground_work'+ for prefix, code in (('memory:', 'ram_pressure'), ('gpu busy:', 'gpu_busy'),+ ('gpu memory:', 'gpu_memory_pressure'),+ ('gpu: its processes cannot be listed', 'gpu_processes_unavailable'),+ ('gpu: another program started', 'gpu_in_use'),+ ('gpu: another program keeps it busy', 'gpu_busy')):+ if text.startswith(prefix):+ return code+ return 'unknown'+++# Callers hold the compile guard or the runtime lease, so they only queue a+# change; one daemon thread does the file I/O in the order changes were made.+_queue = collections.deque()+_wake = threading.Condition()+_writer = None+_queued = _written = 0+_final = set() # Roots whose last change for this process has been queued.+++def record(root, state, *, reason=None, started_at=None, shapes=None, pid=None, final=False):+ """Diagnostic writes must never change compilation, cancellation or retries.++ `final` marks the session's last word: later non-final changes from this+ process are dropped, so a racing idle wait cannot overwrite a stop.+ """+ global _queued, _writer+ if root is None:+ return+ try:+ change = dict(root=Path(root), state=state, reason=reason, started_at=started_at, at=time.time(),+ shapes=None if shapes is None else covered_shapes(shapes),+ pid=(pid or os.getpid()) if state == 'running' else None)+ with _wake:+ if change['root'] in _final and not final:+ return+ if final:+ _final.add(change['root'])+ _queued += 1+ change['sequence'] = _queued+ _queue.append(change)+ if _writer is None:+ _writer = threading.Thread(target=_write, name='FreeVideo precompile status', daemon=True)+ _writer.start()+ _wake.notify_all()+ except Exception:+ pass+++def flush(timeout=1., *, cancelled=None):+ """Wait up to `timeout` seconds for queued changes, yielding to cancellation."""+ deadline = monotonic() + timeout+ with _wake:+ target = _queued+ while _written < target:+ if cancelled is not None and cancelled.is_set():+ return False+ remaining = deadline - monotonic()+ if remaining <= 0:+ return False+ _wake.wait(min(remaining, .02) if cancelled is not None else remaining)+ return True+++def _write():+ global _written+ while True:+ with _wake:+ while not _queue:+ _wake.wait()+ change = _queue.popleft()+ try:+ _apply(change)+ except Exception:+ pass+ with _wake:+ _written = change['sequence']+ _wake.notify_all()+++def _apply(change):+ path = change['root'] / FILENAME+ # Lock a stable sibling: save() replaces the JSON inode. Only this daemon+ # waits for other writers; never inherit or acquire the compilation lease.+ with runtime_lock(io_path(path.with_suffix('.json.lock')), inherit=False, wait_seconds=60.):+ previous, _ = read(path, 64 * 1024)+ value = diagnostic.precompile(previous)+ # Compare and replace under the same cross-process lock, so an older+ # observation cannot overwrite a newer stop or move its timestamp back.+ if value.get('updated_at', 0) > change['at']:+ return+ value.update(schema_version=1, state=change['state'], updated_at=change['at'])+ if change['started_at'] is not None:+ value['started_at'] = change['started_at']+ if change['shapes'] is not None:+ value['covered_shapes'] = change['shapes']+ if change['reason'] is not None:+ value['last_postpone'] = dict(reason=change['reason'] if change['reason'] in diagnostic.PRECOMPILE_REASONS+ else 'unknown', at=change['at'])+ if change['pid'] is not None:+ try:+ import psutil+ value.update(pid=change['pid'], created=psutil.Process(change['pid']).create_time())+ except Exception:+ pass # Exited already: without an identity the state reads as unknown.+ save(path, value)+++def covered_shapes(rows):+ return [shape for row in diagnostic.sequence(rows)[:16]+ if type(diagnostic.mapping(row).get('returncode')) is int and row['returncode'] == 0+ if (shape := diagnostic.precompile_shape(row.get('shape')))]+++def collect(root=None):+ """Read bounded files only; no GPU queries, cache probes or tensor imports."""+ if root is None:+ from .system import install_root+ root = install_root()+ # The ComfyUI parent can select a separate engine through comfyui.json+ # without setting FREEVIDEO_HOME in its own process. Match the bridge's+ # selection, including paths relative to the source checkout.+ if not os.environ.get('FREEVIDEO_HOME'):+ source = Path(__file__).resolve().parents[1]+ config, _ = read(source / 'comfyui.json', 64 * 1024)+ selected = config.get('installation')+ if isinstance(selected, str) and selected.strip():+ root = Path(selected).expanduser()+ if not root.is_absolute():+ root = source / root+ receipt, receipt_status = read(Path(root) / 'precompile.json', 2 * 2**20)+ activity, activity_status = read(Path(root) / FILENAME, 64 * 1024)+ result = dict(state='not_started' if receipt_status == activity_status == 'missing' else 'unknown',+ covered_shapes=covered_shapes(receipt.get('shapes')), receipt=receipt_status,+ scope='installation_snapshot')+ rows = receipt.get('shapes')+ complete = (receipt.get('success') is True and isinstance(rows, list)+ and 0 < len(rows) == len(result['covered_shapes']))+ if complete:+ result['state'] = 'complete'+ if activity.get('schema_version') == 1:+ current = diagnostic.precompile(activity)+ # A receipt published after the last activity write wins (for example+ # if the process exited between saving its receipt and saving status).+ finished = diagnostic.numbers(receipt, ('started', 'seconds'))+ completed_at = finished.get('started', 0) + finished.get('seconds', 0)+ newer_receipt = complete and completed_at > current.get('updated_at', 0)+ shapes = result['covered_shapes']+ if not newer_receipt:+ result.update(current)+ if result['state'] == 'running' and not active(activity):+ result['state'] = 'unknown'+ for shape in current['covered_shapes']:+ if shape not in shapes:+ shapes.append(shape)+ result['covered_shapes'] = shapes+ if current.get('last_postpone'):+ result['last_postpone'] = current['last_postpone']+ if result['state'] == 'complete' and not complete:+ result['state'] = 'unknown'+ return diagnostic.precompile(result)+++def active(value):+ try:+ import psutil+ if type(value.get('pid')) is not int or value['pid'] <= 0:+ return False+ process = psutil.Process(value['pid'])+ return (process.create_time() == value.get('created') and process.is_running()+ and process.status() != psutil.STATUS_ZOMBIE)+ except Exception:+ return Falsediff --git a/freevideo_engine/support_report.py b/freevideo_engine/support_report.pyindex 7a082c9..6f3f665 100644--- a/freevideo_engine/support_report.py+++ b/freevideo_engine/support_report.py@@ -458,6 +458,14 @@ def write(output, report=None, bridge=None, *, _retry=None, live=False, restarteif not request.get('encoding_resources'):request['encoding_resources'] = dict(ram=read_json('.encoding.memory.json'))summary = summarize(request, engine, encoding)+ try:+ from .precompile_state import collect as precompile_status+ precompile = precompile_status()+ except Exception:+ # Status collection is optional even when the installation is broken.+ from .diagnostic_resources import precompile as sanitize_precompile+ precompile = sanitize_precompile(None)+ summary['precompile'] = precompileif live and not restarted and bridge.get('status') in ('starting', 'running'):summary['status'] = 'running'if bridge.get('status') == 'reused':@@ -575,6 +583,9 @@ def write(output, report=None, bridge=None, *, _retry=None, live=False, restartesuffix = ('.encoder-retry-' if encoder_retry else '.retry-') + str(_retry['index']) + '.debug.json'target = output.with_suffix(suffix)cleaned = clean(payload)+ # Like token_summary, text_tokens is numeric shape metadata; restore+ # only this allowlisted section after the generic secret redactor.+ cleaned['summary']['precompile'] = precompileif timeline is not None:# Counter slashes in fixed label keys look like paths to the text# scrubber. Restore only the receipt already validated above.