Skip to content

Native Windows video motion capture with ExMR, FlowHMR and GVHMR, contact correction, humanoid retargeting, and FBX/VMD export.

Python

Improve installer recovery and reuse recent runtime verification

toyxyzd0c990e1c627
diff --git a/README.md b/README.md
index fbdaae2..c4c3dac 100644
--- a/README.md
+++ b/README.md
@@ -57,6 +57,11 @@ To update, close the app and run `update.cmd` from the same folder. See the
[installation guide](docs/USER_GUIDE.md#install) for disk space, prerequisites
and recovery.
+Updates reuse recently verified, unchanged runtimes. If PEAR or camera-alignment
+support preparation fails after the base installation succeeds, the base app
+remains usable; rerun `install.cmd` to retry the unavailable support. See
+[verification and repair](docs/USER_GUIDE.md#installation-verification-and-repair).
+
### Optional model runtimes
`install.cmd` prepares ExMR, FlowHMR, GVHMR and the small shared-runtime support
diff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.json
index d98bab2..f2c27ab 100644
--- a/SOURCE_MANIFEST.json
+++ b/SOURCE_MANIFEST.json
@@ -1,6 +1,6 @@
{
"schema": 1,
- "date": "2026-11-04",
+ "date": "2026-11-06",
"purpose": "Public source distribution; excludes model weights and runtime binaries",
"version": "git-source",
"files": [
@@ -26,8 +26,8 @@
},
{
"path": "README.md",
- "bytes": 12453,
- "sha256": "8d0805bd478dc38ff39680b37b0744a7cb8783d26a22614ac9cc684300651938"
+ "bytes": 12770,
+ "sha256": "e7e36b21ae1e57cea71012be7d50de37e2e8474dce7b2603675b92f439440169"
},
{
"path": "RGBMoCap.cmd",
@@ -96,13 +96,13 @@
},
{
"path": "docs/AGENT_GUIDE.md",
- "bytes": 69250,
- "sha256": "f1f7beb2be54f32d55c6e3d061038f4c9a8bbbe60af71a9aacd3bd752f972c31"
+ "bytes": 70853,
+ "sha256": "d82371616b0a7442e88dfb0ce9086fcd3aaca3d80b85122f5ba5536fbada6a22"
},
{
"path": "docs/BUILD.md",
- "bytes": 13113,
- "sha256": "3ca8d430ea8a261db29bd817c4c3674907d889af6bc9f59132d5818179866f56"
+ "bytes": 16061,
+ "sha256": "402cbcd93299ae5a7e4f6937a15c691683d0fcce5b4b4d029373c8a10df82e0f"
},
{
"path": "docs/CITATIONS.md",
@@ -126,13 +126,13 @@
},
{
"path": "docs/USER_GUIDE.md",
- "bytes": 63738,
- "sha256": "56c928d6a05e882e24fd43773fd146d440f73387b325f532a4afca7939076f33"
+ "bytes": 65698,
+ "sha256": "4ea64b0722fef3ca43bfab9c6266dcf8b6cf620060a46b8b29ebeb75db804ed8"
},
{
"path": "docs/VALIDATION.md",
- "bytes": 139455,
- "sha256": "8b1931274cece344694bcd749ef66e465fc14b566a46fed3fa9604c3b5fc9334"
+ "bytes": 143635,
+ "sha256": "77691e896537ccd67ee14e967685b97c109c2734e61db51d3e7e5eb1d005897e"
},
{
"path": "docs/images/exmr-interaction-contact.png",
@@ -171,8 +171,8 @@
},
{
"path": "docs/models/PEAR.md",
- "bytes": 23965,
- "sha256": "cde9ccbfa48913eecd4659138a967c65aa1c2030557c6ec525cfd548ab393603"
+ "bytes": 24551,
+ "sha256": "8967cc2bbc74abacaa5b0923b7f821369b3fec10840b11259718722b72c24723"
},
{
"path": "docs/models/PROMPTHMR.md",
@@ -236,8 +236,8 @@
},
{
"path": "installer/engine.py",
- "bytes": 18340,
- "sha256": "f285199581bff1154a84da727a0b5b32ae19d52c1fb9b2b3b9e571fe516cd554"
+ "bytes": 18904,
+ "sha256": "5be67c26acc141306b3fd7ce80f74ad3570c6a268ada13cffff187b0707db443"
},
{
"path": "installer/external-assets.json",
@@ -1591,8 +1591,8 @@
},
{
"path": "mocap/pear/alignment_support.py",
- "bytes": 1168,
- "sha256": "c181e2025b6491a80f68f3c954806a63cd280dcf1d9735ac2a5d2d7e4d4b0b09"
+ "bytes": 1959,
+ "sha256": "88de916078a6abfb920832f7c69e4e3544754922506c54ce44b0ade183e47429"
},
{
"path": "mocap/pear/batch.py",
@@ -12866,8 +12866,8 @@
},
{
"path": "tools/git_managed_install.py",
- "bytes": 5686,
- "sha256": "e3f6cbe11315e1a6624e4d91febd2a697ebc7f9196a616b7321b4173df94bca9"
+ "bytes": 7716,
+ "sha256": "2d537e5187a29a33a726ac6c0c88f4d5ae8b9048139a4a4874c03ca224612da3"
},
{
"path": "tools/git_transaction.py",
@@ -12876,8 +12876,18 @@
},
{
"path": "tools/git_update.py",
- "bytes": 1648,
- "sha256": "46491b1aadc8ef27d3ffafc0cf70caf9d5dadea3565db0ad40c3e64d6885423d"
+ "bytes": 1885,
+ "sha256": "ace9d2a8981c7c6eb7887280d9895d3f757d155f8ad7c646ca71c3f37c8ec8d8"
+ },
+ {
+ "path": "tools/optional_support.py",
+ "bytes": 1475,
+ "sha256": "992c156e58b80d845e1957cb276af69abea78bf6060a1b3790b22373413114cf"
+ },
+ {
+ "path": "tools/pinned_download.py",
+ "bytes": 7296,
+ "sha256": "719a7744bd2f03d4ac33d2b388fe2ebfb5712239c2983ebf5523e24f36ce5894"
},
{
"path": "tools/prepare_upstream.py",
@@ -12889,6 +12899,11 @@
"bytes": 3496,
"sha256": "f94692268dcc654ebe21d62302fd1714730af98bd4084c51b27f36215069c01a"
},
+ {
+ "path": "tools/runtime_verification.py",
+ "bytes": 4618,
+ "sha256": "a91fb0a907f4ad1607dc166664ed7f4e426f92b384222ac19484406f989738ec"
+ },
{
"path": "tools/session_lock.py",
"bytes": 763,
@@ -12906,13 +12921,13 @@
},
{
"path": "tools/setup_pear.py",
- "bytes": 5179,
- "sha256": "bcd4d2e0dbbb6ecb5dfa75455d5a0d0d0f11f50ea99cf79e7973c50c8cbb18ee"
+ "bytes": 5430,
+ "sha256": "9e491a2c63df8843b5004edfbaac16d51793aa4a98301b3d4607197e2f7eb6a7"
},
{
"path": "tools/setup_pear_alignment.py",
- "bytes": 2836,
- "sha256": "bc43c636f0256898e4dc14731677348464a194bd055ffdaa33c13ace684e3545"
+ "bytes": 3090,
+ "sha256": "e6ff5e0a3923d9ceac8b4616e7228077502fd71c24a369f075a268e81b253140"
},
{
"path": "tools/setup_prompthmr.py",
@@ -12931,8 +12946,8 @@
},
{
"path": "tools/support_components.py",
- "bytes": 3830,
- "sha256": "000772ff21d47a1a35d5fefa0e7685781e7c05fbbbcf708a29cfc3f275dd4984"
+ "bytes": 3388,
+ "sha256": "bb454f0c6171e2357f5e550a5f88f8f37ce7654842e252b2d1afb6d53e39c903"
},
{
"path": "update.cmd",
diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.md
index 138e0df..11942c5 100644
--- a/docs/AGENT_GUIDE.md
+++ b/docs/AGENT_GUIDE.md
@@ -10,6 +10,9 @@ This guide is for agents helping users operate or modify RGB MoCap. It describes
- Base worker commands use explicit `-X utf8`, including isolated `-I` launches. Isolated mode ignores `PYTHONIOENCODING`/`PYTHONUTF8` from the parent environment. Any redirected/discarded text log stream must also specify UTF-8. Keep byte-oriented PEAR IPC unchanged.
- Close the app before `update.cmd`. The updater requires a clean tracked worktree and the `main` branch, uses `git pull --ff-only`, then verifies/repairs runtime configuration. It refuses tracked local edits. A plain `git pull` does not perform runtime repair; use `install.cmd` after dependency changes when needed. Do not discard local edits or force an update.
- For setup failure, read the message, check connectivity and free space, then retry `install.cmd`. Preserve models, projects and `.setup` state. Do not repeatedly reinstall or redownload models without evidence.
+- Base completion and optional PEAR/camera-alignment readiness are separate. A post-commit support failure reports completion with warnings; it must not recreate the global base pending marker. Inspect `.setup/git-components.json` and the actual capability configuration. Retry with `install.cmd`; camera-alignment preparation is independent of PEAR and also serves MAMMA automatic gravity. Mandatory base failures and unresolved promotion journals remain blocking. Never delete a pending marker blindly.
+- Recent full runtime checks are reused for up to seven days with matching group/verifier identities and an unchanged bounded file inventory, including additions/removals. Reuse does not refresh the full-check date. `install.cmd --verify-all` or `update.cmd --verify-all` forces the existing RECORD hashes/import checks. Missing/expired metadata, dependency changes and detected file changes trigger full checks for affected groups/dependents. Metadata is a change-detection heuristic, not an authenticity guarantee. Do not mark a runtime verified without an actual successful check.
+- `tools/pinned_download.py` supplies bounded HTTPS retries/resume for support archives. Keep certificate verification, HTTPS redirects, exact size and SHA-256, validated Content-Range, cancellation propagation and finite attempt/time limits. Ordinary base wheel downloads and optional package fetching retain their own paths; do not claim this replaces every network call. Source contracts are frozen/rechecked during base installation. A failed Git pull must preserve any pre-existing incomplete-install marker.
- Base installation currently estimates at least 32.4 GiB free before models; ExMR/FlowHMR/GVHMR and add-ons were previously measured around 29 GiB of weights. Optional MAMMA and PromptHMR add separate runtimes and model files; see [MAMMA](MAMMA.md) and [PromptHMR](models/PROMPTHMR.md). The five offline model/runtime sets total about **63.22 GiB (67.9 GB)** before optional PromptHMR moving-camera support, excluding caches, projects, downloads and compiler tools, counting shared files once. Camera support adds about **1.57 GiB** (18.6 MiB modules and 1.55 GiB weights). See the [installed-size table](USER_GUIDE.md#installed-size); installed size and temporary setup headroom are different. Measurements are not guarantees.
Multi-person reconstruction groups supported ExMR, FlowHMR and GVHMR phases
diff --git a/docs/BUILD.md b/docs/BUILD.md
index fb6ea8b..2c6eb08 100644
--- a/docs/BUILD.md
+++ b/docs/BUILD.md
@@ -203,13 +203,17 @@ support folders, diagnostics and private regression artifacts are excluded from
The active receipt binds the support/adapters to the installed shared-runtime group.
Matching verified support is retained without downloading or extracting it again;
a source/base change or damaged support stages and CUDA-verifies a new generation
-before replacing the pointer. Failure leaves prior support and the install retry
-marker intact. No weights or registered geometry are acquired by this step.
+before replacing the pointer. Failure preserves prior support generations. Base
+completion is independent: a post-commit PEAR failure reports a warning rather
+than leaving the base install retry marker. No weights or registered geometry
+are acquired by this step.
`tools/setup_pear_alignment.py` additionally stages the pinned GeoCalib/Kornia
support from `installer/pear-alignment.json`, over the existing Flow runtime,
without upgrading shared packages. It verifies imports/CUDA availability and
-writes a separate `.setup/pear-alignment.json` inventory. VGGT/GeoCalib model
+writes a separate `.setup/pear-alignment.json` inventory bound to the installed
+shared/Flow group IDs and runtime directory creation stamps. A replaced or changed
+base requires support revalidation. VGGT/GeoCalib model
weights are obtained in Model Manager. This support enables camera alignment;
if it is unavailable, PEAR can still track the selected camera with a warning,
provided its base support and model files are ready.
@@ -221,6 +225,46 @@ environment. Missing or unreliable gravity is an actionable failure for MAMMA
automatic cameras. Manual camera data bypasses this support and both camera
checkpoints. A separate GeoCalib package installation into MAMMA is not needed.
+## Base update and recovery
+
+Keep the existing bootstrap, pinned separate profiles and promotion journal.
+`tools/git_managed_install.py` freezes source dependency/installer inputs, recovers
+an interrupted promotion, verifies/stages the base, rechecks the frozen inputs,
+then commits receipts and finishes journal cleanup. Only then clear the global
+pending marker. PEAR and camera alignment are independently attempted through
+`tools/optional_support.py`; `.setup/git-components.json` records their readiness
+and errors. A support warning is not a successful capability verification.
+Cancellation must propagate; mandatory base errors remain fatal.
+If a live runtime is reused, discard its leftover installer staging directory
+before installing dependents, and never promote that stale directory. Otherwise
+an interrupted run could supply an unverified staged interpreter or replace an
+already verified live runtime. This cleanup is confined to installer staging.
+
+`tools/runtime_verification.py` caches successful full checks per profile for
+at most seven days. Cache keys include the group/base dependency identity and
+verifier code; reports must match the committed receipt. A bounded metadata
+inventory includes files added/removed and size/mtime/ctime changes, ignoring
+bytecode caches. Recheck reused inventories before base commit. A fast check
+never extends the full-check date. Missing, changed, expired or malformed caches
+fall back to full RECORD/import verification. `--verify-all` bypasses reuse.
+This is an ordinary-change detector, not protection against hostile metadata
+forgery. Keep the explicit full-audit path and do not broaden numerical cache
+invalidation for installer-only changes.
+
+Support archives use `tools/pinned_download.py`: default TLS verification,
+HTTPS-only redirects, three transient-error attempts, bounded backoff and a
+size-aware total deadline, a finite socket timeout, strict range validation and
+a final complete size/hash check. Partial files are associated with the exact
+URL/size/hash; an ignored Range restarts safely. Certificate/permanent HTTP or
+pin failures do not loop indefinitely. Existing base-wheel and optional-runtime
+package download paths are not all replaced by this helper.
+
+Fault tests must distinguish failure before base commit from failure afterward.
+Include real CMD argument forwarding/local Git fast-forward, retained pending
+state after failed pulls, interrupted promotions, changed source inputs, partial
+downloads, certificate/hash failures and user-data preservation. Keep tests and
+their generated files outside the public source tree. See [validation](VALIDATION.md#installation-recovery-and-recent-verification-2026-11-06).
+
Changed upstream files receive an adaptation notice. Each support generation
also records pinned source URLs/hashes and the adapter hash in
`RGB_MOCAP_PROVENANCE.json`, alongside the retained provider license files.
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index 2f08b54..f11962f 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -163,6 +163,42 @@ be reused. Do not delete `models`, `projects` or the remaining `.setup` state to
retry. If Git reports a conflict or local changes, resolve or back them up before
running `update.cmd` again.
+### Installation verification and repair
+
+First installation, changed dependencies and missing/changed runtime files still
+require full package hash and import checks. For up to seven days after a
+successful full check, ordinary updates/retries can reuse that result when the
+dependency/verifier identities and file inventory remain unchanged. This scans
+file metadata instead of repeatedly reading every package payload. The cache
+does not extend its own expiry. Size/timestamps are change detection, not a
+cryptographic proof against deliberate tampering.
+
+To force the full runtime checks, close the app and run:
+
+```cmd
+install.cmd --verify-all
+```
+
+`update.cmd --verify-all` also updates source and requests full verification.
+Existing installations without verification metadata perform one full check
+before gaining the faster retry path. The commands and separate runtime layout
+are unchanged; no new runtime manager or separate PEAR setup command is required.
+
+The base runtime transaction completes before PEAR and camera-alignment support
+are attempted independently. If only those support steps fail, setup reports
+**Installation complete with warnings** and the base app remains available.
+PEAR needs its own support; automatic MAMMA gravity needs camera-alignment
+support. Those capabilities remain unavailable until their preparation succeeds.
+Rerun `install.cmd`; the component summary is `.setup/git-components.json`.
+Failed mandatory base installation or an unresolved update still blocks launch.
+Do not manually remove `.setup/git-sync.pending` to bypass that protection.
+
+Pinned support downloads retry transient network failures up to three attempts
+with bounded waiting and validated partial-download recovery. HTTPS certificate
+and final size/SHA-256 checks remain required. Permanent errors are reported
+without an endless retry loop. Completed model/project files are not part of
+this repair work.
+
On the tested PC, a separate-folder first install took about 10 min 32 sec with
previously verified package downloads reused; Blender and FFmpeg were downloaded.
A subsequent code update and runtime verification took about 1 min 55 sec. These
diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md
index ba91b3d..aa14e5c 100644
--- a/docs/VALIDATION.md
+++ b/docs/VALIDATION.md
@@ -1158,6 +1158,9 @@ showed no sustained resource growth; it is not a long-duration leak guarantee.
### PEAR support included in base installation (2026-11-01)
+The global retry-marker policy described in this historical test was superseded
+by [independent support recovery](#installation-recovery-and-recent-verification-2026-11-06).
+
`install.cmd` now prepares PEAR's small source/utility overlay after the base
runtime transaction commits. `update.cmd` reaches the same managed installation
flow. PEAR reuses the pinned shared Python/Torch packages; model weights and
@@ -2121,3 +2124,71 @@ repeated app-wrapper failures. The adapter owns no additional readers, queues
or threads. The updated Model Guide rendered in offscreen Qt. The installed
MAMMA engine's 368 checked source files were unchanged. Tests/inputs remained
outside the public checkout; no runtime package or model weight was added.
+
+
+### Installation recovery and recent verification (2026-11-06)
+
+Issue #23 exposed a post-commit PEAR download failure leaving the entire base
+installation pending. Base completion now precedes independent PEAR/alignment
+attempts; only affected capabilities are unavailable after support failure.
+Mandatory pre-commit failures remain blocking. A failed unchanged Git pull also
+preserves any earlier incomplete-install marker. Reused runtimes cannot use or
+promote a previous interrupted run's staged interpreter/directory.
+
+32 isolated fault/regression assertions passed on actual selected source
+helpers. They cover transient/permanent download errors, certificate/hash/range
+rejection, cancellation/deadline checks, offline archive reuse, base-versus-support
+failure, successful support retry without repeated full checks, forced full
+verification, source mutation, cache invalidation/expiry, stale-stage cleanup,
+promotion rollback and user-data sentinels. Three real isolated-Python managed
+installer CLI runs passed with heavyweight package/assets/native work stubbed:
+initial support failure, metadata-based retry and forced full verification.
+The fixture paths included Korean, Japanese, Chinese, accented Latin and Cyrillic.
+
+Four actual Windows CMD/local-Git checks passed for install/update argument
+forwarding, fast-forward update, refusal of tracked edits and retained pending
+state after a failed pull. Their bootstrap installation endpoint was stubbed;
+the checkout path also included spaces, multilingual text and a percent sign.
+No public Git remote was changed. A real localhost HTTPS endpoint rejected an
+untrusted certificate, then interrupted a 1 MiB pinned transfer and successfully
+resumed with a validated byte range and final SHA-256. Test trust was local to
+the test process; system certificate settings were unchanged.
+
+All six existing runtime profiles passed actual full RECORD/import verification
+with bytecode writes disabled. On one Windows PC:
+
+| Profile | Full hashes + imports | Subsequent metadata comparison |
+| --- | ---: | ---: |
+| shared | 161.57 s | 5.16 s |
+| gui | 18.75 s | 0.63 s |
+| flow | 57.74 s | 1.67 s |
+| hand | 28.22 s | 0.69 s |
+| htd | 6.31 s | 0.06 s |
+| exmr | 162.34 s | 5.20 s |
+| Total | 434.94 s | 13.42 s |
+
+The comparison scan followed full verification and had warm filesystem caches.
+It measures verification work, not total installation/update duration. The
+installer does a second metadata consistency scan before commit, plus bootstrap,
+support, auxiliary assets and receipt work. First use without a recent cache,
+changed files/dependencies or expired verification still requires full checks.
+Metadata checks are not cryptographic integrity proofs; `--verify-all` retains
+the full-check route. Fast reuse never refreshes the seven-day full-check expiry.
+
+Exact cached pinned PEAR/geometry-helper and GeoCalib/Kornia archives were also
+extracted into isolated support generations. The existing shared/Flow runtimes
+passed actual CUDA rotation/NMS operations and alignment import/CUDA-availability
+checks against those staged sources. Matching support was reused without another
+subprocess. A changed Flow base identity was rejected. The verifier bridge used
+the already installed interpreters; no installed packages or user support
+receipts were replaced. This was not a clean-Windows installation, an external
+network-failure reproduction, a GeoCalib numerical-quality test or new AI motion
+inference. Numerical algorithms, model weights and runtime package pins were
+unchanged.
+
+The development installation's PEAR/alignment support pointers were subsequently
+refreshed under the application lock, using the unchanged installed packages and
+verified cached archives. Both native checks and readiness configurations passed.
+The real launcher dependency/pending guards, GUI runtime activation and app import
+also passed without opening a GUI or running model inference. Prior support
+generations and user models/projects were preserved.
diff --git a/docs/models/PEAR.md b/docs/models/PEAR.md
index db3f3a7..843add9 100644
--- a/docs/models/PEAR.md
+++ b/docs/models/PEAR.md
@@ -49,6 +49,14 @@ capture. Changing device assignment or requested resolution can reopen capture.
`assets.zip`. Import that ZIP without editing it. Import validates its SHA-256
and extracts only required files. The source ZIP is preserved.
+If setup reports PEAR or camera-alignment support unavailable after the base
+installation has completed, other ready workflows can still run. Rerun
+`install.cmd` to repair those capabilities; PEAR and alignment are checked
+independently. Alignment also serves automatic MAMMA gravity. Recent unchanged
+base runtime verification is reused; [full verification and repair](../USER_GUIDE.md#installation-verification-and-repair)
+remain available. Existing support receipts may require one revalidation after
+this installer update; model weights do not need to be downloaded again.
+
PEAR requires **SMPL-X 2020 and FLAME 2020** geometry. The standard SMPL-X v1.1
used by other models and MAMMA's locked-head model cannot replace these files.
Registered geometry is not included in the repository or downloaded automatically
diff --git a/installer/engine.py b/installer/engine.py
index c7e58ae..e2509e8 100644
--- a/installer/engine.py
+++ b/installer/engine.py
@@ -161,7 +161,18 @@ def install_runtimes(root,resources,lock,cancel,reused=None):
setup=inside(root,root/'.setup');stage=inside(setup,setup/'staging'/lock['id']);stage.mkdir(parents=True,exist_ok=True)
logs=setup/'logs';logs.mkdir(exist_ok=True);cache=setup/'downloads';cache.mkdir(exist_ok=True);uv=resources/'uv.exe'
if sha(uv)!=lock['uv_sha256']:raise ValueError('Setup helper verification failed')
- reused=reused or {}; pending=[g for g in lock['groups'] if g['key'] not in reused]
+ reused=reused or {}
+ # A previous interrupted run may leave this lock's staged directories.
+ # Reused groups must refer only to the validated live installation, never
+ # an old staged base interpreter or a leftover directory at promotion.
+ for g in lock['groups']:
+ key=g['key']
+ if TARGETS.get(key)!=g['target']:raise ValueError('Invalid runtime target')
+ if key in reused:
+ stale=stage/g['target']
+ if stale.exists():remove_owned(stage,stale)
+ (stage/('complete-'+key+'.json')).unlink(missing_ok=True)
+ pending=[g for g in lock['groups'] if g['key'] not in reused]
for version in sorted({g['python'] for g in pending}):
emit(message='Preparing private Python '+version,phase='python',current=0,total=0)
run([uv,'python','install',version,'--install-dir',setup/'python','--no-bin','--no-registry','--no-config','--no-progress','--cache-dir',setup/'uv-cache'],root,cancel,logs/('python-'+version+'.log'))
diff --git a/mocap/pear/alignment_support.py b/mocap/pear/alignment_support.py
index 37c6b1e..cddddc5 100644
--- a/mocap/pear/alignment_support.py
+++ b/mocap/pear/alignment_support.py
@@ -4,9 +4,21 @@ import json,hashlib,sys
from ..paths import ROOT
def identity():return hashlib.sha256((ROOT/'installer/pear-alignment.json').read_bytes()+(ROOT/'tools/setup_pear_alignment.py').read_bytes()).hexdigest()
+def base_identity():
+ """Bind the overlay to both installed runtime groups, including replacements."""
+ receipt=json.loads((ROOT/'SETUP_RECEIPT.json').read_text('utf8'))
+ rows={}
+ for key,name in [('shared','runtime'),('flow','runtime_flow')]:
+ group_id=receipt['group_ids'][key]
+ if not isinstance(group_id,str) or not group_id:raise ValueError('Missing alignment base runtime receipt')
+ folder=ROOT/name
+ if folder.is_symlink() or not folder.resolve().is_relative_to(ROOT.resolve()):raise ValueError('Invalid alignment base path')
+ rows[key]=dict(group_id=group_id,created_ns=folder.stat().st_ctime_ns)
+ return hashlib.sha256(json.dumps(rows,sort_keys=True).encode()).hexdigest()
+
def configuration():
data=json.loads((ROOT/'.setup/pear-alignment.json').read_text('utf8'));folder=(ROOT/data['folder']).resolve()
- if not folder.is_relative_to((ROOT/'runtime_pear').resolve()) or data['identity']!=identity():raise ValueError('Camera alignment support needs install.cmd')
+ if not folder.is_relative_to((ROOT/'runtime_pear').resolve()) or data['identity']!=identity() or data.get('base_identity')!=base_identity():raise ValueError('Camera alignment support needs install.cmd')
for name,stamp in data['files'].items():
p=(folder/name).resolve()
if not p.is_relative_to(folder):raise ValueError('Invalid alignment support path')
diff --git a/tools/git_managed_install.py b/tools/git_managed_install.py
index 6f9956a..28aee29 100644
--- a/tools/git_managed_install.py
+++ b/tools/git_managed_install.py
@@ -1,22 +1,40 @@
-"""Experimental Git installer: verified profile reuse and transaction-safe promotion."""
+"""Git installer: independent support repair and transaction-safe base promotion."""
from pathlib import Path
import argparse,hashlib,importlib.util,json,os,shutil,stat,sys,urllib.request,uuid,zipfile
ROOT=Path(__file__).resolve().parents[1]
+sys.path.insert(0,str(ROOT))
sys.path.insert(0,str(ROOT/'tools'))
from runtime_support import cache_dependency_files,prepared_lock,sha
from session_lock import app_lock
from git_transaction import begin,promote,recover,store
+from runtime_verification import reuse as reuse_verification,save as save_verification,inventory as runtime_inventory
+
+CONTRACTS={'lock_sha256':'installer/runtime-lock.json','registry_sha256':'mocap/runtime_registry.py',
+ 'support_sha256':'installer/git-support-lock.json','assets_sha256':'installer/external-assets.json'}
+
+def source_snapshot():
+ names=[*CONTRACTS.values(),'installer/engine.py','installer/verify_runtime.py',
+ 'tools/runtime_support.py','tools/git_managed_install.py','tools/runtime_verification.py',
+ 'tools/stage_assets.py','tools/support_components.py','tools/pinned_download.py']
+ names.extend(p.relative_to(ROOT).as_posix() for p in (ROOT/'installer/runtime_sources').rglob('*') if p.is_file() and p.suffix not in ('.pyc','.pyo'))
+ return {name:sha(ROOT/name) for name in names}
+
+def assert_sources(snapshot):
+ if source_snapshot()!=snapshot:
+ raise RuntimeError('Installation source changed while setup was running. Close other updates/editors and rerun install.cmd.')
def atomic(path,value):
temp=path.with_name(path.name+'.partial');temp.write_text(json.dumps(value,indent=2),encoding='utf8');os.replace(temp,path)
def setup():
parser=argparse.ArgumentParser();parser.add_argument('--assets-root',type=Path,default=None)
+ parser.add_argument('--verify-all',action='store_true',help='Recheck all installed runtime RECORD hashes and imports, ignoring recent verification metadata.')
args=parser.parse_args();folder=ROOT/'.setup';resources=folder/'bootstrap-git';resources.mkdir(parents=True,exist_ok=True)
cache_dependency_files(ROOT)
from stage_assets import stage as stage_assets
with app_lock(ROOT):
pending=folder/'git-sync.pending';pending.write_text('Run install.cmd to complete or retry.\n',encoding='utf8')
+ frozen=source_snapshot()
lock=prepared_lock(resources)
for origin,name in [(ROOT/'installer/engine.py','engine.py'),(ROOT/'installer/verify_runtime.py','verify_runtime.py'),(ROOT/'mocap/runtime_registry.py','runtime_registry.py')]:
shutil.copy2(origin,resources/name)
@@ -46,7 +64,9 @@ def setup():
if args.assets_root:stage_assets(args.assets_root,ROOT)
else:stage_assets(None,ROOT,download=True)
logs=folder/'logs';logs.mkdir(exist_ok=True)
- reused=engine.reusable_groups(ROOT,lock,None,logs)
+ ids=engine.group_ids(lock)
+ checked,retained=reuse_verification(ROOT,lock,ids,args.verify_all)
+ reused=engine.reusable_groups(ROOT,lock,None,logs,checked=checked)
stage,reports=engine.install_runtimes(ROOT,resources,lock,None,reused)
names=[*engine.TARGETS.values(),*sorted(roots)]
if not (ROOT/'SETUP_RECEIPT.json').is_file():
@@ -57,9 +77,15 @@ def setup():
if dest.exists() and (dest.is_symlink() or dest.stat().st_file_attributes&stat.FILE_ATTRIBUTE_REPARSE_POINT):
raise RuntimeError('A runtime path is a link; refusing to replace it: '+str(dest))
receipt=ROOT/'SETUP_RECEIPT.json';state=folder/'git-runtime-state.json'
+ assert_sources(frozen)
+ for group in lock['groups']:
+ key=group['key']
+ if key in retained and runtime_inventory(ROOT,group['target'])!=retained[key]['files']:
+ raise RuntimeError('Runtime files changed during setup: '+key+'. Rerun install.cmd --verify-all.')
journal,transaction=begin(ROOT)
try:
for name in names:
+ if name in {engine.TARGETS[key] for key in reused}:continue
incoming=(stage/name) if name in engine.TARGETS.values() else (support_stage/name)
if not incoming.exists():continue
promote(ROOT,journal,transaction,name,incoming)
@@ -69,16 +95,21 @@ def setup():
for path in sorted((ROOT/name).rglob('*')):
if path.is_file():
st=path.stat();inventory.append(dict(path=path.relative_to(ROOT).as_posix(),stat=[st.st_size,st.st_mtime_ns]))
- atomic(state,dict(lock_sha256=sha(ROOT/'installer/runtime-lock.json'),registry_sha256=sha(ROOT/'mocap/runtime_registry.py'),support_sha256=sha(support_path),assets_sha256=sha(ROOT/'installer/external-assets.json'),support_inventory=inventory))
+ atomic(state,dict(**{key:frozen[name] for key,name in CONTRACTS.items()},support_inventory=inventory))
+ assert_sources(frozen)
transaction['committed']=True;store(journal,transaction)
except BaseException:
recover(ROOT,engine.remove_owned)
raise
recover(ROOT,engine.remove_owned)
+ # A failure in an independent live/camera capability must not mark the
+ # already committed, compatible base installation as incomplete.
+ pending.unlink(missing_ok=True)
if support_stage.exists():engine.remove_owned(folder,support_stage)
- from setup_pear import prepare as prepare_pear
- prepare_pear()
- pending.unlink()
- print('Installation complete. Existing models and projects were retained.',flush=True)
+ try:save_verification(ROOT,lock,ids,reports,retained)
+ except (OSError,ValueError) as exc:
+ print('Recent verification metadata could not be saved; the next install will fully verify: '+str(exc),flush=True)
+ from tools.optional_support import prepare as prepare_support
+ prepare_support(ROOT)
if __name__=='__main__':setup()
diff --git a/tools/git_update.py b/tools/git_update.py
index ceda34f..dcfeaff 100644
--- a/tools/git_update.py
+++ b/tools/git_update.py
@@ -13,12 +13,16 @@ def main():
if git('status','--porcelain','--untracked-files=no'):raise RuntimeError('Tracked source files have local changes. Commit or back up changes before updating.')
if git('branch','--show-current')!='main':raise RuntimeError('Switch to the intended main branch before updating.')
before=git('rev-parse','HEAD');pending=ROOT/'.setup/git-sync.pending'
+ pending.parent.mkdir(parents=True,exist_ok=True)
+ previous_pending=pending.read_bytes() if pending.exists() else None
pending.write_text('Update requires installation and validation.\n',encoding='utf8')
try:
print('Updating the current branch...',flush=True)
subprocess.run(['git','-C',str(ROOT),'pull','--ff-only'],check=True)
except BaseException:
- if git('rev-parse','HEAD')==before:pending.unlink(missing_ok=True)
+ if git('rev-parse','HEAD')==before:
+ if previous_pending is None:pending.unlink(missing_ok=True)
+ else:pending.write_bytes(previous_pending)
raise
command=[str(Path(os.environ['SystemRoot'])/'System32/WindowsPowerShell/v1.0/powershell.exe'),'-NoProfile','-ExecutionPolicy','Bypass','-File',str(ROOT/'tools/git_bootstrap.ps1'),*sys.argv[1:]]
print('Checking the updated runtime configuration...',flush=True)
diff --git a/tools/optional_support.py b/tools/optional_support.py
new file mode 100644
index 0000000..c164568
--- /dev/null
+++ b/tools/optional_support.py
@@ -0,0 +1,36 @@
+"""Prepare independent capabilities after the base installation has committed."""
+from pathlib import Path
+import json
+import os
+
+
+def prepare(root):
+ from tools.setup_pear import prepare as pear
+ from tools.setup_pear_alignment import prepare as alignment
+ path = Path(root) / '.setup/git-components.json'
+ rows = {}
+
+ def record():
+ temp = path.with_suffix('.partial')
+ temp.write_text(json.dumps(dict(version=1, components=rows), indent=2), encoding='utf8')
+ os.replace(temp, path)
+
+ for name, action in [('PEAR', lambda: pear(align=False)), ('Camera alignment', alignment)]:
+ rows[name] = dict(status='preparing')
+ record()
+ try:
+ action()
+ except Exception as exc:
+ rows[name] = dict(status='unavailable', error=str(exc)[-1500:])
+ print(name + ' support unavailable: ' + str(exc), flush=True)
+ else:
+ rows[name] = dict(status='ready')
+ record()
+ failures = [name for name, row in rows.items() if row['status'] != 'ready']
+ if failures:
+ print('Installation complete with warnings. The base app is ready. Unavailable: '
+ + ', '.join(failures) + '. Rerun install.cmd to retry; see .setup/git-components.json. '
+ 'Automatic MAMMA gravity requires Camera alignment support.', flush=True)
+ else:
+ print('Installation complete. Existing models and projects were retained.', flush=True)
+ return rows
diff --git a/tools/pinned_download.py b/tools/pinned_download.py
new file mode 100644
index 0000000..96c8ecc
--- /dev/null
+++ b/tools/pinned_download.py
@@ -0,0 +1,166 @@
+"""Bounded HTTPS recovery for exact pinned support archives; standard library only."""
+from pathlib import Path
+import hashlib
+import http.client
+import json
+import os
+import re
+import socket
+import ssl
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+
+class HTTPSOnly(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ if urllib.parse.urlsplit(newurl).scheme != 'https':
+ raise ValueError('Support download redirected outside HTTPS')
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
+
+
+def digest(path):
+ result = hashlib.sha256()
+ with Path(path).open('rb') as stream:
+ for block in iter(lambda: stream.read(1024 * 1024), b''):
+ result.update(block)
+ return result.hexdigest()
+
+
+def valid(path, spec):
+ return path.is_file() and path.stat().st_size == spec['bytes'] and digest(path) == spec['sha256']
+
+
+def transient(exc):
+ if isinstance(exc, urllib.error.HTTPError):
+ return exc.code in (408, 416, 429, 500, 502, 503, 504)
+ if isinstance(exc, urllib.error.URLError):
+ return transient(exc.reason)
+ if isinstance(exc, ssl.SSLCertVerificationError):
+ return False
+ # Local disk/permission errors and malformed responses must not be retried.
+ return isinstance(exc, (ssl.SSLEOFError, ssl.SSLZeroReturnError, ConnectionError,
+ socket.timeout, socket.gaierror, http.client.IncompleteRead, http.client.RemoteDisconnected))
+
+
+def download(cache, name, spec, *, open_url=None, clock=time.monotonic, sleep=time.sleep, cancel=None):
+ if Path(name).name != name or name in ('', '.', '..') or ':' in name or '\\' in name:
+ raise ValueError('Invalid support download name')
+ url = spec['url']
+ if urllib.parse.urlsplit(url).scheme != 'https':
+ raise ValueError('Support download must use HTTPS')
+ size, expected = spec['bytes'], spec['sha256']
+ if not isinstance(size, int) or size <= 0 or not re.fullmatch(r'[0-9a-f]{64}', expected):
+ raise ValueError('Invalid support download pin')
+ cache = Path(cache)
+ cache.mkdir(parents=True, exist_ok=True)
+ path = cache / (name + '.zip')
+ partial = path.with_name(path.name + '.partial')
+ metadata = partial.with_name(partial.name + '.json')
+ pin = dict(url=url, bytes=size, sha256=expected)
+ if valid(path, spec):
+ return path
+
+ def reset():
+ partial.unlink(missing_ok=True)
+ metadata.unlink(missing_ok=True)
+
+ try:
+ if json.loads(metadata.read_text('utf8')) != pin:
+ reset()
+ except (OSError, ValueError, TypeError):
+ reset()
+ metadata.write_text(json.dumps(pin), encoding='utf8')
+ open_url = open_url or urllib.request.build_opener(HTTPSOnly()).open
+ began = clock()
+ # Large Blender archives get a size-aware total budget, independent of the
+ # finite socket timeout. All retries share this budget.
+ budget = max(180., min(7200., 120. + size / (128 * 1024)))
+
+ def check():
+ if cancel:
+ cancel()
+ if clock() - began >= budget:
+ raise TimeoutError('Support download total time limit reached: ' + name)
+
+ for attempt in range(3):
+ check()
+ start = partial.stat().st_size if partial.exists() else 0
+ if start >= size:
+ if valid(partial, spec):
+ os.replace(partial, path)
+ metadata.unlink(missing_ok=True)
+ return path
+ reset()
+ metadata.write_text(json.dumps(pin), encoding='utf8')
+ start = 0
+ headers = {'User-Agent': 'RGBMoCap-Setup/1', 'Accept-Encoding': 'identity'}
+ if start:
+ headers['Range'] = 'bytes=%d-' % start
+ print('Downloading %s from upstream (attempt %d/3, %.1f/%.1f MiB)...' %
+ (name, attempt + 1, start / 1024**2, size / 1024**2), flush=True)
+ try:
+ request = urllib.request.Request(url, headers=headers)
+ check()
+ with open_url(request, timeout=min(30., max(1., budget - (clock() - began)))) as response:
+ if urllib.parse.urlsplit(response.geturl()).scheme != 'https':
+ raise ValueError('Support response is not HTTPS')
+ status = response.status
+ resume = status == 206
+ if resume:
+ match = re.fullmatch(r'bytes (\d+)-(\d+)/(\d+)', response.headers.get('Content-Range', ''))
+ if (not match or int(match[1]) != start or int(match[3]) != size
+ or not start <= int(match[2]) < size or int(match[2]) != size - 1):
+ reset()
+ raise ValueError('Invalid support download Content-Range')
+ elif status == 200:
+ start = 0
+ else:
+ raise ValueError('Unexpected support download status: ' + str(status))
+ count, last = start, clock()
+ with partial.open('ab' if resume else 'wb') as output:
+ while True:
+ check()
+ # read1 returns available data rather than waiting to
+ # fill a large buffer during a slow, trickling transfer.
+ chunk = getattr(response, 'read1', response.read)(256 * 1024)
+ if not chunk:
+ break
+ count += len(chunk)
+ if count > size:
+ raise ValueError('Support download exceeds pinned size')
+ output.write(chunk)
+ if clock() - last >= 2:
+ print('Downloading %s: %.1f/%.1f MiB (%.0f s)' %
+ (name, count / 1024**2, size / 1024**2, clock() - began), flush=True)
+ last = clock()
+ if count != size:
+ raise http.client.IncompleteRead(b'', size - count)
+ check()
+ if not valid(partial, spec):
+ reset()
+ raise ValueError(name + ' archive hash or size mismatch')
+ os.replace(partial, path)
+ metadata.unlink(missing_ok=True)
+ return path
+ except Exception as exc:
+ if isinstance(exc, ValueError):
+ reset()
+ if not transient(exc) or attempt == 2:
+ if isinstance(exc, urllib.error.HTTPError):
+ exc.close()
+ raise
+ if isinstance(exc, urllib.error.HTTPError) and exc.code == 416:
+ reset()
+ metadata.write_text(json.dumps(pin), encoding='utf8')
+ check()
+ delay = 1. * (attempt + 1)
+ if isinstance(exc, urllib.error.HTTPError):
+ retry_after = exc.headers.get('Retry-After', '') if exc.headers else ''
+ if retry_after.isdigit():
+ delay = min(10., max(delay, float(retry_after)))
+ exc.close()
+ print('Transient support download failure for %s (%s); retrying in %.0f s.' %
+ (name, type(exc).__name__, delay), flush=True)
+ sleep(delay)
diff --git a/tools/runtime_verification.py b/tools/runtime_verification.py
new file mode 100644
index 0000000..d2fda3c
--- /dev/null
+++ b/tools/runtime_verification.py
@@ -0,0 +1,107 @@
+"""Bounded metadata reuse of a successful full runtime verification.
+
+This is change detection for ordinary update/retry, not an authenticity check.
+--verify-all always runs the existing RECORD hashes and import checks.
+"""
+from pathlib import Path
+import hashlib
+import json
+import os
+import stat
+import time
+
+MAX_AGE_SECONDS = 7 * 24 * 60 * 60
+MAX_FILES = 250000
+MAX_CACHE_BYTES = 64 * 1024 * 1024
+
+
+def inventory(root, target):
+ root = Path(root).resolve()
+ if target not in {'runtime', 'runtime_gui', 'runtime_flow', 'runtime_hand', 'runtime_htd', 'runtime_exmr'}:
+ raise ValueError('Unexpected runtime inventory target')
+ folder = root / target
+ if not folder.is_dir():
+ raise ValueError('Runtime directory is missing: ' + target)
+ if folder.is_symlink() or getattr(folder.lstat(), 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT:
+ raise ValueError('Runtime directory is a link: ' + target)
+ rows = {}
+ def unreadable(exc):
+ raise exc
+ for current, dirs, files in os.walk(folder, onerror=unreadable):
+ base = Path(current)
+ for name in [*dirs, *files]:
+ path = base / name
+ info = path.lstat()
+ if path.is_symlink() or getattr(info, 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT:
+ raise ValueError('Runtime inventory contains a link: ' + target)
+ dirs[:] = sorted(name for name in dirs if name != '__pycache__')
+ for name in sorted(files):
+ path = base / name
+ if path.suffix.lower() in ('.pyc', '.pyo'):
+ continue
+ info = path.stat()
+ rows[path.relative_to(folder).as_posix()] = [info.st_size, info.st_mtime_ns, info.st_ctime_ns]
+ if len(rows) > MAX_FILES:
+ raise ValueError('Runtime inventory exceeds the supported file count')
+ if not rows:
+ raise ValueError('Runtime inventory is empty: ' + target)
+ return rows
+
+
+def verifier_identity(root):
+ return hashlib.sha256(b''.join((Path(root) / name).read_bytes() for name in
+ ('installer/engine.py', 'installer/verify_runtime.py', 'mocap/runtime_registry.py',
+ 'tools/runtime_verification.py'))).hexdigest()
+
+
+def reuse(root, lock, ids, force=False):
+ """Return unchanged fully verified groups; missing/old caches require full checks."""
+ if force:
+ return {}, {}
+ root = Path(root)
+ try:
+ receipt = json.loads((root / 'SETUP_RECEIPT.json').read_text('utf8'))
+ verifier = verifier_identity(root)
+ except (OSError, ValueError, TypeError):
+ return {}, {}
+ checked, records = {}, {}
+ for group in lock['groups']:
+ key = group['key']
+ if group.get('base') and group['base'] not in checked:
+ continue
+ try:
+ path = root / '.setup/runtime-verification' / (key + '.json')
+ if path.stat().st_size > MAX_CACHE_BYTES:
+ continue
+ row = json.loads(path.read_text('utf8'))
+ age = time.time() - row['verified_at']
+ if (row['version'] != 1 or row['verifier'] != verifier or row['group_id'] != ids[key]
+ or receipt['group_ids'][key] != ids[key] or not 0 <= age < MAX_AGE_SECONDS
+ or not isinstance(row['report'], dict) or not row['report']
+ or row['report'] != receipt['runtimes'][key]
+ or not isinstance(row['files'], dict) or not row['files']
+ or inventory(root, group['target']) != row['files']):
+ continue
+ checked[key], records[key] = row['report'], row
+ print('Using recent full verification and unchanged file metadata: ' + key, flush=True)
+ except (OSError, ValueError, KeyError, TypeError):
+ continue
+ return checked, records
+
+
+def save(root, lock, ids, reports, retained):
+ root = Path(root)
+ folder = root / '.setup/runtime-verification'
+ folder.mkdir(parents=True, exist_ok=True)
+ verifier = verifier_identity(root)
+ for group in lock['groups']:
+ key = group['key']
+ # A fast reuse must never extend the full-verification expiry.
+ if key in retained:
+ continue
+ row = dict(version=1, verifier=verifier, group_id=ids[key], verified_at=time.time(),
+ report=reports[key], files=inventory(root, group['target']))
+ path = folder / (key + '.json')
+ temporary = path.with_suffix('.partial')
+ temporary.write_text(json.dumps(row, separators=(',', ':')), encoding='utf8')
+ os.replace(temporary, path)
diff --git a/tools/setup_pear.py b/tools/setup_pear.py
index 7fe84f1..dcab98f 100644
--- a/tools/setup_pear.py
+++ b/tools/setup_pear.py
@@ -7,7 +7,7 @@ from mocap.pear_runtime import identity,base_identity,configuration
from installer.pear_adapters import adapt
from tools.session_lock import app_lock
-def prepare(cache=None):
+def prepare(cache=None,align=True):
"""Called under the installer lock, after committing the shared base."""
from tools.support_components import download
lock=json.loads((ROOT/'installer/pear-sources.json').read_text(encoding='utf-8'))
@@ -16,15 +16,21 @@ def prepare(cache=None):
except (OSError,ValueError,KeyError,TypeError):current=None
if current is not None:
print('Keeping verified PEAR support over the shared runtime.',flush=True)
- from tools.setup_pear_alignment import prepare as prepare_alignment
- prepare_alignment(cache);return current
+ if align:
+ from tools.setup_pear_alignment import prepare as prepare_alignment
+ prepare_alignment(cache)
+ return current
base=base_identity()
- folder=ROOT/'runtime_pear'/('support-'+identity()[:20]+'-'+uuid.uuid4().hex[:8]);folder.mkdir(parents=True)
+ folder=ROOT/'runtime_pear'/('support-'+identity()[:20]+'-'+uuid.uuid4().hex[:8])
cache=Path(cache) if cache else ROOT/'.setup/pear-downloads';cache.mkdir(parents=True,exist_ok=True)
try:
+ archives={}
for name,row in lock['sources'].items():
print('Preparing PEAR support: '+name,flush=True)
- archive=download(cache,name,dict(row,filename=name+('.whl' if name=='roma' else '.zip')))
+ archives[name]=download(cache,name,dict(row,filename=name+('.whl' if name=='roma' else '.zip')))
+ # Do not accumulate empty/partly extracted generations on network failure.
+ folder.mkdir(parents=True)
+ for name,archive in archives.items():
with zipfile.ZipFile(archive) as z:
for info in z.infolist():
p=Path(info.filename)
@@ -50,8 +56,10 @@ def prepare(cache=None):
files={p.relative_to(folder).as_posix():[p.stat().st_size,p.stat().st_mtime_ns] for p in folder.rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.suffix not in ('.pyc','.pyo')}
atomic_json(ROOT/'.setup/pear-runtime.json',dict(version=2,identity=identity(),base_identity=base,folder=folder.relative_to(ROOT).as_posix(),files=files))
print('PEAR support ready. Existing runtime packages, models and projects were not changed.',flush=True)
- from tools.setup_pear_alignment import prepare as prepare_alignment
- prepare_alignment(cache);return folder
+ if align:
+ from tools.setup_pear_alignment import prepare as prepare_alignment
+ prepare_alignment(cache)
+ return folder
except Exception:
# Keep failed staging for diagnosis; no previous configuration is overwritten.
print('PEAR setup failed. Existing support generations were preserved.',flush=True);raise
diff --git a/tools/setup_pear_alignment.py b/tools/setup_pear_alignment.py
index 7ed9f64..d23c31a 100644
--- a/tools/setup_pear_alignment.py
+++ b/tools/setup_pear_alignment.py
@@ -3,7 +3,7 @@ from pathlib import Path
import json,zipfile,stat,uuid,subprocess
from mocap.paths import ROOT
from mocap.storage import atomic_json
-from mocap.pear.alignment_support import identity,configuration
+from mocap.pear.alignment_support import identity,base_identity,configuration
def prepare(cache=None):
from tools.support_components import download
@@ -11,11 +11,15 @@ def prepare(cache=None):
current=configuration();print('Keeping verified PEAR camera alignment support.',flush=True);return current
except (OSError,ValueError,KeyError,TypeError):pass
lock=json.loads((ROOT/'installer/pear-alignment.json').read_text('utf8'))
+ base=base_identity()
cache=Path(cache) if cache else ROOT/'.setup/pear-downloads';cache.mkdir(parents=True,exist_ok=True)
- folder=ROOT/'runtime_pear'/('alignment-'+identity()[:16]+'-'+uuid.uuid4().hex[:8]);folder.mkdir(parents=True)
+ folder=ROOT/'runtime_pear'/('alignment-'+identity()[:16]+'-'+uuid.uuid4().hex[:8])
+ archives={}
for name,row in lock['sources'].items():
print('Preparing PEAR camera alignment: '+name,flush=True)
- archive=download(cache,name,row)
+ archives[name]=download(cache,name,row)
+ folder.mkdir(parents=True)
+ for name,archive in archives.items():
with zipfile.ZipFile(archive) as z:
for info in z.infolist():
p=Path(info.filename)
@@ -29,7 +33,8 @@ def prepare(cache=None):
target=folder/p;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(z.read(info))
code='import sys;sys.path.insert(0,'+repr(str(ROOT))+');from mocap.runtime_registry import activate;activate('+repr(str(ROOT))+',"flow");sys.path.insert(0,'+repr(str(folder))+');import torch,kornia,kornia_rs;from geocalib import GeoCalib;assert kornia.__version__=="0.7.4";assert torch.cuda.is_available();print("PEAR camera alignment imports verified")'
subprocess.run([str(ROOT/'runtime/python.exe'),'-I','-X','utf8','-B','-c',code],check=True,timeout=180)
+ if base_identity()!=base:raise RuntimeError('Camera alignment base runtime changed during setup; retry install.cmd.')
atomic_json(folder/'PROVENANCE.json',lock)
files={p.relative_to(folder).as_posix():[p.stat().st_size,p.stat().st_mtime_ns] for p in folder.rglob('*') if p.is_file()}
- atomic_json(ROOT/'.setup/pear-alignment.json',dict(identity=identity(),folder=folder.relative_to(ROOT).as_posix(),files=files))
+ atomic_json(ROOT/'.setup/pear-alignment.json',dict(identity=identity(),base_identity=base,folder=folder.relative_to(ROOT).as_posix(),files=files))
print('PEAR camera alignment support ready; model weights remain separate.',flush=True);return folder
diff --git a/tools/support_components.py b/tools/support_components.py
index 94990ad..74c6f48 100644
--- a/tools/support_components.py
+++ b/tools/support_components.py
@@ -14,22 +14,13 @@ def valid(path,spec):
return path.is_file() and path.stat().st_size==spec['bytes'] and digest(path)==spec['sha256']
def download(cache,name,spec):
- path=cache/(name+'.zip'); partial=cache/(name+'.zip.partial')
- if valid(path,spec):return path
- if not spec['url'].startswith('https://'):raise ValueError('Support download must use HTTPS')
- print('Downloading '+name+' from upstream...',flush=True)
- try:
- with urllib.request.urlopen(spec['url'],timeout=120) as response,partial.open('wb') as output:
- shutil.copyfileobj(response,output,1024*1024)
- if not valid(partial,spec):raise ValueError(name+' archive hash or size mismatch')
- os.replace(partial,path)
- finally:
- if partial.exists():partial.unlink()
- return path
+ from tools.pinned_download import download as fetch
+ return fetch(cache,name,spec)
def safe_members(archive,root):
total=0
- for item in archive.infolist():
+ for count,item in enumerate(archive.infolist(),1):
+ if count>100000:raise ValueError('Support archive has too many files')
name=item.filename
path=PurePosixPath(name)
if '\\' in name or path.is_absolute() or '..' in path.parts or not path.parts or path.parts[0]!=root or ':' in name: