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.

Slow-drive model read-ahead; launcher updates read the published release files

Bowen Xuec25c9e0708f9
diff --git a/freevideo_engine/comfy_updates.py b/freevideo_engine/comfy_updates.py
index 95ace1b..cfcad47 100644
--- a/freevideo_engine/comfy_updates.py
+++ b/freevideo_engine/comfy_updates.py
@@ -61,6 +61,7 @@ class UpdateStatus:
self.client_seen = -1e9
self.lock = threading.Lock()
self.thread = None
+ self.failures = 0
def launcher(self):
if not self.bridge:
@@ -110,13 +111,18 @@ class UpdateStatus:
available = public_details(candidate) if newer else None
with self.lock:
self.state.update(status='available' if available else 'current', available=available)
+ self.failures = 0
self.next_check = time.monotonic() + 15 * 60
- except Exception:
+ except Exception as error:
# Offline/rate-limited checks must not interrupt a running server.
# Keep a previously verified notice and retry without a user action.
with self.lock:
+ self.failures += 1
self.state['status'] = 'unavailable'
- self.next_check = time.monotonic() + 60
+ delay = max(min(launcher_update.MAX_RETRY_SECONDS,
+ launcher_update.RETRY_SECONDS * 2**min(self.failures - 1, 4)),
+ launcher_update.retry_after(error))
+ self.next_check = time.monotonic() + delay
def register():
diff --git a/freevideo_engine/encode_worker.py b/freevideo_engine/encode_worker.py
index 2f0a92b..5744ba3 100644
--- a/freevideo_engine/encode_worker.py
+++ b/freevideo_engine/encode_worker.py
@@ -187,6 +187,33 @@ def stop_read_ahead(trace):
trace.data['encoder_read_ahead'] = reader.close()
+def start_model_read_ahead(trace, request):
+ """On a slow drive, read the video model's files while the encoder computes.
+
+ Speculative and bounded like the checkpoint reader: any failure leaves the
+ model load exactly as before. Once per request."""
+ cache = request.get('model_cache')
+ if not cache or getattr(trace, 'model_read_ahead', None) is not None or 'model_read_ahead' in trace.data:
+ return
+ try:
+ from .model_read_ahead import ModelReadAhead
+ # Recorded before the thread starts: an interrupt during start() still finds it to close.
+ reader = trace.model_read_ahead = ModelReadAhead(
+ cache=cache, resident_blocks=request.get('model_resident_blocks'), headroom_bytes=request.get('model_headroom_bytes'),
+ ram_budget_bytes=request.get('ram_budget_bytes'),
+ budget_is_estimate=bool(request.get('ram_budget_is_estimate')))
+ reader.start()
+ except Exception as error:
+ trace.data['model_read_ahead'] = dict(state='failed', reason=type(error).__name__ + ': ' + str(error))
+
+
+def stop_model_read_ahead(trace):
+ """Stop the model read-ahead, once, and keep what it read in the metrics."""
+ reader = getattr(trace, 'model_read_ahead', None)
+ if reader is not None and 'model_read_ahead' not in trace.data:
+ trace.data['model_read_ahead'] = reader.close()
+
+
def encode(args, request, resident=None, diagnostics=None):
from .encoder_diagnostics import EncoderTrace
trace = diagnostics or EncoderTrace(request, resident=resident is not None)
@@ -194,9 +221,11 @@ def encode(args, request, resident=None, diagnostics=None):
metrics = _encode(args, request, resident, trace)
except BaseException:
stop_read_ahead(trace)
+ stop_model_read_ahead(trace)
trace.finish(False)
raise
stop_read_ahead(trace)
+ stop_model_read_ahead(trace)
result = trace.finish(True, metrics)
if not args.check_library and not request.get('idle_preload'):
print(json.dumps({'event': 'encoder_complete', **result}), flush=True)
@@ -383,6 +412,9 @@ def _encode(args, request, resident, trace):
checkpoint_paths = [path]
def timed_load(*values, **kwargs):
phase('encoder_device_load', load_seconds=load_seconds)
+ # A retry copies the encoder again: the model's reader, started after
+ # the first copy, ends first and is not started a second time.
+ stop_model_read_ahead(trace)
if not encoder_cache_hit:
# Only for the copy: reads that overlapped the library import or
# the model's construction slowed them (see encoder_read_ahead).
@@ -396,6 +428,8 @@ def _encode(args, request, resident, trace):
result = native_load(*values, **kwargs)
torch.cuda.synchronize()
stop_read_ahead(trace)
+ if not encoder_cache_hit:
+ start_model_read_ahead(trace, request)
transfer_seconds[0] += time.perf_counter() - tick
phase('encoder_page_release', device_load_seconds=transfer_seconds[0])
# The checkpoint's pages are dead weight once its weights are on the
@@ -492,6 +526,8 @@ def _encode(args, request, resident, trace):
value['task'] = task
torch.cuda.synchronize()
prompt_encode_seconds = time.perf_counter() - encode_started
+ # Keyframe and reference-media encoding read the drive themselves.
+ stop_model_read_ahead(trace)
keyframe_metrics = {}
if images is not None:
phase('keyframe_vae')
diff --git a/freevideo_engine/encoder_diagnostics.py b/freevideo_engine/encoder_diagnostics.py
index 3f48aea..7054b13 100644
--- a/freevideo_engine/encoder_diagnostics.py
+++ b/freevideo_engine/encoder_diagnostics.py
@@ -28,7 +28,7 @@ def cached_metrics(value):
value.update({key: 0. for key in timings})
value['cache_source_metrics'] = {key: value.pop(key) for key in ('timing', 'runtime',
'load_stages', 'gpu', 'checkpoint', 'encoder_attempts', 'token_summary', 'cast_buffers',
- 'resident_encoder_cache_hit', 'resident_encoder_gpu_ready_at_start') if key in value}
+ 'resident_encoder_cache_hit', 'resident_encoder_gpu_ready_at_start', 'model_read_ahead') if key in value}
value.pop('phase', None)
return value
diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.py
index d2137e5..758b8d5 100644
--- a/freevideo_engine/generate.py
+++ b/freevideo_engine/generate.py
@@ -596,6 +596,11 @@ def _run(args):
'diagnostic_output': str(destination)}
if media:
encoding.update(media=media, geometry=canvas, base=profile['engine'].get('base'))
+ # Lets the encoder child read the video model while it computes, on a slow drive.
+ from .model_read_ahead import request_fields
+ if getattr(args, 'cache', None):
+ encoding.update(request_fields(args.cache, profile['engine'],
+ budget_is_estimate=ram_budget_is_estimate(args)))
conditioning_key = cache_key(encoding['prompt'], media, canvas)
encode_request = temporary / 'encode.json'
encode_request.write_text(json.dumps(encoding) + '\n', encoding='utf-8')
diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml
index 8947803..3a1b1b4 100644
--- a/freevideo_engine/launcher/Main.qml
+++ b/freevideo_engine/launcher/Main.qml
@@ -770,7 +770,8 @@ ApplicationWindow {
}
FMeter { visible: s.update.phase === "downloading"; Layout.fillWidth: true; fraction: s.update.progress && s.update.progress.total ? s.update.progress.done / s.update.progress.total : -1; active: visible }
FText { visible: !s.update.phase && !!text; text: releaseSummary(availableRelease); Layout.fillWidth: true; color: theme.muted; font.pixelSize: theme.micro }
- FButton { text: t("What's new", "更新内容"); flat: true; visible: !s.update.phase; implicitHeight: theme.heightSm; onClicked: releaseNotesOpen = true }
+ FButton { text: t("What's new", "更新内容"); flat: true; visible: !s.update.phase && !!availableRelease; implicitHeight: theme.heightSm; onClicked: releaseNotesOpen = true }
+ FButton { objectName: "updateBannerManualDownload"; text: t("Download from the release page ↗", "去发布页手动下载 ↗"); flat: true; visible: s.update.status === "error" && !!s.update.release_page; implicitHeight: theme.heightSm; onClicked: backend.link(s.update.release_page) }
}
FCard {
objectName: "modelUpgradeCard"
@@ -1256,19 +1257,19 @@ ApplicationWindow {
id: updateContents; width: updateScroll.availableWidth
spacing: 14
FText { text: s.update.candidate ? t("Update available", "有可用更新") : s.update.engine ? t("Engine update", "引擎更新") : t("Updates", "更新"); font.pixelSize: theme.section + 2; font.weight: Font.DemiBold }
- FText { objectName: "updateDialogText"; text: s.update.phase === "waiting" ? t("A video is still generating. FreeVideo restarts and updates as soon as it finishes.", "还有视频正在生成,完成后会自动重启并更新。") : s.update.status === "ready" && s.update.candidate ? t("Downloaded. Restart to finish; models and settings are kept.", "下载完成,重启即可完成更新,模型和设置都会保留。") : s.update.candidate ? t("FreeVideo ", "FreeVideo ") + releaseVersion(s.update.candidate) + t(" is available (current ", " 已发布(当前 ") + releaseVersion(currentRelease) + t("). Updating keeps your models and settings. FreeVideo restarts after the download; running videos finish first.", ")。更新会保留模型和设置,下载完成后自动重启;正在生成的视频会先完成。") : s.update.engine ? t("This launcher already includes engine ", "启动器已带有新版引擎 ") + releaseVersion(currentRelease) + t(" (installed: ", "(已安装 ") + engineVersion + (s.status === "open" ? t("). Updating takes about a minute, restarts ComfyUI once and keeps your models and settings.", ")。更新约需 1 分钟,会重启一次 ComfyUI,模型和设置都会保留。") : t("). Updating takes about a minute, then FreeVideo starts; models and settings are kept.", ")。更新约需 1 分钟,完成后自动启动,模型和设置都会保留。")) : s.update.status === "current" ? t("You're up to date.", "已是最新版本。") : s.update.status === "development" ? t("Running from source. Update with Git.", "当前从源码运行,请通过 Git 更新。") : s.update.status === "error" ? t("Couldn't check for updates. Try again below.", "暂时无法检查更新,请重试。") : t("Checking the latest release…", "正在检查最新版本…"); color: theme.muted; Layout.fillWidth: true }
+ FText { objectName: "updateDialogText"; text: s.update.phase === "waiting" ? t("A video is still generating. FreeVideo restarts and updates as soon as it finishes.", "还有视频正在生成,完成后会自动重启并更新。") : s.update.status === "ready" && s.update.candidate ? t("Downloaded. Restart to finish; models and settings are kept.", "下载完成,重启即可完成更新,模型和设置都会保留。") : s.update.candidate ? t("FreeVideo ", "FreeVideo ") + releaseVersion(s.update.candidate) + t(" is available (current ", " 已发布(当前 ") + releaseVersion(currentRelease) + t("). Updating keeps your models and settings. FreeVideo restarts after the download; running videos finish first.", ")。更新会保留模型和设置,下载完成后自动重启;正在生成的视频会先完成。") : s.update.engine ? t("This launcher already includes engine ", "启动器已带有新版引擎 ") + releaseVersion(currentRelease) + t(" (installed: ", "(已安装 ") + engineVersion + (s.status === "open" ? t("). Updating takes about a minute, restarts ComfyUI once and keeps your models and settings.", ")。更新约需 1 分钟,会重启一次 ComfyUI,模型和设置都会保留。") : t("). Updating takes about a minute, then FreeVideo starts; models and settings are kept.", ")。更新约需 1 分钟,完成后自动启动,模型和设置都会保留。")) : s.update.status === "current" ? t("You're up to date.", "已是最新版本。") : s.update.status === "development" ? t("Running from source. Update with Git.", "当前从源码运行,请通过 Git 更新。") : s.update.status === "error" ? t("Could not check for updates.", "暂时无法检查更新。") : t("Checking the latest release…", "正在检查最新版本…"); color: theme.muted; Layout.fillWidth: true }
FMeter { Layout.fillWidth: true; visible: s.update.status === "downloading"; active: true; fraction: s.update.progress && s.update.progress.total ? s.update.progress.done/s.update.progress.total : -1 }
FReleaseNotes { objectName: "updateReleaseNotes"; visible: !!availableRelease; Layout.fillWidth: true; release: availableRelease; earlier: availableEarlier; zh: s.zh; heading: t("What's new", "更新内容") + " · " + releaseVersion(availableRelease) }
FButton { text: t("Version & release notes", "版本与更新说明"); flat: true; onClicked: releaseNotesOpen = true }
FText { visible: !!s.update.error; text: s.update.error || ""; color: theme.danger; Layout.fillWidth: true; font.pixelSize: theme.micro }
- FField { id: githubToken; visible: !!s.update.error; Layout.fillWidth: true; echoMode: TextInput.Password; placeholderText: t("GitHub token · optional", "GitHub Token · 可选") }
+ FButton { objectName: "updateManualDownloadButton"; text: t("Download from the release page ↗", "去发布页手动下载 ↗"); flat: true; Layout.fillWidth: true; visible: s.update.status === "error" && !!s.update.release_page; onClicked: backend.link(s.update.release_page) }
}
}
RowLayout {
id: updateActions; Layout.fillWidth: true
FButton { objectName: "updateLaterButton"; text: s.update.candidate || s.update.engine ? t("Later", "稍后更新") : t("Close", "关闭"); flat: true; onClicked: { manualUpdate = false; backend.dismissUpdate() } }
Item { Layout.fillWidth: true }
- FButton { objectName: "updateNowButton"; text: s.update.status === "error" ? t("Retry update", "重试更新") : s.update.status === "ready" && s.update.candidate ? t("Restart & update", "重启并更新") : s.update.candidate || s.update.engine ? t("Update now", "立即更新") : t("Check again", "重新检查"); primary: true; enabled: ["checking","downloading"].indexOf(s.update.status) < 0 && s.update.phase !== "waiting"; onClicked: { manualUpdate = !!s.update.candidate || !s.update.engine; backend.update(githubToken.text) } }
+ FButton { objectName: "updateNowButton"; text: s.update.status === "error" ? t("Retry update", "重试更新") : s.update.status === "ready" && s.update.candidate ? t("Restart & update", "重启并更新") : s.update.candidate || s.update.engine ? t("Update now", "立即更新") : t("Check again", "重新检查"); primary: true; enabled: ["checking","downloading"].indexOf(s.update.status) < 0 && s.update.phase !== "waiting"; onClicked: { manualUpdate = !!s.update.candidate || !s.update.engine; backend.update("") } }
}
}
}
diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py
index c9905cf..3214463 100644
--- a/freevideo_engine/launcher_session.py
+++ b/freevideo_engine/launcher_session.py
@@ -740,8 +740,10 @@ class Session:
self.update_snoozed = dict(self.update_snoozed, **{key: time.monotonic() + SNOOZE_SECONDS})
self.update_intent = None
self.update_waiting = False
- if self.updater and self.updater.state['status'] == 'downloading':
+ if self.updater and (self.updater.state['status'] == 'downloading'
+ or self.updater.state.get('retry_operation') == 'download'):
self.updater.cancelled.set()
+ self.updater.stop()
def _unsnooze(self):
key = self.update_key()
@@ -888,7 +890,10 @@ class Session:
def _tick_updates(self):
now = time.monotonic()
updater = self.updater
+ if updater:
+ updater.poll(allow_download=not (self.controller.busy or self.importer.busy or self.cleaner.busy))
if (updater and self.update_intent is None and not updater.busy and now - self.update_checked >= CHECK_SECONDS
+ and not updater.retry
and updater.state.get('status') in ('idle', 'current', 'available', 'error', 'cancelled')):
self.update_checked = now
updater.run('check', background=True)
@@ -913,7 +918,7 @@ class Session:
elif self.update_intent == 'launcher' and updater and not updater.busy:
if row.get('status') == 'ready':
self._restart_when_idle()
- elif row.get('status') != 'downloading':
+ elif row.get('status') != 'downloading' and not row.get('retry_at'):
self.update_intent, self.update_waiting = None, False
elif self.update_intent == 'engine':
self._update_engine_when_idle()
@@ -1026,6 +1031,10 @@ class Session:
row = dict(self.updater.state) if self.updater else dict(status='development')
# Only display fields from the update manifest, never access tokens.
view = {k: row[k] for k in ('status', 'error', 'progress', 'candidate') if k in row}
+ from .launcher_update import error_text, release_page
+ if row.get('error_code'):
+ view['error'] = error_text(row, self.language.startswith('zh'))
+ view['release_page'] = release_page(self.updater.current) if self.updater else ''
key = self.update_key()
view.update(engine=self.engine_update_pending(), current=__version__,
current_release=public_details(self.updater.current) if self.updater else self.release_details,
diff --git a/freevideo_engine/launcher_update.py b/freevideo_engine/launcher_update.py
index 802ed83..290d5ce 100644
--- a/freevideo_engine/launcher_update.py
+++ b/freevideo_engine/launcher_update.py
@@ -4,6 +4,7 @@ Executables live in a versioned user cache. The original EXE stays intact and
forwards to a newer, explicitly approved download on subsequent starts.
"""
import hashlib
+from email.utils import parsedate_to_datetime
import json
import os
from pathlib import Path
@@ -17,9 +18,8 @@ import urllib.parse
import urllib.request
from . import execution_paths
-from .diagnostics import Redactor
from .monitoring import save
-from .long_paths import io_path, resolved, plain, plain_text, plain_errors
+from .long_paths import io_path, resolved, plain, plain_errors
from . import disk_space
REPOSITORY = 'FlashML-org/FreeVideo'
@@ -27,7 +27,8 @@ REPOSITORY = 'FlashML-org/FreeVideo'
# these tags, which the release workflow keeps up to date for them.
CHANNEL = 'windows-preview'
API = 'https://api.github.com/repos/' + REPOSITORY
-RELEASE_PAGE = 'https://github.com/' + REPOSITORY + '/releases/latest'
+WEB = 'https://github.com/' + REPOSITORY
+RELEASE_PAGE = WEB + '/releases/latest'
MAX_EXE_BYTES = 512 * 2**20
MAC_CHANNEL = 'macos-preview'
# Linux has no release before combined releases, so no platform tag to fall back on.
@@ -40,6 +41,88 @@ RELEASE_ASSETS = {CHANNEL: ('FreeVideo.exe', 'update-windows.json'),
MAC_CHANNEL: ('FreeVideo-Mac-arm64.dmg', 'update-macos.json'),
LINUX_CHANNEL: ('FreeVideo-Linux-x86_64.AppImage', 'update-linux.json')}
CHANNELS = tuple(RELEASE_ASSETS)
+RETRY_SECONDS = 60
+MAX_RETRY_SECONDS = 15 * 60
+MAX_DOWNLOAD_RETRIES = 3
+# No answer may postpone the next attempt beyond the service's own hourly window.
+MAX_SERVER_WAIT_SECONDS = 3600
+# Every released launcher stops reading update metadata at this size.
+MAX_MANIFEST_BYTES = 65536
+_api_retry_at = 0.
+
+
+class UpdateUnavailable(OSError):
+ def __init__(self, kind, retry_after=0):
+ self.kind, self.retry_after = kind, retry_after
+ super().__init__('Update service temporarily unavailable')
+
+
+def retry_after(error):
+ """Respect GitHub's primary/secondary limit and HTTP Retry-After headers."""
+ if isinstance(error, UpdateUnavailable):
+ return error.retry_after
+ headers = {str(k).lower(): v for k, v in (getattr(error, 'headers', None) or {}).items()}
+ delays = [0]
+ value = headers.get('retry-after', '')
+ try:
+ delays.append(float(value))
+ except (ValueError, TypeError):
+ try:
+ delays.append(parsedate_to_datetime(value).timestamp() - time.time())
+ except (ValueError, TypeError, OverflowError):
+ pass
+ if headers.get('x-ratelimit-remaining') == '0':
+ try:
+ delays.append(float(headers.get('x-ratelimit-reset', '')) - time.time() + 1)
+ except (ValueError, TypeError):
+ pass
+ return min(MAX_SERVER_WAIT_SECONDS, max(d for d in delays if d == d))
+
+
+def failure_kind(error):
+ if isinstance(error, UpdateUnavailable):
+ return error.kind
+ if isinstance(error, urllib.error.HTTPError):
+ headers = {str(k).lower(): v for k, v in (error.headers or {}).items()}
+ if error.code == 429 or (error.code == 403 and
+ (headers.get('x-ratelimit-remaining') == '0' or headers.get('retry-after'))):
+ return 'rate_limited'
+ if error.code == 404:
+ return 'missing'
+ if error.code in (401, 403):
+ return 'blocked'
+ return 'connection' if isinstance(error, OSError) else 'invalid'
+
+
+def error_text(row, zh=False):
+ """Product copy stays separate from raw exceptions, URLs and credentials."""
+ messages = {
+ 'rate_limited': ('The update service is busy.', '更新服务繁忙。'),
+ 'missing': ('The files for the new version are still being published.', '新版本的文件还在发布中。'),
+ 'blocked': ('The update service could not be reached.', '无法访问更新服务。'),
+ 'connection': ('Could not connect to the download server.', '无法连接下载服务器。'),
+ 'invalid': ('The downloaded update files are incomplete or damaged.', '下载的更新文件不完整或已损坏。'),
+ 'disk': ('There is not enough disk space to download the update.', '磁盘空间不足,无法下载更新。'),
+ }
+ message = messages.get(row.get('error_code'))
+ if message is None:
+ return row.get('error', '') # Other frontend errors retain their own copy.
+ text = message[bool(zh)]
+ if row.get('retry_at'):
+ return text + ('稍后会自动重试,当前版本可以照常使用。' if zh else
+ ' FreeVideo will try again later. You can keep using the current version.')
+ return text + ('请重试,或去发布页手动下载。' if zh else
+ ' Try again, or download it from the release page.')
+
+
+def asset_url(tag, name):
+ return WEB + '/releases/download/' + urllib.parse.quote(tag, safe='') + '/' + name
+
+
+def _asset_url(candidate):
+ return candidate['asset'].get('url') or (asset_url(NIGHTLY_TAG, RELEASE_ASSETS[candidate['channel']][0])
+ if build_track(candidate) == 'nightly' else
+ RELEASE_PAGE + '/download/' + RELEASE_ASSETS[candidate['channel']][0])
def build_target(value):
@@ -52,7 +135,7 @@ def build_track(value):
def release_page(current):
- if build_track(build_identity(current)) == 'nightly':
+ if build_track(current) == 'nightly':
return 'https://github.com/' + REPOSITORY + '/releases/tag/' + NIGHTLY_TAG
return RELEASE_PAGE
@@ -105,9 +188,26 @@ def manifest(value):
or not re.fullmatch(r'[0-9a-f]{64}', str(asset.get('sha256', '')))):
raise ValueError('Invalid launcher update asset')
result['asset'] = {k: asset[k] for k in ('id', 'bytes', 'sha256')}
+ if download_address(asset.get('url'), result):
+ result['asset']['url'] = asset['url']
return result
+def download_address(url, build):
+ """Whether url is this platform's package on a tag of its own track.
+
+ The address is optional. One this build does not recognise is left out
+ rather than failing the update: size and SHA-256 still bind the package."""
+ prefix = WEB + '/releases/download/'
+ if not isinstance(url, str) or not url.startswith(prefix):
+ return False
+ parts = url[len(prefix):].split('/')
+ tags = (NIGHTLY_TAG,) if build_track(build) == 'nightly' else (build['channel'],)
+ return (len(parts) == 2 and parts[1] == RELEASE_ASSETS[build['channel']][0]
+ and (parts[0] in tags or (build_track(build) == 'stable'
+ and re.fullmatch(r'v\d+\.\d+\.\d+', parts[0]) is not None)))
+
+
def newer(candidate, current):
from .release_notes import older
return (build_target(candidate) == build_target(current)
@@ -138,15 +238,28 @@ class UpdateRedirect(urllib.request.HTTPRedirectHandler):
def open_download(url, token='', *, binary=False):
# One inherited route, then one direct route. Do not mutate shell, Git or
# registry proxies. Never retry a slow-but-active binary on another source.
- if not url.startswith(API + '/'):
- raise ValueError('Unexpected update API address')
+ global _api_retry_at
+ is_api = url.startswith(API + '/')
+ if not is_api and not (url.startswith(WEB + '/releases/download/')
+ or url.startswith(RELEASE_PAGE + '/download/')):
+ raise ValueError('Unexpected update download address')
+ _trusted_url(url)
+ if is_api and time.time() < _api_retry_at:
+ raise UpdateUnavailable('rate_limited', _api_retry_at - time.time())
for direct in (False, True):
opener = urllib.request.build_opener(urllib.request.ProxyHandler({} if direct else None), UpdateRedirect())
headers = {'User-Agent': 'FreeVideo-launcher', 'Accept': 'application/octet-stream' if binary else 'application/vnd.github+json'}
- if token:
+ if token and is_api:
headers['Authorization'] = 'Bearer ' + token
try:
return opener.open(urllib.request.Request(url, headers=headers), timeout=5)
+ except urllib.error.HTTPError as error:
+ if failure_kind(error) == 'rate_limited':
+ if is_api:
+ _api_retry_at = time.time() + max(RETRY_SECONDS, retry_after(error))
+ raise
+ if direct or error.code in (401, 404):
+ raise # Repeating a missing asset does not help; a blocked proxy may.
except (OSError, urllib.error.URLError):
if direct:
raise
@@ -181,7 +294,7 @@ def _release(token, channel, track):
if track == 'nightly':
release = _json(API + '/releases/tags/' + NIGHTLY_TAG, token)
if not isinstance(release, dict) or release.get('draft') or release.get('tag_name') != NIGHTLY_TAG:
- raise ValueError('No nightly build is published yet')
+ raise UpdateUnavailable('missing')
return release, executable, metadata
try:
release = _json(API + '/releases/latest', token)
@@ -193,32 +306,72 @@ def _release(token, channel, track):
if isinstance(release, dict) and not release.get('draft') and not release.get('prerelease') and metadata in names:
return release, executable, metadata
if channel == LINUX_CHANNEL:
- raise ValueError('No published update is available for this platform')
+ raise UpdateUnavailable('missing')
# Until the first combined release, updates come from the platform tag.
release = _json(API + '/releases/tags/' + channel, token)
if not isinstance(release, dict) or release.get('draft') or release.get('tag_name') != channel:
- raise ValueError('No published update is available for this platform')
+ raise UpdateUnavailable('missing')
return release, executable, 'update.json'
-def latest_release(token='', *, channel=CHANNEL, track='stable'):
- """Read and validate the published build without downloading an executable."""
- if channel not in CHANNELS:
- raise ValueError('Unknown launcher update channel')
- if track not in TRACKS:
- raise ValueError('Unknown launcher release track')
+def _api_latest_release(token, channel, track):
+ """Compatibility fallback for releases without directly readable metadata."""
release, executable_name, metadata_name = _release(token, channel, track)
assets = {a.get('name'): a for a in release.get('assets', []) if isinstance(a, dict)}
metadata, executable = assets.get(metadata_name, {}), assets.get(executable_name, {})
if type(metadata.get('id')) is not int:
- raise ValueError('Update metadata is not published yet; check the release page')
- candidate = manifest(_json(API + '/releases/assets/' + str(metadata['id']), token, binary=True, limit=65536))
+ raise UpdateUnavailable('missing')
+ candidate = manifest(_json(API + '/releases/assets/' + str(metadata['id']), token, binary=True, limit=MAX_MANIFEST_BYTES))
+ _selection(candidate, channel, track)
+ if candidate['asset']['id'] != executable.get('id') or candidate['asset']['bytes'] != executable.get('size'):
+ raise UpdateUnavailable('missing')
+ candidate['asset'].setdefault('url', asset_url(release['tag_name'], executable_name))
+ return manifest(candidate)
+
+
+def _fallback(primary, call):
+ """The API route after the direct one failed. The direct route needs no
+ quota, so a limited API does not decide when it is tried again."""
+ try:
+ return call()
+ except OSError as error:
+ if failure_kind(error) == 'rate_limited':
+ raise primary
+ raise
+
+
+def _selection(candidate, channel, track):
if candidate['channel'] != channel:
raise ValueError('Update metadata belongs to a different platform')
if build_track(candidate) != track:
raise ValueError('Update metadata belongs to a different release track')
- if candidate['asset']['id'] != executable.get('id') or candidate['asset']['bytes'] != executable.get('size'):
- raise ValueError('A new release is being published; check again shortly')
+
+
+def latest_release(token='', *, channel=CHANNEL, track='stable'):
+ """Read and validate the published build without downloading an executable."""
+ if channel not in CHANNELS:
+ raise ValueError('Unknown launcher update channel')
+ if track not in TRACKS:
+ raise ValueError('Unknown launcher release track')
+ metadata = RELEASE_ASSETS[channel][1]
+ url = (asset_url(NIGHTLY_TAG, metadata) if track == 'nightly' else
+ RELEASE_PAGE + '/download/' + metadata)
+ try:
+ candidate = manifest(_json(url, '', binary=True, limit=MAX_MANIFEST_BYTES))
+ except urllib.error.HTTPError as error:
+ if error.code == 404 and track == 'stable' and channel != LINUX_CHANNEL:
+ try:
+ candidate = manifest(_json(asset_url(channel, 'update.json'), '', binary=True, limit=MAX_MANIFEST_BYTES))
+ except OSError as legacy:
+ return _fallback(legacy, lambda: _api_latest_release(token, channel, track))
+ _selection(candidate, channel, track)
+ # Older manifests have no URL; keep their package on the same tag.
+ candidate['asset'].setdefault('url', asset_url(channel, RELEASE_ASSETS[channel][0]))
+ return candidate
+ return _fallback(error, lambda: _api_latest_release(token, channel, track))
+ except OSError as error:
+ return _fallback(error, lambda: _api_latest_release(token, channel, track))
+ _selection(candidate, channel, track)
return candidate
@@ -263,13 +416,16 @@ def download(candidate, root, token='', *, progress=None, cancel=None):
# Each attempt owns one stage. Failed stages cannot be resumed, so discard
# only ours; never touch another attempt, the original launcher or models.
import tempfile
- import shutil
if disk_space.free_bytes(target.parent) < asset['bytes'] + 16*2**20:
- raise OSError('Not enough disk space to download the launcher update')
+ raise UpdateUnavailable('disk')
start, done = time.monotonic(), 0
stage = None
try:
- with open_download(API + '/releases/assets/' + str(asset['id']), token, binary=True) as response:
+ try:
+ response = open_download(_asset_url(candidate), '', binary=True)
+ except OSError as error:
+ response = _fallback(error, lambda: open_download(API + '/releases/assets/' + str(asset['id']), token, binary=True))
+ with response:
with tempfile.NamedTemporaryFile(prefix='download-', suffix='.partial', dir=io_path(target.parent), delete=False) as stream:
stage = Path(plain(stream.name))
digest = hashlib.sha256()
@@ -404,13 +560,32 @@ class UpdateClient:
pass
self.thread = None
self.cancelled = threading.Event()
+ self.retry = None
+ self.failures = 0
@property
def busy(self):
return self.thread is not None and self.thread.is_alive()
- def run(self, operation, candidate=None, *, background=False):
- """A background check keeps the shown state and ignores offline failures."""
+ def stop(self):
+ self.cancelled.set()
+ self.retry = None
+ self.state = {k: v for k, v in self.state.items() if k not in ('retry_at', 'retry_operation')}
+ if self.state.get('error_code'):
+ self.state['error'] = error_text(self.state)
+
+ def poll(self, *, allow_download=True):
+ """UI ticks dispatch due retries; no sleeping worker blocks launch or close."""
+ if self.cancelled.is_set():
+ self.retry = None
+ if self.busy or not self.retry:
+ return
+ operation, candidate, at = self.retry
+ if time.time() >= at and (operation != 'download' or allow_download):
+ self.run(operation, candidate, background=operation == 'check', _retry=True)
+
+ def run(self, operation, candidate=None, *, background=False, _retry=False):
+ """Only an explicit download, or its bounded retry, fetches a package."""
if self.busy:
return
if operation not in ('check', 'download'):
@@ -419,29 +594,51 @@ class UpdateClient:
kind = 'application' if self.current.get('packaging') == 'app' else 'folder'
raise ValueError('Download and extract the updated %s ZIP from the release page' % kind)
self.cancelled.clear()
+ self.retry = None
+ if not _retry:
+ self.failures = 0
quiet = background and operation == 'check'
if not quiet:
self.state = dict(status='checking' if operation == 'check' else 'downloading', candidate=candidate)
def work():
+ selected = candidate
try:
if operation == 'check':
found = check(self.current, self.token)
+ if self.cancelled.is_set():
+ raise InterruptedError('Update check cancelled')
if found and (self.available is None or newer(found, self.available)):
self.available = found
save(self.root / 'updates/available.json', found)
self.state = dict(status='available' if self.available else 'current', candidate=self.available)
else:
+ if _retry and (not candidate['asset'].get('url') or build_track(candidate) == 'nightly'
+ or candidate['asset']['url'] == asset_url(candidate['channel'], RELEASE_ASSETS[candidate['channel']][0])):
+ # A rolling release or a legacy latest URL may have moved.
+ found = check(self.current, self.token)
+ if found and newer(found, candidate):
+ selected = found
def progress(value):
- self.state = dict(status='downloading', candidate=candidate, progress=value)
- download(candidate, self.root, self.token, progress=progress, cancel=self.cancelled)
- self.state = dict(status='ready', candidate=candidate)
+ self.state = dict(status='downloading', candidate=selected, progress=value)
+ download(selected, self.root, self.token, progress=progress, cancel=self.cancelled)
+ self.state = dict(status='ready', candidate=selected)
+ self.failures = 0
except Exception as error:
- if quiet:
- return # The next periodic check retries without a reminder.
- message = Redactor([(self.token, '<REDACTED>')] if self.token else []).text(plain_text(error))
- if isinstance(error, urllib.error.HTTPError) and error.code in (401, 403, 404):
- message = 'GitHub update access unavailable. A private repository needs a GitHub token with read access; also check API rate limits.'
- self.state = dict(status='cancelled' if self.cancelled.is_set() else 'error', error=message,
- candidate=candidate or self.available)
+ self.failures += 1
+ row = dict(status='cancelled' if self.cancelled.is_set() else 'error',
+ error_code=failure_kind(error), candidate=selected or self.available)
+ if (not self.cancelled.is_set() and row['error_code'] not in ('invalid', 'disk')
+ and (operation == 'check' or self.failures <= MAX_DOWNLOAD_RETRIES)):
+ delay = max(min(MAX_RETRY_SECONDS, RETRY_SECONDS * 2**min(self.failures - 1, 4)),
+ retry_after(error))
+ row['retry_at'] = time.time() + delay
+ row['retry_operation'] = operation
+ self.retry = (operation, selected, row['retry_at'])
+ # A background check nobody asked for leaves what is shown alone
+ # and only retries; the failure of a check that is shown stays current.
+ if quiet and self.state.get('retry_operation') != 'check':
+ return
+ row['error'] = error_text(row)
+ self.state = row
self.thread = threading.Thread(target=work, daemon=True)
self.thread.start()
diff --git a/freevideo_engine/launcher_update_ui.py b/freevideo_engine/launcher_update_ui.py
index f67c604..f08bebf 100644
--- a/freevideo_engine/launcher_update_ui.py
+++ b/freevideo_engine/launcher_update_ui.py
@@ -3,7 +3,7 @@ import time
import webbrowser
from . import branding
-from .launcher_update import RELEASE_PAGE, launch_download, DownloadedLauncherUnavailable
+from .launcher_update import error_text, release_page, launch_download, DownloadedLauncherUnavailable
class UpdateUI:
@@ -39,15 +39,12 @@ class UpdateUI:
self.detail.pack(fill='both', expand=True)
self.progress = app.ttk.Progressbar(body, maximum=1); self.progress.pack(fill='x', pady=8)
self.rate = app.ttk.Label(body, text=''); self.rate.pack(anchor='w')
- self.access = app.ttk.Frame(body)
- app.ttk.Label(self.access, text=app.t('GitHub token · private updates · this session only', 'GitHub Token · 私有更新 · 仅本次会话使用')).pack(anchor='w')
- self.token = app.tk.StringVar(value=self.client.token)
- app.ttk.Entry(self.access, textvariable=self.token, show='•').pack(fill='x')
actions = app.ttk.Frame(body); actions.pack(fill='x', pady=(14, 0))
self.primary = app.ttk.Button(actions, command=self.accept); self.primary.pack(side='left')
self.dismiss_button = app.ttk.Button(actions, command=self.dismiss)
self.dismiss_button.pack(side='left', padx=8)
- app.ttk.Button(actions, text=app.t('Release page', '下载页'), command=lambda: webbrowser.open(RELEASE_PAGE)).pack(side='right')
+ app.ttk.Button(actions, text=app.t('Download manually', '手动下载'),
+ command=lambda: webbrowser.open(release_page(self.client.current))).pack(side='right')
d.protocol('WM_DELETE_WINDOW', self.dismiss)
self.render()
if self.client.state['status'] in ('idle', 'current', 'cancelled'):
@@ -55,8 +52,8 @@ class UpdateUI:
def dismiss(self):
self.snoozed = True
- if self.client.state['status'] == 'downloading':
- self.client.cancelled.set()
+ if self.client.state['status'] == 'downloading' or self.client.state.get('retry_operation') == 'download':
+ self.client.stop()
if self.dialog:
self.dialog.destroy(); self.dialog = None
@@ -72,11 +69,10 @@ class UpdateUI:
app.close()
elif row['status'] == 'available' or (row['status'] in ('error', 'cancelled') and row.get('candidate')):
if getattr(self.client, 'current', {}).get('packaging') == 'onedir':
- webbrowser.open(RELEASE_PAGE)
+ webbrowser.open(release_page(self.client.current))
else:
self.client.run('download', row['candidate'])
else:
- self.client.token = self.token.get().strip()
self.client.run('check')
except DownloadedLauncherUnavailable:
self.client.run('download', row['candidate'])
@@ -99,7 +95,7 @@ class UpdateUI:
'cancelled': ('Update paused', '更新已停止')}
self.heading.configure(text=app.t(*headings.get(state, headings['checking'])))
candidate = row.get('candidate')
- description = row.get('error', '')
+ description = error_text(row, app.zh)
if candidate:
description += ('\n\n' if description else '') + '%s · %s · %s\n%.1f MiB\n\n%s' % (candidate['version'],
time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime(candidate['built_at'])), candidate['revision'][:8],
@@ -119,10 +115,6 @@ class UpdateUI:
self.rate.configure(text=('%.0f%% · %.1f MiB/s · ~%ds' %
(100*progress['done']/progress['total'], progress['bytes_per_second']/2**20,
progress['remaining_seconds'])) if progress else '')
- if state == 'error':
- self.access.pack(fill='x', pady=8, before=self.primary.master)
- else:
- self.access.pack_forget()
downloadable = state == 'available' or (state in ('error', 'cancelled') and candidate)
self.primary.configure(text=app.t('Restart & update', '重启并更新') if state == 'ready' else
app.t('Download folder ZIP', '下载文件夹版') if downloadable and
@@ -137,6 +129,7 @@ class UpdateUI:
self.timer = None
if self.closed:
return
+ self.client.poll(allow_download=not self.app.controller.busy)
row = self.client.state
state = row['status']
self.button.configure(text=self.app.t('Update available', '有可用更新') if row.get('candidate') else
@@ -153,7 +146,7 @@ class UpdateUI:
def stop(self):
self.closed = True
- self.client.cancelled.set()
+ self.client.stop()
if self.timer is not None:
self.app.window.after_cancel(self.timer)
self.timer = None
diff --git a/freevideo_engine/model_read_ahead.py b/freevideo_engine/model_read_ahead.py
new file mode 100644
index 0000000..43b6b19
--- /dev/null
+++ b/freevideo_engine/model_read_ahead.py
@@ -0,0 +1,324 @@
+"""Read the video model's weight files while the text encoder works, on a slow drive.
+
+A request that has to load the text encoder from the drive reads it first, then
+the video model, with the drive idle in between: the encoder's own compute keeps
+the GPU busy for tens of seconds and reads nothing. When the drive is slow that
+idle time is read time lost; the model load then starts cold and waits for every
+block. This reader fills the gap. It runs from the end of the encoder's device
+copy to the end of its compute, reads the root and the resident block files in
+the order the engine loads them, and keeps nothing but reclaimable OS cache (no private copy,
+CUDA allocation or pinned memory), so the load that follows finds those pages
+cached. It stops before keyframe and reference-media encoding, which read the
+drive themselves.
+
+It acts only when the drive is slow: the first megabytes (up to 64 MiB) are
+timed, and a drive or cache that reads at 1.2 GB/s or faster stops there and
+leaves the request otherwise as it was (a fast drive loses nothing waiting, and
+copying cached pages would take a core from the encoder). The weights the
+engine will pin in RAM and the host work it does beside them are subtracted
+from the live RAM before deciding how much to read, so the cache never competes
+with them for more than the request leaves. Only files every load reads first
+(`model_files`) are read ahead; the blocks it pins, views or streams depend on the
+platform and the live memory, and are left to the load.
+"""
+import os
+from pathlib import Path
+import threading
+import time
+
+from .encoder_prewarm import GiB
+
+# One read; close() waits for the one in flight.
+CHUNK = 2**20
+# How long the foreground waits for the reader to stop; see ModelReadAhead.close.
+CLOSE_WAIT_SECONDS = 1.
+
+# A drive or cache reading at least this fast is not worth a second reader.
+FAST_BYTES_PER_SECOND = 1.2e9
+PROBE_BYTES = 64 * 2**20
+# Live RAM is sampled once per this many bytes.
+MEMORY_CHECK_BYTES = 256 * 2**20
+SYSTEM_RESERVE = 2 * GiB
+
+
+def cache_room():
+ """Physical RAM that file cache may use, and whether the sample is complete.
+
+ Commit is not part of it: cached pages of a file are not committed memory.
+ """
+ from .hardware import cgroup_memory
+ from .system import system_memory
+ memory = system_memory()
+ available = memory.get('physical_available_bytes')
+ if type(available) is not int or available < 0:
+ available = memory['available_bytes']
+ group = cgroup_memory()
+ if group.get('available_bytes') is not None:
+ available = min(available, group['available_bytes'])
+ return available, bool(group.get('complete', True))
+
+
+def probe(file, size, result, cancelled, limit=None, scratch=None, read=None):
+ """Read the first bytes of an open file and record how fast they came.
+
+ `read(view)` fills the view and returns the bytes read, or None once reading
+ was cancelled. Returns the bytes read, or None when the read was cancelled or
+ the file ended early."""
+ scratch = bytearray(CHUNK) if scratch is None else scratch
+ read = file.readinto if read is None else read
+ limit = min(PROBE_BYTES if limit is None else limit, size)
+ done = 0
+ started = time.monotonic()
+ while done < limit:
+ if cancelled.is_set():
+ return None
+ count = read(memoryview(scratch)[:min(CHUNK, limit - done)])
+ if not count:
+ return None
+ done += count
+ result['read_bytes'] = result.get('read_bytes', 0) + count
+ elapsed = max(time.monotonic() - started, 1e-6)
+ result.update(probe_bytes=done, probe_bytes_per_second=done / elapsed)
+ return done
+
+
+def model_files(cache, *, resident_blocks=None, cancelled=None):
+ """The weight files every model load reads first, in the order it reads them.
+
+ The root, then the resident blocks in index order (all blocks when
+ `resident_blocks` is None). The blocks beyond them are pinned, viewed or
+ read at each step by a plan that depends on the platform and the live
+ memory, and the AdaLN files are read only when their tables are missing;
+ none of those are read ahead. Each step first checks `cancelled` (an Event), and a
+ lookup that finds it set returns nothing."""
+ import json
+ import re
+ def stopped():
+ return cancelled is not None and cancelled.is_set()
+ try:
+ cache = Path(cache).resolve()
+ if stopped():
+ return []
+ manifest = json.loads((cache / 'manifest.json').read_text(encoding='utf-8'))
+ root, blocks = [], []
+ for group in manifest['groups']:
+ if stopped():
+ return []
+ path = cache / group['file']
+ found = re.fullmatch(r'blocks/(\d+)\.safetensors', path.relative_to(cache).as_posix())
+ if found and path.is_file():
+ blocks.append((int(found.group(1)), path))
+ elif group.get('group') == 'root' and path.is_file():
+ root.append(path)
+ blocks.sort(key=lambda row: row[0])
+ if resident_blocks is not None:
+ blocks = blocks[:max(0, int(resident_blocks))]
+ return [str(path) for path in root] + [str(path) for _, path in blocks]
+ except (OSError, ValueError, KeyError, TypeError, AttributeError):
+ return []
+
+
+def request_fields(cache, engine, *, budget_is_estimate):
+ """What the encode request carries for the read-ahead; nothing when it cannot be formed.
+
+ It touches no file: the reader's own thread resolves the model's files
+ (`model_files`), so a drive that does not answer cannot hold up the request."""
+ try:
+ return dict(model_cache=str(cache), model_resident_blocks=int(engine.get('resident_blocks') or 0),
+ ram_budget_is_estimate=bool(budget_is_estimate),
+ model_headroom_bytes=round(float(engine.get('pin_host_gb') or 0) * 1e9 + _headroom()))
+ except Exception:
+ return {}
+
+
+def _headroom():
+ from .system import HOST_WEIGHT_HEADROOM
+ return HOST_WEIGHT_HEADROOM
+
+
+# Readers that did not stop in time and may still be inside a call that does not return.
+_abandoned = []
+
+
+def abandoned_readers():
+ _abandoned[:] = [reader for reader in _abandoned if not reader.done.is_set()]
+ return len(_abandoned)
+
+
+class ModelReadAhead:
+ def __init__(self, paths=(), *, cache=None, resident_blocks=None, headroom_bytes=0, ram_budget_bytes=None,
+ budget_is_estimate=False):
+ # Either the files themselves, or the model cache whose files the reader thread looks up.
+ self.paths = [Path(item) for item in paths]
+ self.cache, self.resident_blocks = cache, resident_blocks
+ self.headroom_bytes = max(0, int(headroom_bytes or 0))
+ self.ram_budget_bytes = ram_budget_bytes
+ self.budget_is_estimate = bool(budget_is_estimate)
+ self.cancelled = threading.Event()
+ # Taken only to check for cancellation and mark an open or read as in flight, never
+ # across the call itself; `inflight` is clear while one is running.
+ self.gate = threading.Lock()
+ self.inflight = threading.Event()
+ self.inflight.set()
+ # Set by the reader thread as its last act; the one sure sign that it has ended.
+ self.done = threading.Event()
+ self.thread = None
+ self.closed = None
+ self.result = dict(state='not-started', read_bytes=0, elapsed_seconds=0.,
+ gpu_allocation_bytes=0, private_buffer_bytes=CHUNK,
+ scope='Video model root and resident block files; reclaimable OS cache, no GPU residency')
+
+ def start(self):
+ if self.thread is not None or self.closed is not None:
+ return self
+ if abandoned_readers():
+ self.result.update(state='skipped', reason='An earlier read-ahead has not returned from the drive')
+ return self
+ if os.environ.get('FREEVIDEO_MODEL_READ_AHEAD', 'auto').lower() in ('off', '0', 'false'):
+ self.result.update(state='skipped', reason='Disabled by FREEVIDEO_MODEL_READ_AHEAD')
+ return self
+ self.thread = threading.Thread(target=self._run, name='FreeVideo model read-ahead', daemon=True)
+ self.thread.start()
+ return self
+
+ def _begin(self):
+ with self.gate:
+ if self.cancelled.is_set():
+ return False
+ self.inflight.clear()
+ return True
+
+ def _read(self, view, file):
+ if not self._begin():
+ return None
+ try:
+ return file.readinto(view)
+ finally:
+ self.inflight.set()
+
+ def _open(self, path):
+ if not self._begin():
+ return None
+ try:
+ return path.open('rb', buffering=0)
+ finally:
+ self.inflight.set()
+
+ def _allowance(self):
+ available, complete = cache_room()
+ allowance = max(0, available - SYSTEM_RESERVE - self.headroom_bytes)
+ if self.ram_budget_bytes is not None and not self.budget_is_estimate:
+ from .ram import ProcessMemory
+ from .system import memory_sample
+ used = memory_sample(ProcessMemory().sample(os.getpid()))
+ complete = complete and type(used) is int and used >= 0
+ allowance = min(allowance, max(0, int(self.ram_budget_bytes) - (used or 0) - SYSTEM_RESERVE
+ - self.headroom_bytes))
+ return allowance, complete
+
+ def _run(self):
+ started = time.monotonic()
+ try:
+ if self.cache is not None:
+ self.paths = [Path(item) for item in model_files(
+ self.cache, resident_blocks=self.resident_blocks, cancelled=self.cancelled)]
+ if self.cancelled.is_set():
+ self.result.update(state='stopped', reason='Encoding finished before the files were looked up')
+ return
+ if not self.paths:
+ self.result.update(state='skipped', reason='No model files to read ahead')
+ return
+ stamps = [(path, path.stat()) for path in self.paths]
+ total = sum(stamp.st_size for _, stamp in stamps)
+ allowance, complete = self._allowance()
+ self.result.update(total_bytes=total, allowance_bytes=allowance, headroom_bytes=self.headroom_bytes)
+ if not complete or total <= 0 or allowance < min(total, CHUNK):
+ self.result.update(state='skipped', reason='Live RAM cannot retain the model beside its pinned weights')
+ return
+ target = min(total, allowance)
+ self.result.update(target_bytes=target)
+ scratch = bytearray(CHUNK)
+ checked = 0
+ for index, (path, stamp) in enumerate(stamps):
+ if self.result['read_bytes'] >= target:
+ break
+ file = self._open(path)
+ if file is None:
+ self.result.update(state='stopped', reason='Encoding finished before the drive was measured')
+ return
+ with file:
+ if index == 0:
+ done = probe(file, stamp.st_size, self.result, self.cancelled,
+ limit=min(target, PROBE_BYTES), scratch=scratch,
+ read=lambda view: self._read(view, file))
+ if done is None:
+ if not self.cancelled.is_set():
+ raise ValueError('Model file truncated during read-ahead')
+ self.result.update(state='stopped', reason='Encoding finished before the drive was measured')
+ return
+ if self.result['probe_bytes_per_second'] >= FAST_BYTES_PER_SECOND:
+ self.result.update(state='skipped', reason='The drive or cache reads fast; the load reads on demand')
+ return
+ self.result['slow_drive'] = True
+ remaining = min(stamp.st_size - (file.tell() if index == 0 else 0),
+ target - self.result['read_bytes'])
+ while remaining > 0:
+ pressure = False
+ if self.result['read_bytes'] - checked >= MEMORY_CHECK_BYTES:
+ checked = self.result['read_bytes']
+ available, complete = cache_room()
+ pressure = not complete or available < SYSTEM_RESERVE + self.headroom_bytes + MEMORY_CHECK_BYTES
+ if self.cancelled.is_set() or pressure:
+ self.result.update(state='stopped', reason='Encoding finished, or live RAM pressure')
+ return
+ count = self._read(memoryview(scratch)[:min(CHUNK, remaining)], file)
+ if count is None:
+ self.result.update(state='stopped', reason='Encoding finished, or live RAM pressure')
+ return
+ if not count:
+ raise ValueError('Model file truncated during read-ahead')
+ remaining -= count
+ self.result['read_bytes'] += count
+ current = path.stat()
+ if (current.st_size, current.st_mtime_ns) != (stamp.st_size, stamp.st_mtime_ns):
+ raise ValueError('Model file changed during read-ahead')
+ if self.result['read_bytes'] < total:
+ self.result.update(state='partial', reason='Model pages within the live RAM allowance read; the load reads the rest')
+ else:
+ self.result.update(state='ready', reason='Model files read into the OS cache; the load reuses them')
+ except Exception as error:
+ # Speculative I/O never replaces the loader's own reads and validation.
+ self.result.update(state='failed', reason=type(error).__name__ + ': ' + str(error))
+ finally:
+ self.result['elapsed_seconds'] = time.monotonic() - started
+ self.done.set()
+
+ def close(self):
+ """Stop reading and return what was read; later calls return the same result.
+
+ Cancellation is set first, so no open or read starts after it; the
+ foreground then waits at most CLOSE_WAIT_SECONDS for the one that had
+ started (its call is the only thing that can still be running) and for
+ the thread to end. A drive that does not answer in that time leaves the
+ thread inside its call: it is abandoned (`abandoned` in the result) and
+ ends, closing its file, whenever the call returns. It starts nothing
+ more, holds no GPU or pinned memory, and no new read-ahead starts while
+ one is abandoned."""
+ if self.closed is None:
+ self.cancelled.set()
+ abandoned = False
+ if self.thread is not None:
+ deadline = time.monotonic() + CLOSE_WAIT_SECONDS
+ try:
+ with self.gate:
+ # Any open or read begun before this point has marked itself in flight.
+ pass
+ self.inflight.wait(max(0., deadline - time.monotonic()))
+ self.done.wait(max(0., deadline - time.monotonic()))
+ finally:
+ # Also when the wait is interrupted: a reader that has not ended is registered.
+ abandoned = not self.done.is_set()
+ if abandoned and self not in _abandoned:
+ _abandoned.append(self)
+ self.closed = dict(self.result, abandoned=abandoned)
+ return self.closed
diff --git a/scripts/publish_release.py b/scripts/publish_release.py
index aca1ff5..80de9b8 100644
--- a/scripts/publish_release.py
+++ b/scripts/publish_release.py
@@ -20,9 +20,10 @@ import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
-from freevideo_engine.launcher_update import (CHANNEL, LINUX_CHANNEL, MAC_CHANNEL, NIGHTLY_TAG, # noqa: E402
- RELEASE_ASSETS, build_identity, build_track)
-from freevideo_engine.release_notes import notes # noqa: E402
+from freevideo_engine.launcher_update import (CHANNEL, LINUX_CHANNEL, MAC_CHANNEL, MAX_MANIFEST_BYTES, # noqa: E402
+ NIGHTLY_TAG, RELEASE_ASSETS, asset_url, build_identity, build_track,
+ manifest)
+from freevideo_engine.release_notes import notes, version_key # noqa: E402
PLATFORMS = (CHANNEL, MAC_CHANNEL, LINUX_CHANNEL)
LEGACY_PLATFORMS = (CHANNEL, MAC_CHANNEL)
@@ -191,11 +192,38 @@ class Releases:
return {a['name']: a for a in self.api('Read %s assets' % tag, 'releases/%d' % release['id'])['assets']}
-def metadata(build, asset, path):
+def fitted(value, name):
+ """The update metadata as uploaded, within what every released launcher reads.
+
+ A launcher stops reading at MAX_MANIFEST_BYTES and then cannot update at
+ all. While the file would be larger, the notes of the oldest earlier
+ version are left out, and the log names each one."""
+ value = dict(value)
+ data, left_out = json.dumps(value, indent=2).encode('utf-8'), []
+ while len(data) > MAX_MANIFEST_BYTES:
+ earlier = sorted(value.get('release_history') or [], key=lambda row: version_key(row['product_version']))
+ if not earlier:
+ raise SystemExit('::error::%s is %d bytes, more than the %d that released launchers read. '
+ 'Shorten the release notes of this version.' % (name, len(data), MAX_MANIFEST_BYTES))
+ left_out.append(earlier[0]['product_version'])
+ value['release_history'] = earlier[:0:-1]
+ if not value['release_history']:
+ del value['release_history']
+ data = json.dumps(value, indent=2).encode('utf-8')
+ if left_out:
+ print('%s: left out the notes of %s to stay within %d bytes (now %d)'
+ % (name, ', '.join(left_out), MAX_MANIFEST_BYTES, len(data)))
+ if manifest(json.loads(data))['asset'].get('url') != value['asset']['url']:
+ raise SystemExit('::error::%s names a download address that launchers do not accept' % name)
+ return data
+
+
+def metadata(build, asset, path, tag):
if asset['size'] != build['path'].stat().st_size:
raise SystemExit('Uploaded %s differs in size from the built file' % asset['name'])
- value = dict(build['raw'], asset=dict(id=asset['id'], bytes=asset['size'], sha256=build['sha256']))
- Path(path).write_text(json.dumps(value, indent=2), encoding='utf-8')
+ value = dict(build['raw'], asset=dict(id=asset['id'], bytes=asset['size'], sha256=build['sha256'],
+ url=asset_url(tag, build['path'].name)))
+ Path(path).write_bytes(fitted(value, Path(path).name))
return path
@@ -208,7 +236,7 @@ def write(folder, name, text):
def bind_metadata(releases, tag, builds, channels, folder, names):
"""Upload update metadata for each platform, bound to the assets now on the release."""
uploaded = releases.assets(tag)
- files = [metadata(builds[c], uploaded[builds[c]['path'].name], Path(folder) / names[c]) for c in channels]
+ files = [metadata(builds[c], uploaded[builds[c]['path'].name], Path(folder) / names[c], tag) for c in channels]
gh('Upload update metadata to %s' % tag, 'release', 'upload', tag, *map(str, files), '--clobber')