Release V3.8 source, illustrated manual and Spectrum workflow

This commit is contained in:
ukr8b3g-cmyk
2026-09-07 21:25:51 +09:00
parent 0a7c6703b7
commit 315146946e
208 changed files with 74579 additions and 24542 deletions
+40
View File
@@ -0,0 +1,40 @@
tests/
tools/*
!tools/__init__.py
!tools/p20_file_backed_tensor_poc.py
!tools/verify_runtime.py
.pytest_cache/
**/__pycache__/
*.pyc
*.pyo
# Local backup archives are not distribution assets. The official workflow
# archive is re-included explicitly below.
*.zip
# Internal source/development records and the source-tree Manifest are not part
# of the Registry archive. REGISTRY_MANIFEST.sha256 covers the staged package.
AGENTS.md
PROJECT_STATE.md
WORKLOG.md
MANIFEST.sha256
# Repository-only automation and test configuration are not runtime assets.
.github/
.gitignore
.gitattributes
pytest.ini
# Ship only current V3.8 public contracts. Historical validation notes,
# version-specific design documents, and their screenshots stay in source.
docs/*
!docs/N2B_BRANCH_PROVENANCE_CONTRACT_V1.md
!docs/V38_OPEN_INTEGRATION_CONTRACT.md
!docs/V38_RELEASE_AND_MIGRATION.md
# One user-supplied Spectrum graph, in JSON and ZIP forms. External custom-node
# dependencies are documented, not bundled. Historical examples stay in Git.
examples/*
!examples/workflows/
examples/workflows/*
!examples/workflows/MiniMax_H3_Continuum_V38.json
!examples/workflows/MiniMax_H3_Continuum_V38.zip
+3
View File
@@ -0,0 +1,3 @@
# Release manifests and the user-supplied workflow ZIP hash exact file bytes.
# Keep Git checkout/add from rewriting line endings on Windows or Linux.
* -text
+52 -3
View File
@@ -1,7 +1,9 @@
# AGENTS.md
## Scope
MiniMax H3 Continuum V3.7.0 for ComfyUI. Treat the accepted V3.6 generation defaults as the current Production baseline; preserve V3.6.1/V3.5.3/V3.4 node IDs, public contracts, and saved-workflow loading without letting legacy or Experimental controls change current behavior. Still Image Guide remains Experimental / Production HOLD.
MiniMax H3 Continuum V3.8 for ComfyUI. Treat the accepted V3.7 Production engine and the accepted V3.8 GPU Gates as the current execution baseline. V3.8 supports its approved current public surface; pre-V3.8 public Node IDs and saved workflows are distributed through their historical Release/tag and are not V3.8 compatibility requirements. Experimental controls must not change current Production behavior. Still Image Guide remains Experimental / Production HOLD.
Current release-hygiene baseline: O1 and AUDIO-R1 are PASS; the public surface is seven nodes; Sampling Contract is v5; Run Storage is v3; State, Session, Assembly, Driving Audio, and Second Pass/O1 contracts are protected. Release / Registry readiness remains HOLD until package staging is rerun for the latest working tree.
## Non-negotiable rules
- Follow ComfyUI Core behavior for user-facing validation. Continuum-only prompt restrictions, model allowlists, compatibility gates, and policy-based execution stops are prohibited.
@@ -10,7 +12,7 @@ MiniMax H3 Continuum V3.7.0 for ComfyUI. Treat the accepted V3.6 generation defa
- Keep warnings diagnostic-only unless execution cannot continue safely. Hard stops are limited to corrupt internal contracts such as invalid latent/layout topology, incompatible Assembly Plan data, broken stored revision schema/hash, unusable required payloads, or decode formats that cannot be assembled.
- Unknown upstream nodes, models, wrappers, or merged models must not be rejected solely because they are unknown.
- Keep legacy `strict_compatibility` inputs loadable for old workflows, but ignore their value. They must never enable blocking behavior.
- Before every change, run `tools\snapshot.ps1` against the authoritative source. Preserve the compact V3.4 UI unless the user explicitly approves a UI change.
- Before every change, run `tools\snapshot.ps1` against the authoritative source. Preserve the current V3.8 backend schema and serialized widget order until a separately approved UI/public-surface implementation changes them.
- In public templates, connection examples, screenshots, and documentation, keep ComfyUI Core nodes on their standard display titles. Do not assign custom titles to Core nodes, because users must be able to distinguish Core nodes from Continuum and third-party custom nodes immediately.
- Runtime tests must record the workflow, prompt, media inputs, model/LoRA/sampler/step settings, dimensions, chunk count/duration, elapsed time, and observed result. Inspect embedded workflow metadata when present.
- Do not globally replace `PackedLayout`, `MiniMaxH3.extra_conds`, or other ComfyUI classes.
@@ -23,7 +25,7 @@ MiniMax H3 Continuum V3.7.0 for ComfyUI. Treat the accepted V3.6 generation defa
- V2 must not decode Video/Audio VAE between H3 chunks.
- Accepted full chunk latents remain on CPU; do not accumulate generated chunks in VRAM.
- Spectrum history must remain run-scoped through its public sampler wrappers; never import Spectrum private runtime functions.
- Changes must preserve V1 node identifiers and State schema unless an explicit migration is included.
- Do not treat V1-V3.7 public Node IDs as V3.8 compatibility requirements. Removing their V3.8 registration still requires an explicit audited public-surface change; historical implementations may remain internally while V3.8 depends on them. Preserve State/Session data safely unless a separately approved migration replaces it.
## Project files
@@ -32,6 +34,49 @@ MiniMax H3 Continuum V3.7.0 for ComfyUI. Treat the accepted V3.6 generation defa
- `WORKLOG.md`: append-only summaries of completed work and evidence.
- Do not duplicate long history across these files. Update `PROJECT_STATE.md` when facts change and append one concise entry to `WORKLOG.md` after completed work.
## Product direction
- Product definition: H3 Continuum is a Production Sampler that generates, reviews, partially regenerates, and resumes long-form video without restarting the entire work.
- Keep one discoverable Main surface plus an in-node `Advanced` disclosure. Do not require users to discover a hidden node property before normal Production controls become usable.
- Evaluate new work against three pillars: `Continuation Quality`, `Non-destructive Production`, and `Open Integration`. Prefer external integration or `Deferred` when work does not clearly strengthen one of them.
- `Main / Production` must be simple by default and expose Production controls when expanded. Do not develop a separate Easy product path. Its primary flow is Continuation Quality, Review/Regenerate, Resume/Branch, and Finalize.
- `Advanced` contains Second Pass, Selective/Temporal Refine, external integration, and diagnostics. Experimental or development-only nodes do not become public merely because their code and tests are retained.
- Do not build an all-in-one node pack. Keep external Upscaler, TensorRT, FBC, Sol-Attn, Spectrum, Director, Prompt Planner, Save/Encoder, and Core or external VAE Decode outside Continuum unless an explicit integration contract is approved.
- Do not grow the Main Sampler with unbounded sockets or serialized widgets. Prefer stable latent/assembly/refine/run contracts and external adapters.
- V3.8 is the current supported product. V3.7 and earlier remain obtainable from historical GitHub Release/tag rather than being carried as public V3.8 Node-ID compatibility.
- A saved workflow that references a Node ID not exported by V3.8 may load as an unknown node. State this explicitly in the V3.8 README, Release Notes, and migration note, and direct users to the corresponding historical Release/tag. Do not restore old registrations solely to hide this intentional support boundary.
- The accepted V3.8 launch surface is seven searchable nodes: Sampler V3.8, Reference Audios, Finalize, Load Image, Load Audio, Load Video, and Second Pass. AUDIO-R1 is the approved one-node modular-input exception; existing six node IDs and schemas remain compatible.
- Public-surface cleanup changes export mappings only. Do not physically delete legacy classes/modules while current V3.8 imports or inherits them, and do not exclude runtime-imported legacy modules from the package archive.
- Main UI disclosure state is presentation-only. It must not enter Sampling or Run Storage identity, alter backend kwargs, or rewrite values of hidden widgets. Connection-specific size controls must be visible when their corresponding input is connected.
- Keep the accepted V3.8 Main facade explicit rather than inference-driven. Its first controls are `Prompt Format`, `Continuity`, `Base Seed`, `Control After Generate`, and `Audio Continuity`, followed by independent `Chunks` and `Seconds per Chunk`, a read-only calculated `Total Length`, an always-visible `Size Source = First Image | Manual`, the applicable Resolution or exact Width/Height controls, Run, Progress, a clear Queue-ready summary, and one Advanced disclosure. Do not show permanent connected/unconnected input badges, infer an Input Mode, derive chunks from a total-duration selector, or automatically change Size Source when an upstream node is bypassed or disconnected. When the canonical backend revision is `review_ready`, replace the setup facade with the amber review status and the three explicit Queue actions; do not infer this state in the frontend.
- Keep Main UI numbers compact: Chunks and pixel dimensions are integers, and Seconds per Chunk shows a decimal only when one is meaningful. Use user-facing `Full Video`, `Review by Chunk`, and `Resume & History` labels while preserving their existing backend values. Review action buttons must remain hidden until the canonical Run Storage revision reports `review_ready`; never infer readiness from frontend widgets alone. Hide empty Render History and keep Advanced settings behind the visible in-node disclosure.
- Every visible V3.8 Main, Advanced, Review, and Render History control, plus every public Sampler input, must have non-empty mouse-over help. Context-sensitive controls must explain the currently selected behavior; `Output Size` must explicitly distinguish First Image for I2VA/FL2VA from Manual Width/Height for T2VA or workflows without a First Image.
- Completed-review UI exception (2026-09-07, user-authorized repair): a canonical backend revision with status `complete` must retain its completion panel, Back to Settings/Return to Review, and non-empty Render History. Show Try this chunk again only when that revision carries a valid review_unit, as already supported by the backend. Hide the no-op Continue/Finish buttons on completion. This extends the earlier review_ready-only presentation rule; never rewrite backend status, infer readiness from widget counts, or invent a retry unit for a full-run completion.
- Keep Core node display names unchanged in every public workflow.
- User-approved distribution exception (2026-09-07): publish the supplied Spectrum graph as `MiniMax_H3_Continuum_V38.json` and the user's matching ZIP, byte-for-byte, including its existing titles, prompts, media names, and saved settings. It is one graph with external Spectrum, rgthree, KJNodes, and ComfyUI-Easy-Use dependencies, not a Core-only template. Document setup differences instead of silently rewriting the workflow. Keep unrelated backup ZIPs out of new commits/packages.
- Hi-Res Fix is not part of the new standard workflow. Preserve its historical implementation until cleanup is approved; use Second Pass as the external latent-processor bridge.
- Keep P1a First Block Cache and P2 boundary-aware Sol-Attn `Deferred`. Keep A5 and A8b `HOLD` under their recorded release contracts. Issue #13 reporter-exact R3 remains the highest Continuation Quality investigation when its required workflow is available.
## H3 completion review handoff
- After every implementation or Gate is complete and its local validation report is ready, send that self-contained completion report to the pinned ChatGPT task titled `H3情報チェック` before starting the next phase.
- The fixed current destination is task ID `6a94b91e-af7c-83e8-be18-ddc504f690c4` (pinned index 3). A second older task has the same title; do not send to the unpinned duplicate.
- Wait for and read the review reply, then bring its conclusions and requested corrections back into the active Continuum task as feedback. Treat the reply as review input under the user's authority; preserve the repository rules and request approval where a proposed change expands scope.
- Do not duplicate a handoff that the user explicitly says they already completed manually. If the destination is unavailable or the reply requires user judgment, stop and report that condition instead of silently skipping the review.
## A8b and A5 HOLD release contracts
- 2026-09-05 explicit user exception ("許可、許可。"): Issue13 R3B may run one isolated Video-only weak tapered context-noise A/B experiment before reporter-exact R3. This waives only the reporter-exact/independence prerequisite for that diagnostic. Keep Production/source runtime unchanged, Audio/masks/depth/Seed/SIGMAS/grouping unchanged, default OFF bit-exact, and pass CPU/Shadow/Replay before GPU. Restore clean exported prefix after the diagnostic perturbation. No combined interventions, A5 work, public controls, or Production promotion are authorized. General A8b and Release HOLD remain; GPU-audit sharing is limited to the fixed H3情報チェック task.
- A8a is the accepted read-only baseline: full pytest `1041`, Manifest `242/242`, every observer record has `execution_applied=false`, and Production/Sampling/Run Storage/State/Session/Assembly parity is preserved.
- Keep A8b execution policy on HOLD until one intervention type is specified and approved. Do not change context, transport, mask, latent, or conditioning in combination. Seed, SIGMAS, and physical grouping remain unchanged unless separately approved.
- Exclude the failed Issue #13 candidates from A8b: effective 13-frame history, 22-frame Video prefix with 75% preservation, Soft Re-anchor, and Production Fixed Prefix/teacher forcing.
- Before A8b GPU Sampling, either complete reporter-exact Issue #13 R3 or prove by static and replay evidence that the proposed intervention is independent of the recursive-feedback path. Then pass an A8a Shadow/Replay Gate with no unnecessary action, Terminal misclassification, or Run Storage replay difference.
- Any approved A8b implementation starts Experimental and Default OFF. Existing Production must remain bit-exact, public schema changes require separate approval, and external Sage/Sol/Spectrum wrappers must remain intact.
- Keep A5 Reference Video Influence Schedule/Fade on HOLD until reporter-exact Issue #13 R3 classifies Reference Video as unrelated, an amplification-only factor with a defined safe range, or a necessary/strong cause candidate. Only the first two outcomes may unlock Experimental A5 work; the last keeps A5 on HOLD.
- A5 OFF must remain bit-exact with Production. Initial A5 may change only Reference Video influence; it must not change Video continuation, Audio, Seed, SIGMAS, Terminal Merge, Assembly, or Run Storage. Do not implement A5 and A8b concurrently.
- A5 promotion requires at least `3x5` plus a long-form continuation GPU Gate covering trajectory, identity, saturation, contrast, sharpness, and highlight drift. Short-form evidence alone is insufficient.
## Validation
```bash
@@ -42,12 +87,16 @@ Runtime installer verification must check native PackedLayout behavior and all r
GPU checks must cover Sage only, Sage+Sol, Sage+Spectrum, and Sage+Sol+Spectrum with identical prompts and seeds. V2 must also be compared against the equivalent V1 3×5-second graph.
- Once the user has explicitly approved a GPU run, free-VRAM and process-RSS readings are advisory. Do not refuse to start or stop an otherwise healthy run solely because a numeric free-VRAM/RSS threshold was crossed. Continue unless an actual CUDA/PyTorch/Windows OOM or allocation failure, backend crash/health failure, NaN/Inf, or a structural layout/AV/duration integrity failure makes the run unsafe or invalid.
## Reusable local environment
- Source repository: `D:\Codex\_git_push_work\ComfyUI-H3-Continuum`
- Primary tested runtime: `D:\StabilityMatrix\Data\Packages\ComfyUI_W\custom_nodes\ComfyUI-H3-Continuum`
- Secondary runtime: `D:\StabilityMatrix\Data\Packages\ComfyUI_WAN\custom_nodes\ComfyUI-H3-Continuum`
- User-organized V3.8 test videos and related test artifacts are under `D:\output\video\comfy_video\v38`. Reuse that path when inspecting prior V3.8 outputs; do not move, rename, or delete its contents without explicit approval.
- Restart ComfyUI_W with `D:\StabilityMatrix\Data\Packages\ComfyUI_W\venv\Scripts\python.exe`. Do not launch the base executable reported by `Get-Process.Path`; it omits the venv dependencies even though it is the resolved process image.
- When the source adds or changes runtime imports, do not synchronize only the visibly changed files. Install the complete current `REGISTRY_MANIFEST.sha256` set, or first prove a dependency-complete narrow set; then verify registration through the live ComfyUI `object_info` endpoint. A standalone verifier launched from the source checkout is not sufficient evidence for a mixed installed runtime.
- Reuse the repository's existing pytest configuration and helper scripts instead of rediscovering paths on every task.
- Read this file before each task. Record durable project decisions, paths, commands, failure causes, and validation methods here so later work reuses them instead of restarting from zero.
- GitHub authentication for this repository is already configured. Do not request a new login or token unless an actual authentication command fails.
+28
View File
@@ -1,5 +1,33 @@
# Changelog
## 3.8.0
### Added
- Established the seven-node V3.8 public surface: Sampler V3.8, Finalize, Load Image, Load Audio, Load Video, Second Pass, and the modular Reference Audios helper. Unreleased Easy facade prototypes remain in source but are not registered.
- Added `H3 Continuum Sampler V3.8` with shared `Draft` 0.30 MP, `Balanced` 0.60 MP, `Native 768`, and `Custom MP` resolution presets.
- Added `Review Each Chunk`, `Continue / Next`, `Regenerate Current`, and `Finish Remaining` controls backed by Run Storage review branches and canonical-head recovery.
- Publish one user-supplied V3.8 Spectrum workflow unchanged as JSON and ZIP. It requires Spectrum, rgthree, KJNodes, and ComfyUI-Easy-Use; the same graph can be switched to a task-matched LightX2V Turbo LoRA.
- Added Continuum Image, Audio, and Video loaders with explicit native bypass behavior for optional workflow inputs.
- Added `H3 Continuum Reference Audios`, which bundles up to three ordered Core-native standalone audio references behind one appended V3.8 Sampler socket while preserving the legacy single-reference path.
- Replaced the Main `Landscape / Portrait / Square` choice with a two-path `Size Source`: preserve the connected First Image aspect at the selected preset, or enter an exact aligned Manual Width and Height.
### Improved
- Integrated Driving Audio with Review, Smart Regenerate, Finish Remaining, and restart persistence.
- Preserved FL2VA Long Terminal Merge as one atomic physical review unit, including Smart Regenerate of the complete terminal pair.
- Reused one resolution resolver across Easy and normal V3.8 samplers while leaving the V3.7 schema and Production path unchanged.
- Extended Run Storage with Review lifecycle metadata, prefix reuse, nonce branches, and latest canonical-head restoration without changing the sampling identity contract.
- Added a frontend-only `Basic / Production` node property for Sampler V3.8. It changes presentation only and preserves the Python schema, widget order and values, backend inputs, Sampling identity, and Run Storage identity.
- Added Registry packaging rules that exclude tests, tools, diagnostics, Labs assets, and historical workflows while retaining all runtime-imported implementation modules.
- Kept the old V3.8 Aspect input as a hidden compatibility field. Saved Auto workflows migrate to First Image, while saved Landscape, Portrait, and Square workflows migrate to the same resolved Manual canvas.
### Notes
- Second Pass / `refine_context` is not supported on a partial Review sequence. Complete Review before running Second Pass.
- The 16GB GPU Gate passed with small headroom: Strict Minimal peaked at `14.96 GiB`, and complex accepted gates reached about `15.5-15.6 GiB`. Results vary by environment and are not a universal 16GB guarantee.
- Still Image Guide remains Experimental. V3.7 and earlier Node IDs are not exported by V3.8; workflows using them can appear with unknown nodes and should be opened with the matching historical Release/tag.
## 3.7.0
- Added `H3 Continuum Sampler V3.7` with one optional Still Image Guide input while preserving the V3.6 required-input schema, Production defaults, and saved-workflow compatibility.
+27 -13
View File
@@ -1,22 +1,36 @@
ComfyUI-H3-Continuum 3.2.1 — インストール
ComfyUI-H3-Continuum V3.8 — インストール
1. ComfyUIを終了します。
2. ZIPを展開します。
3. `ComfyUI-H3-Continuum` フォルダーを ComfyUI/custom_nodes/ に配置します。
4. 旧 `ComfyUI-H3-Continuum-Join` が残っている場合は退避します。
5. ComfyUIを再起動します。
6. 旧UIが残る場合はブラウザをハードリロードします。
2. 既存の `ComfyUI-H3-Continuum` を更新する場合は、作業中のworkflowとRun Storageを先に退避します。
3. ZIPを展開し、`ComfyUI-H3-Continuum` フォルダーを `ComfyUI/custom_nodes/` に配置します。
4. ComfyUIを再起動します。旧UIが残る場合はブラウザをハードリロードします。
StabilityMatrix標準例:
D:\StabilityMatrix\Data\Packages\ComfyUI_W\custom_nodes\ComfyUI-H3-Continuum\
StabilityMatrixの配置例:
`D:\StabilityMatrix\Data\Packages\ComfyUI_W\custom_nodes\ComfyUI-H3-Continuum\`
自動インストール:
install_windows.bat
PowerShellによる自動インストール:
`install_windows.ps1`
標準検証:
V3.8の公開ノードは7個です。
- H3 Continuum Sampler V3.8
- H3 Continuum Reference Audios
- H3 Continuum Finalize
- H3 Continuum Load Image
- H3 Continuum Load Audio
- H3 Continuum Load Video
- H3 Continuum Second Pass
標準の入出力経路は、Sampler V3.8 → ComfyUI Core Video / Audio Decode → Finalize → Core Create Video → Core Save Videoです。Hi-Res Fixは標準経路に含みません。サイズは `Size Source = First Image`(初期画像がある場合)または `Manual`(Width / Heightを入力)で指定します。
配布Workflowは `examples/workflows/MiniMax_H3_Continuum_V38.json` と同じJSONを含む同名ZIPです。このZIPはWorkflowだけを格納しており、手順3のカスタムノード本体ZIPとは別物です。Spectrum初期設定のgraphをそのまま配布するため、Spectrum、rgthree、KJNodes、ComfyUI-Easy-Useを別途導入してください。Turboへ切り替えてもこれらのノードはgraphに残ります。モデルや画像・音声は含みません。保存済みファイル名は各自の入力へ置き換え、不要な入力はOFFにしてください。
最小確認:
- chunks: 2 または 3
- chunk_seconds: 5.0
- continuity: Balanced — 22 frames
- Audio Seam: Off(標準)/ Auto(音声境界補正を試す場合)
- Sequence Prompt: Text (Multiline)を接続
- 最終Video/Audio VAE DecodeはComfyUI Coreノードへ接続
- 最終Video/Audio VAE Decodeと保存はComfyUI Coreノードへ接続
- Reference Audioを複数使う場合は `H3 Continuum Reference Audios` helperへ最大3本を接続
同一機能の旧フォルダーや旧Manager導入版を重複配置しないでください。V3.7以前のNode IDを使う保存workflowは、その対応Release/tagで開いてください。
+112 -44
View File
@@ -1,15 +1,17 @@
dca65fb1393e67f59c6f81f9411e3e745eb8f1097e9a2adf7ffc6f4e3901ca9f __init__.py
3e7a1ec3380be2a222c8a3e9b8a6bb184d3a760478957f48186438f15235bdba branch_provenance.py
4f6feeb2f63a9285b0e76fb2e2618058c7d7c279af1632e1a6ccabcc9ec9a45a .github/workflows/tests.yml
0a2f69d4cec89d440f5d5aa1ec68a7c9a741382d313f80dcddf96d13f70b3e68 .gitignore
53bab1717a2e87602a45837a13998ac3f251cda354e1f547a23f8631bd5f2456 AGENTS.md
972c437a560f4fa096a663498b39688f98e68078bfd14c54342cf98ee5cc046e CHANGELOG.md
e97e47c7585e81d9ec5fd32c0ca0b64699fd4610cd03e9d6575a91c30a10ca4e compatibility.py
e0d0093229dd4719e97e1ee2c0cf935f6692f323f97af49a6361fd9ffac8a3d2 AGENTS.md
2a1340ac613def60f0a2c1c7e382c87486b49b14ebc3c6ef34ae14af633295d2 CHANGELOG.md
c1ed3a0342730450958fb62fd21854a876991f3a4aefb24e5383b0c73cd2312d compatibility.py
4d62508f900af9f93ec320afb900c27cc9a300d1e0c0a94714258498c5ede5fc conditioning.py
64967f4987e3ad9316f3a47f0dcf582eeff39ee0c3485f4184d3532d495534ae constants.py
cf255b8a635471229aebadc926acfdcacb65963adbcb9e0f9505d04eada2c6b5 continuation.py
bf0556b076dbaca67c3405a7d86c333ca7fdf3d4381529b0a9edc906519943e9 guide_timeline.py
f9375629fa1a2c4d3538442f0c3192d7ba2f46fe9544fb2e21f0c144b53d608c docs/AB_TEST_LOG_JA.md
c93a3e52e4deabe5ef0db7f34a7605856a543089574ba17227e697e9a2c0139a docs/ARCHITECTURE.md
b30fe4640359bebfcdeeb94dbeec94cb346c8e3646509e1dcdb87d7021ba04ff docs/N2B_BRANCH_PROVENANCE_CONTRACT_V1.md
7660570840229b6fcbe62f0fbb52966d0099d64d7e6f01a739fbf9899293c8e4 docs/FUTURE_ROADMAP.md
9a634b4ff6c9ca98285f6b250402a3d0e67d29f031e134d9bfcab54c119ed337 docs/images/comfyui-manager-h3-continuum.png
6c72d9a9e35648355c4dd4c8f060a6b7667e322f4b6c86690df9d6769ba182b7 docs/images/h3-continuum-advanced.png
@@ -65,32 +67,36 @@ a8460ca5092511f6d22da3363331ba8bff4feab01c569e539811049ea1add051 examples/workf
ea8c245d36909672710bc9f535f37195e48d7151b0cb2217bcaaca5fcc6d02c0 examples/workflows/MiniMax_H3_Continuum_V35.json
9f1a0766b97ead788989fb6eb69a6b36ad236d7a924eea4a88e4a1696e2db6d8 examples/workflows/MiniMax_H3_Continuum_V351_LBH_Conditioning_Bridge.json
1c7f1810f0cdd0bdcee09fe9eb8cb052993dd7343753dc0ec0157e00fe702da3 examples/workflows/MiniMax_H3_Continuum_V36.json
e8f41dee2240f1fcc6e8fd12448856513483ff3ae0427b2c554bb351f9ae8047 graph_contract.py
3d14acac341c63207995e2bd45cd407fdb3e2308273b1c90605adfe6f2e0bd8f hardening.py
6abdbc29472c7f9d447085b189fc47b69e110b94ef83192f9689d04000408843 INSTALL_JA.txt
9d88ffd2d8f7b4a037bfce0aee59afbe0ab77a27c1496aff34e9d08553772804 examples/workflows/MiniMax_H3_Continuum_V37.json
e490c87e4995930f95c8fffc4c678111d7897e74003e1962b9b4a247ba43f4ac examples/workflows/MiniMax_H3_Continuum_V38.json
d2d22c441f2a86a49277e3ff30f05678cf3383ca74207efeb81e74bb8b4a72ce examples/workflows/MiniMax_H3_Continuum_Easy_V38.json
8c109973e5b49cf52b32e0ebb2b5ae6a4e349191e66c2696ff43ce76fefeb07c graph_contract.py
1473c384082700f422f2cf9141e0d012d87d2b43ac8a8a433edc7172e6ca7bf6 hardening.py
7c8b1226592dcd9d0ec6cc1579956e380fedc9b2672386c29db82169a6cf5f10 INSTALL_JA.txt
23bddc5a41d2e997f4fbf789c7128e32f4f197f1405b2aef1c76794f57482446 install_windows.bat
d74073e7ee292ebeba913af4288284f9f197cd91fceed6c62bf6c66b784c7cec install_windows.ps1
fcf80acf6479ece00066eeb59f75d5246cb7b17b75ba84938b73ae17a5083903 install_windows.ps1
6aa3f5780baa7bb0c0672b5f01a2f77e5f209da93f6373468cb274ea2f643d4b layout_adapter.py
c44abbd789091bbead01250dbd5453e60539d2665c69f162335fdbd2936019c2 LICENSE
d3e213005670e94dee33a240349a4d245cf9a3b6602099f11ed30cf5a32e2c21 media.py
3b3ed9c27bb29b9d77f146c4aada1ce20adb9ffc551465cdcad699971869c256 metadata.ini
b08f4deb90628aa2cd6e219f59c3109fdda8c1e9a6571ba784a560d55b2b7f9d model_patch.py
9332e48af66e5a179e142c377abd830a2b9f0e5baef0640d8ac907be33120cf2 nodes.py
d2b235868cf6c21971f9ec7620c487382f3fb83c7cf7cbf87af0ed1cc0cdbd38 PACKAGE_INFO_JA.txt
ddc9ec3c96cf8f00dc082e0c4576cbf4952f79d8a6990c2e69901cc45fa33c98 PACKAGE_VALIDATION.txt
8b360a1c47a8ee5a95656ffbc83bfc16de69678ecec2c1d8cace46b5ea4e911e metadata.ini
2d611f7201889851eac6459f8aa2b37baf342b345241979ca6042b61b252dff9 model_patch.py
a4ce23167b83e8d72b86a802dfde4f4045828433c7c13aab799bd64831dc04a4 nodes.py
57dcb61cc3e83b2ca97616919ac6ee17d4c62caf845c38161573f56dad12f8fe PACKAGE_INFO_JA.txt
000a56a942b13d11973994ab32cd2a1abc424a3fe1d95a323240077bd8092bdf PACKAGE_VALIDATION.txt
b470819f16fc179654dc1600721a63f0a5a14e777f4c004d574b499da6886ba5 public_api.py
1840e43c3cdcea05c098a579e2dc9df4562f0aa0f00e12c42dd5bc5bb1efb8af pyproject.toml
96f98d727b72d6aefd431061572e187c303365a3e5b4d20cbb2bcf030aa30112 pyproject.toml
94fdc2d545b2d4077a4d70229fd22ba3ccac21d49d1097d2873f76d04e9a3c7a pytest.ini
a2df354b9fccd7cf26c20dc917179ca8859b42a5cdb6891c05f73f6b5f8f1658 README_JA.md
92114c808f65f24782b13fd00610883c0452cf32fb73bce0186f8beab84f94fc README.md
5d89c366b4f076fa73a2695557e0af749bf95df1dad0d55dbb2fe5b1c2519ad7 reference_audio.py
a0266ab4434b8e9844219d2b6dd8a168d198dd8f142775be01a39b81dc196b91 reference_video.py
564f5f2bf29665059845a98b9ca3e9a1309566aab73bcaa96f95fab8251ab06c reference.py
88aa955161d04d14ebd8d90d6cb6c6206097160a671eb4d1bfe9b3e76ebc6c13 README_JA.md
bd71498ddb59edc250ca623ee7cc6fb0c3a728025c879cda81390d435e5c6eac README.md
44127adcfa30ee84bff9cd4b2d0c695355209550e76982d374122008728aa5bc reference_audio.py
5cb9bfd6810d3a93a637451980a4cc5c1436e5b84cfd1c7a111cd192e876351b reference_video.py
131bdfbb7a7173c9e7826859c0e648bfb69bd18bf20fa5528c0e18a63f888b26 reference.py
467edb2c188d024c2392aafe7423b3f835e16b10f570da76e2f7dda8a962c1c5 requirements.txt
f28afe2c0033f1aa0ef3053e9005badd51242d4431a6d191af375ab2a59f50b3 run_storage.py
a65d657466491aba8b2d1004e87071cee2819869813e646789df736a3ccf479e run_storage.py
6056de6c0a5322a8a51ba5a114538dca2ef67788cd1afba10fedd483b95f6afa state_io.py
3a359a0467725cc292ccb4c86cf0c3d30bb6a114d01f5345792b09ea3d45441d state.py
43ec4023dc06c941e5d7a04db4b8a89fb58d744ceb986f6eb9bf534d4fdcb87b temporal.py
db08ce77cc5c5835f2403d4d589394090fa5d25ff3b1840312b2808e1bc203b7 tests/fixtures/v38_a3c_selective_refine_saved_workflow.json
3eeed61b7ee519631825e5f89e9a441644c66e552fce4207927cb8536867c8b1 tests/conftest.py
041289556cc621ea1857cbb8931ae41d817f69e084b2e8a7622e184a3197b61b tests/test_compatibility.py
875ac33b5458ec5e8d845850ed495707c394436aaadb668a44f36f6a1b73764d tests/test_conditioning_modes.py
@@ -99,7 +105,7 @@ c058f189d8e58fd48a80c20c0a857969737a8b13960eee60e5c17db2b9288bc1 tests/test_lay
2dddf05bbb91b7aa803959a7a8ed78489792ea9c35c5634bfb7d5b1a6c81880f tests/test_model_patch.py
45e8839cd82fd955df344b3bc6efa20092b8870ea378b0c898b073665d3e47d7 tests/test_nodes_logic.py
b635d404ca67df69894c4fcf80d8782cc5699e946bfb55ae4c44fff9d930b018 tests/test_p20_file_backed_tensor_poc.py
69a6155d3719d75bc9783d55c327100ca3097b2a8d71e6b82c1e5daf5191a568 tests/test_p21_memory_attribution.py
0f18b8810b2899f87ce6d6bfeee46fcd90ba787fa09665bddd8fc128f1952c65 tests/test_p21_memory_attribution.py
2b097971258dd10f0df33e0f8cb5843ee6cd3e9ef9e7abb80b890c66baf22908 tests/test_p22_file_backed_buffer.py
d09d2bae2fac04a058ebce22fa0e761d90b267107923ab8cd01a99cc547624e6 tests/test_p23_assembly_v35.py
d2a02c120e01d360ddca17a92d5bc53b12c9f0734d06440b3fc2fad2e754e549 tests/test_p23_video_seam_patches.py
@@ -107,30 +113,30 @@ d2a02c120e01d360ddca17a92d5bc53b12c9f0734d06440b3fc2fad2e754e549 tests/test_p23
403a0ff300330ac1f97642bf0681e80b83eec18e8911c03952ddf203ce794e5a tests/test_p46a_reference_video_memory.py
1ae0369943ba2fb13f21ad0cf56ee58621ba09bf20174379595e157a1775c7fd tests/test_public_api.py
892d3e3e022a527652dd995508c8bbb650c370caf9ee66fa3eb1f7fd288bba38 tests/test_public_workflow_integrity.py
7681e942fea293e863ae28aee11ba9e69af2e0b7e1f99ac2c9e82cbe77c10ff1 tests/test_release_metadata.py
acf50045b69f59f42aa351c9d389e1f259ffa5714643487e899165158ca99893 tests/test_release_metadata.py
d4c53d2c260b635d70fa211029d608f63776e0a56c20253475fa47c58363f8a7 tests/test_state_io.py
5af6a16a2337e3483bb0f9197fe04756decd309e4737520c5557b527d68d51bb tests/test_state.py
a1f60f01e9d86c1f2a010752612e373e85112c7054ffc31185b9b459eb2b34a5 tests/test_temporal.py
970e8206c033c60d241732fc86f37018ffad2d66483ba235dd0eb39936ff718e tests/test_timeline_video.py
f175e9ebf39d6fcaac578b640422676d7f7a54bfdf0f77ec44a3da6aafefd7cd tests/test_timeline_video.py
dc8b9cf0e77b4983ee4eecc60f4acde7d0e063f3b7569402feca8a56165107fd tests/test_v2_decoder.py
3cc94a6a7957ef285f58d373fbab001d926d2b43a754d60bb00bfce98675f32d tests/test_v2_prompts.py
5dfdd4b108ba7444c0f5f371c3b1e244b5735d23136127b9818fd60738c78b68 tests/test_v2_registration.py
424a4b34fb391ff3729b38a9b202e36f5bc8b9689a2a9bbf9589254c6261d9c6 tests/test_v2_registration.py
86314c190d4335586c18191dc095926909c67fe839eb29e65324acd16c44f24e tests/test_v2_seam.py
74e623120a963cb96b68651b44f47a836ea8449d30ce89d749c71ffad4766d4e tests/test_v2_seeds_motion.py
b42bcc0983147462d96c6b71cc4a38e846995dafa6eebefc3ae0d9bb36caf359 tests/test_v2_sequence_orchestration.py
0b5b20a8318862d167f135720e0489b8d4f93406d67c6646e052e35b03dcb876 tests/test_v2_session.py
58438c3ed814adf40cefde098a37cae00ddcb703b7e5548bbbb295e54bed5a6d tests/test_v2_widget_migration.py
1db3b655866b70b297dee9c01e3d79d10b4f7efbc481a0edf5ac8bac12a56926 tests/test_v217_stable_facade.py
78bc478a5e4edda902c80849c911782a99e75c06dfb04127391b6cc5b27b28e1 tests/test_v3_hardening.py
eb5b27f8f0d79529c56ef344a5601703642c3cba5388c9768116223e2ed58a36 tests/test_v3_video_seam.py
144433f5b5bca50e1933778ff1ba4a852b3e2c4a0108f8b50ef0be3bc9b14e5d tests/test_v31_run_storage.py
fc57dd687a3648f763afbd8badc139451fe64d644db06f81a7a38926cb6b9df7 tests/test_v217_stable_facade.py
473abac48a57aa5f297c6e141a94de17ddcb9424a8744bae1c46e6a6a734a0ab tests/test_v3_hardening.py
35b26c8cade7acb2eec35375d7dfa9a4a112f67a5cec6a842d61c69039de0d84 tests/test_v3_video_seam.py
316a345f88dc424e0d5e017ca64bb0568d0b4e4ddebd076bdebf717028ddb4e4 tests/test_v31_run_storage.py
3af78ab85c8e19dee8d0a98bfd11a2c0e88c30d87256da1f9699c49a19a684e9 tests/test_v32_reference.py
72719bcd6686d84f518d80751e3754b875d34c2aa72e2183dfa05ac9158a9eb0 tests/test_v34_driving_audio.py
47c07c57934d4194ad56da2559b97631fc98b061ba1eb1b8390eab99d13648a6 tests/test_v35_compact_ui_frontend.py
cf1ca6342a89e4cb02b398b32edbe91b6c1353535383e9f51d459466305a0114 tests/test_v35_conditioning_bridge.py
f41ebbb64a9cab7dd74e97a149b25d8a15681b3a38003ec00b5baf4b6003b905 tests/test_v35_context_sampler.py
a21c0722907ebb08fe24efbcf8b51494de546cde748a24d536e72270a9b784d1 tests/test_v35_hires_fix.py
9ceac8c3c6e4e57ec8b53b48f3b547c204df36a3f6281328aa9ab5ebc2e6a0b6 tests/test_v35_latent_resize.py
43aef01fc587c9f9e87baf312eb4d588975aaaacab161a36bfcb638a4c11e31c tests/test_v34_driving_audio.py
4279354d9ed046588d3a685f5150f1cd1891575ddbdcdba870062d8000c64f30 tests/test_v35_compact_ui_frontend.py
75dbdd0d9694d82fab7da23f5cc03bc118c024abc865f6c282799aa8c57427fc tests/test_v35_conditioning_bridge.py
7dabf482f1fdcb9d5d3deadc1b797f1be576bdf47e0c1008bd7d5be7819f9b30 tests/test_v35_context_sampler.py
7380c2ea1eeb4fb212ef51ffdf6d14a33132d3ae6d4c7ed5015f28bba6b7e75b tests/test_v35_hires_fix.py
09a6f88fe4f63b12b11d28a82df1ef8eaf01c756f7bb633a516061b93ae4f73b tests/test_v35_latent_resize.py
59a07f2172014dfdc0a447775324d7cd049f20b823276dfaf9b7b3f79628f5a8 tests/test_v35_pixel_vae_resize.py
05ba609fb948665f050d58fb087569a158c040d08bebad1d728b911673b95462 tests/test_v35_refine_context.py
8ae5173eaec35adf9efcde2c464c95651c848248bdbdd6396ed2e3c3c1ac7965 tests/test_v35_refine_sampling.py
@@ -140,49 +146,111 @@ a11956a22f373d96f13b395971f39187d6bb12cdc153ce794b4729d258ce9725 tests/test_v35
5003c5f5ce1a4b4c77deb47011431e4a15fe0cecaeb6d689e0d0878567c42f5a tests/test_v351_reference_audio.py
5f70cf8bd5248120ffcbe75ff3a54e23030fa6eb318ab0de6e0b08ee20e25a87 tests/test_v36_chunk_duration.py
bf69d1ac3fc30f963b6fed6cbd661f273593904b03275467427a954fbdc0a03f tests/test_v36_masked_video_prefix.py
46531e6d505cc383b559994c2c74a1619d49715dc6fca838b1df29d575d9dea2 tests/test_v36_public_sampler.py
cb9ddd365ccf60693cef254685599bb002acda9986671c2ffa6a8083dae35008 tests/test_v36_public_sampler.py
324c213aba761e8989a78eadc0cfdcc54d098f50ed1fe84a5ea7aec26f0dc595 tests/test_v37_guide_production.py
14ce0c7f78bcba9948e9e9930c4de5a8c7e8c453fcb6172066d43f593f7175ea tests/test_v37_guide_timeline.py
28adaed7d5a9ce74b91cecc37a8bb173832ef41827bdfdfc2f7ae79d96a4dc59 tests/test_v37_public_workflow.py
70b2413ad779bdde05bb131ef19db881c48e02004287d99626467303e23f8af6 tests/test_v37_refine_schedule.py
61484ca0552e8341301a481a87e12e44279dbeed68d4b841f4301a4f87ce4a29 tests/test_easy_load_audio.py
4405c94cf190534fdabf5af3fd2ae9cc7cd1b2af6eb8b0d4ab73327cbcd455b9 tests/test_easy_load_image.py
8ba1b07a4d2cdb21aba16a6c05791ec3e35ec7f4f3651e6de5e961be464b7074 tests/test_easy_load_video.py
b7da41d7654aefaa06997720f7cbbaa7ddc3827b41ed365efd5992e399aa779c tests/test_v38_adaptive_continuity_observer.py
1a24a0cb040a4effba3fcd2974df093597c1686923f0a84f0cd267305a96f7a5 tests/test_v38_audio_only_refine.py
e813b5d21af2963a325862acd344b33caa124d0cd3940a940c58118cf27742e0 tests/test_v38_chunk_boundary_diagnostics.py
8cdd5e14487a59ef333cf675fe3da52eb319480e69c5a6262377533cf7d0b160 tests/test_v38_chunk_scoped_refine.py
c9577e9b2d430c9435a287bf679a920020192d51f780e02b47f286e2e4b6a615 tests/test_v38_easy_mode.py
f84c1b4f31c2f45a2eff1b192945f84f08b009dcd2e27b029cd3c9666e59393c tests/test_v38_easy_public_workflow.py
98eb59407741dd187dc22d94b4f433f341294d05cc38106fde15b580b1465001 tests/test_v38_memory_action_policy.py
338371e7aefc0f303bf62899e5c7f15e1bead2ad3579eee7144f4681487f4014 tests/test_v38_public_workflow.py
12337a491fa67b38b32aaeb16e0b209393960dbc46db2a8bf968b8c3902855ef tests/test_v38_packed_row_planner.py
967ab1262a90b5ba5b19ad8fb8c9d74aef4a35b02b4a176144b6edc537547939 tests/test_v38_ref_encode_cache.py
8b376f45261d045b584f02b4d14cd70c2d6269b9c814d4e62b5c612f6e30e36f tests/test_v38_refine_target.py
0b2b1280a1217816984a99c0f948a52a8e2e6fdf924b5c4f2f578719b12b01ed tests/test_v38_video_audio_refine.py
072c9b30a5edefacb4cd682808b9b04dd088f5b7bafce2c090def8dab0efc037 tests/test_v38_reliability.py
cff84ae0562ba5fc48f3608ecaa433e74c0af9b689d7dca94ec8c3c4e9dc232f tests/test_v38_resolution_preset.py
2ac395009e49f9554af8d1a251d93fc5d5e7070bf80f5a0b7b3f7e00cde15077 tests/test_v38_review_cache.py
ee4dd8f6eb8114706b2625b4471b041a0ea66198f9f825c63e913c896ed87530 tests/test_v38_branch_provenance.py
72a0e3cb334049b66dd36f52c826931067c242fa63557933fd667138b38d6e8d tests/test_v38_review_control.py
83301839f08d275f5648d7782b6d96795e14b1ce79d722e83e57190fe52fb4aa tests/test_v38_review_execution_cap.py
836b8264065886b929b098d26c3137e8e5f6fc1dbcfb91d53d0511be584b121e tests/test_v38_review_run_storage.py
d4b06d4732920a662da722717b805868d2a737f83a111bc62086decbf7408382 tests/test_v38_review_ui.py
75697036f361a9b8ea74f69b15e408670f686c8c0e8a6c1d48fe059cc837d12a tests/test_v38_selective_second_pass_node.py
8026a241301dfc4de518649305458a538ef17a0b1567b113877a2af377738528 tests/test_v38_temporal_window_refine.py
0dbe8a5f71c92f3523942343b40787104c8b96781461ba3ba82934a6bdbe5834 THIRD_PARTY_NOTICES.md
f218e1a93c42467c6057c5c1d04d57cc82f6331b97ec9257e4e2dfb9c831876a timeline_video.py
e5a84569953ee63b9625f4f2e3195ec368204fddcfc746564cfbd0e8449bb8e9 tools/p20_file_backed_tensor_poc.py
71e5270fe0b0768c761a06eccdf61a600413802c17b6acf689647d09f1a93d67 tools/verify_runtime.py
cf9eaee6730fb15aa757b13d9a3c5775f398d845e4c7cb4be66f88f620f6a7e8 tools/v38_easy_driving_audio_gpu_gate_runner.py
cc247c01a01efaf594c24c7ce36ca3357c092fc28dd742c7577093ee9d5efdef tools/v38_resolution_gpu_gate_runner.py
ad8609a45ba818fb74245b30cb0a3a221d6b345c20671092cafd714d8b07aaea tools/v38_review_phase_f_gpu_gate_runner.py
60e9bf2c7c40ef9dd71f08ec2ec8c25f7ae9b08e74c3b7be5964e1138848ae82 tools/v38_review_phase_f_recovery_runner.py
556bce17d14303d1e8a36a85dc13da24c46eedd86f3eacdb102289574faf0626 tools/verify_runtime.py
ffd61f3f31c9b6430e1169007ee906c8f5000eba63ee44e2976ad4f5f1112671 v2/__init__.py
2003902c87bba09cfa143f5a9e4248f3a78c0fb544449a75fd40ba2cacb35655 v2/context_diagnostics.py
cde27db19b677e318cc4dfb4235be7a11429c19945f4083052a91fe117e74c82 v2/decoder.py
31012ec48a64c7467ad869c79982b7f8502c1785c33f51ee1b5727ce8b4243fb v2/diagnostics.py
8fe649acb25c36361c042807b828c545d8febf760f9ba0187fbec3e69698064e v2/h3_builder.py
2ebff4502381f675d06bba4b127b81bc3201e7579ddcd46fa5051cbdf3facd55 v2/h3_builder.py
aea01a48a8c03a25ed97ea05e5b137f89e388832d1be7d38f2da2be3d1b9830b v2/motion.py
19249ea6b00be3a792f957aff85e2cc11422f8301f7391af1f7c269f33605314 v2/nodes.py
aefa29b9d51a05f9a972d75404fd786300202251887e67f55530e97ccd9519f5 v2/nodes.py
dc2b901789e4b024dbcbc4024c63eb8cbc564d77003ce8c35c0584851ba6dfbd v2/prompts.py
4080f1875b958b316e8e76852c4be5527a6de5c71d604e7642d3098478eb4a36 v2/sampling.py
2fd811794c4cc0f2ce050250b80484876454926b9f20fce6af3a97d728e5acdf v2/seam_guard.py
be0d8585fa57e0ccd6d02577bbc7299629e5bfe20e186747f571fccc98b67d7e v2/seam_types.py
12cfcc0c71ca087fe39a5ce2922959a62b2bb311bfe664f05c4480affce03708 v2/seeds.py
0003f5c609c05dd8688d8eed640cf3fcaf95dbd40c3804fae1c957afbad3b132 v2/sequence.py
3a98f8a21756f3813f52197946e761227507b14c40703c9fb1bb108c1e4ddbe7 v2/sequence.py
13213e7709fd02bb810af3c18e4cd7d010f8cdfb121a4b99866a9f2333331089 v2/session_io.py
3ea23dbce6fcd217b6e81235855479b9b16fed7a21693cf156f9014555c4fe13 v2/session.py
78c830cdf49034c6e3b2cd3da5914d5cfc5638eb63ec6dbd1bab13c50d6d4caf v3/__init__.py
ea2922567df90436dd6fa21696833a49dd0cbfeee142a5fedc3a7c303824d473 v3/adaptive_continuity.py
b3dc61503d35d9ef0a0dc7fed1c9b2fdc00fcb2072d4e39f64ae0826f9ec7dca v3/assembly_v35.py
7815230e0a9540bc2edeaf818e940b7a1fdd817fd217ba8a4f9cb21aaf6a308e v3/assembly.py
3f62fdb35e804f42d7cbf0828b4e87e69a2b99246c3f7467fe4fa698f1d803c9 v3/conditioning_bridge_nodes.py
7ef3960e741a23ce3e34de56c8987104798e01475a57967da597d3bad6eab269 v3/driving_nodes.py
92b92c51b87182d420ce0468f57797fbb6fe4123d04080b73d6d89581ff96c31 v3/driving_nodes.py
2f395da6a41981713f99ba40b73d14f2274b8ca34a73cf2b275a444993765b99 v3/easy_audio_nodes.py
64b3e54b42e5156642f9957ccc374fd190d9fc7145637984e702534fb1bf80b4 v3/easy_image_nodes.py
ac859cb1a6e23b8ceae300d818c24fe1346b649a0d663017a9b3ac64aa96fca3 v3/easy_nodes.py
bf6bae0c9e14883728860470af86e14395dba40a7377cd874d4dc4548ae53c65 v3/easy_video_nodes.py
6cc7ed74666084c55beb9075304e92a9defafd81b9c6678239ca3859a08cddd7 v3/file_backed_buffer.py
cb53e1b104415032ec79b7e7aa1c99848e63da3eedaa251eeba102970e4172b5 v3/hires_fix_nodes.py
0858487e2b8c0060a856273ffc65d23165b2f253d183f506e27e419aea0da561 v3/latent_resize_nodes.py
5b8a54e67a608e757a505abc712effb33312636e3bb235835a485a506e80eeee v3/masked_continuation.py
91a868d2e392b018b01d0396209849c146b0d560ceb109fcdd87dea7f3d786aa v3/memory_action_policy.py
85477badd85281cfb77582fdd5b34228a9f6b68376f1b7743af2ca7d4b55aa36 v3/memory_attribution.py
ef00dc62585a3581cc6641cb832abfc7dd01e02a45ebe8c438a463905052097d v3/nodes.py
b528e34e24407896e3728d693a40393b46ec7bce236d455721712dfe2fe75adb v3/nodes.py
b7c4a35a5e73f528492bc6946b97b687c412f1d3f5f976c19d45c6dc20288c9a v3/pixel_vae_resize.py
34ea38c03b6322288d88fc8595e3655a7a7afddb51709142a954eb7349f71ac2 v3/plan.py
a3411c7a295308d21623551cf4aeca5bef511eb5f063f31ac84032e3bdf4e16d v3/packed_row_planner.py
ec71e3965f445756d54d005c0e27bea520e26dbac44e1ee3d3867bfe2da100b0 v3/ref_encode_cache.py
9076c47aa5145c81f34793d6c90410656065248f37d9990a92a6a4061b358811 v3/refine_context.py
43f33f989eb70ca87b916fc33267732a2be3dd4581fc72af17c53f840b53ca49 v3/refine_schedule.py
519586b1b3f48c73d329f7a2aaa8a1bfc6fe31ac2ecb64f2b1fdf9c19026001a v3/refine_sampling.py
30cd7cd29cb804f9d5d85af49b1e4b9ebfa8bc7b485043ed745491dc1d99294b v3/second_pass_nodes.py
5483328d9c76802f7883e74fa766585ea13a62606f41ea0691f33c7ec846d485 v3/second_pass.py
ac373d9783d3a7bb968e8117843d246d6a090b66a819015348bff84e7747442c v3/refine_target.py
45ae91f13e8f71405d2f46045c8acc6eabbc9500c194cf5d0ba541bb085cd135 v3/refine_window.py
afc149dc347b4c1502ddf32ea4229e633799cd34d2b2c6f98bf8a47910a9ef77 v3/refine_scope.py
ae909b43ad17934c85881d3b0bea81e7b45c215eeb4d1f9f6a9ea72faf633ddf v3/reliability_v38.py
520a4ae849f83450855ce0023c582db5f91d29d8694a99aa8cf491351c837cff v3/resolution.py
c21602eb983d497f0eb559197f4f1408b9b5ebb8dcd3aab65e746641f77bcfd4 v3/review_control.py
452022107cea233aa84d5366ec4943ac5aadbd5fcf786113f1d542a641eac8f7 v3/second_pass_nodes.py
66501234756c2b558ce84f887bd540e7f843ed574c8a8b2522950bd1985d7acc v3/second_pass.py
6e71e944313339f14e14e11cec682593159ca5542aa5d38095371da781d60224 v3/targeted_refine_sampling.py
5a044bdd70c546e4446e0c26af92aae88049ffa2e0e2d01b52033a83a3152d0e v3/targeted_second_pass.py
4178dcfa442abdb06ce276e05bd7bcbaa6da28469ba5e57d3da3c663de4e4a9d v3/video_seam_v35.py
2f07ace1462644f0bee553827b3571535de4d0c2d9ef847bd9e0ca73a4eed5cb v3/video_seam.py
b5a8069934ed305688ebc07acda05a6d4d391365892cd6c9d6c9db651520f4cd version.py
cdcf166531835a5256fd9fcbb02d02efacfb669253cb3ea280d868cefd7e5874 web/project_id.js
d1957fa668a0332e483330bc79fc53095712420e401035a4f80cf6b532677d51 version.py
c2883272b05a9a9146b5c6cf614ddae8a3e6893cd910902023aae61360195289 web/easy_bypass_toggle.js
092088096307d33ac016b82b4774ca38845a2ff2f63b97ac6da8c5aca4fea413 web/easy_load_audio.js
9db0aa94f634578a962d5db49e5c70356040a59df968e3a2e531b327a623081f web/easy_load_image.js
873efcbd15c2d9fa10c9d5fc51a796ad3a18c0c6acceecf499c4b956aa845c6c web/easy_load_video.js
0c68d13a1f8beb7431a32b471f8b0612c42fcc4bf72dd97611a025d158008662 web/easy_v38.js
7b318be7e0a6ffa7a0b924f149ee90c10e4ebfb731da2bc40297bad0ecf63269 web/project_id.js
be0b8d39e5343680ebea815c3a4fb6ce7a32e065f30e43e013040a40f702cef3 .comfyignore
1d2838cc47694609289ea15132872ad48e1b6c8274da4b7bf188dd3ebf066121 docs/V38_RELEASE_AND_MIGRATION.md
7a75ba760008ab0e58b164ebc628b5f1db7a8704e0bde5406d62ea0de2244f7b tests/test_v38_public_surface_cleanup.py
0cf8d49bcb71b30437dc893f6218dc4cfb1cd244b647e4fbc2861dea2271a33a web/reference_audio_ui.js
4f602b2ceae803fd08a4960a25082f6a79149edcf708161e6c288efe12a7a5dd REGISTRY_MANIFEST.sha256
717577efdec5e61600504b77bc2a099ef022c4fe2333e936c3310c7182d8f2a0 docs/V38_OPEN_INTEGRATION_CONTRACT.md
623d528a02b6712cba28c374ba3ad979bc84e2ac5318640692589a04ba6ab15f tests/test_v38_open_integration_contract.py
0bc369ee428b8a5bc8e370a81fbab427262a1fdb7805a78c442c91698d65efba tools/__init__.py
5960c6feb10df5b79d51711d46de55f2f850be69e4943b6c5d12df38b0cedd26 tests/test_v38_multi_reference_audio.py
bb5a1530c890d357dc48ea74039340d746e876e8f85e06d4d9a19369f8ff5961 tests/test_v38_hover_help.py
3d681ded5d4c50cc20c2382e29fdc98d8a48e76d552c41ad5a195d941e66e612 .gitattributes
83d28cc0cd549066962dc21ceae05d2b189fe22391b556887eab2cc1800e1e80 examples/workflows/MiniMax_H3_Continuum_V38.zip
+16 -1
View File
@@ -1,7 +1,22 @@
ComfyUI-H3-Continuum V3.7.0
ComfyUI-H3-Continuum V3.8.0
MiniMax H3の5秒ChunkをAV latent contextで継続し、長尺映像として組み立てるComfyUIカスタムノードです。
V3.8.0:
- 公開面はSampler V3.8、Finalize、Load Image、Load Audio、Load Video、Second Pass、Reference Audios helperの7ノード
- Main Samplerへfrontend-onlyのBasic/Production表示propertyを追加。Python Schema、widget順・値、backend引数は不変
- MainのAspect選択をSize Source(First Image/Manual)へ整理。ManualではWidth/Heightを表示し、旧Aspect値は同じcanvasへ移行
- Draft 0.30 MP、Balanced 0.60 MP、Native 768、Custom MPのResolution Resolverを維持
- Review Each Chunk、Continue、Regenerate Current、Finish RemainingをRun Storageへ統合
- FL2VA Terminal Merge pairを1つのatomic review unitとして維持
- Driving AudioをReview、Smart Regenerate、Finish Remaining、restart persistenceと併用可能
- Image/Audio/Video Loaderはnative Bypass中もEnable行を明瞭に表示し、その場でONへ復帰可能
- 公開WorkflowはMiniMax_H3_Continuum_V38.jsonと同じJSONを含む同名ZIP。Spectrum初期設定のgraphを変更せず配布。Spectrum、rgthree、KJNodes、ComfyUI-Easy-Useが必要
- 16GB GPU GateはPASS。ただしVRAM headroomは小さく、Strict Minimal 14.96 GiB、複雑なGateは約15.5~15.6 GiB
- Review途中のpartial sequenceではSecond Pass/refine_contextは正式対応外。Review完了後にSecond Passを実行
- V3.7以前のNode IDはV3.8で非export。旧保存Workflowは対応するhistorical Release/tagを使用
- Registry配布からtests、tools、diagnostics、Labs資産、旧Workflowを除外し、内部継承moduleは維持
V3.7.0:
- H3 Continuum Sampler V3.7と、1枚のStill Image Guide用optional入力を追加
- Conditioning AdapterでFirst/Last、Continuation context、Still Guide元画像をSecond Passのtarget解像度へ再構築
+36 -47
View File
@@ -1,53 +1,42 @@
ComfyUI-H3-Continuum V3.7.0 package validation
ComfyUI-H3-Continuum V3.8 — package validation record
Status: V3.7.0 release candidate. Conditioning Adapter and the internal RefineSchedule v1 are correctness-accepted without changing V3.6 Production defaults or the existing SIGMAS socket. Still Image Guide positioning, source ownership, Terminal Merge, Run Storage identity, and target-resolution reconditioning are correctness-accepted, but hard-anchor quality remains Experimental / Production HOLD. All V3.6/V3.5.3/V3.4 public node IDs and saved-workflow contracts remain available.
Status: source-tree release-hygiene candidate. Release / Registry readiness remains HOLD until the separate final package-staging gate completes. This record is not a release artifact and does not authorize commit, push, tag, release, or Registry publication.
Required automated checks:
- python -m compileall -q .
- python -m pytest -q -p no:cacheprovider
- python tools/verify_runtime.py --comfy-root <runtime-path>
Public surface: exactly seven nodes
- H3 Continuum Sampler V3.8
- H3 Continuum Reference Audios
- H3 Continuum Finalize
- H3 Continuum Load Image
- H3 Continuum Load Audio
- H3 Continuum Load Video
- H3 Continuum Second Pass
Validated runtime paths include:
- H3 Continuum Sampler V3.7 required-input parity with V3.6 and one optional Still Image Guide input
- Conditioning Adapter reconstruction of First/Last, continuation context, and owned Still Guide sources at target geometry
- RefineSchedule v1 External / Full / Tail / Partial contracts with exact source schedule slicing
- Internal Tail 6 at 704x704: six evaluations, decoded Video SSIM 0.982936 versus the external Tail 6 baseline, and bit-exact decoded Audio PCM
- 1152x1152 Still Guide source reconditioning correctness with first-pass Audio passthrough preserved
- Still Guide single-IMAGE validation and explicit source-role priority at First/Last endpoint collisions
- V3.7 compact frontend parity for project identity, hidden widgets, Run Storage controls, queue normalization, diagnostics, and permanent Reference Audio sockets
- V3.6.1 mixed Timeline/List Prompt diagnostics and fail-open normalization
- V3.6.1 non-Balanced Audio Continuity fallback routing before Run Storage identity creation
- V3.6.1 public-node Strong 39 / Audio Continuity fallback GPU Smoke on ComfyUI_W: 2x5 seconds, 576x576, 240 frames, 10.000-second video and audio
- H3 Continuum Sampler V3.6 Standard / Compatibility backend mapping without exposing internal transport identifiers
- Masked AV protected Video/Audio prefix bit-exact finalization
- Run Storage Save, Auto Resume, and Regenerate From with backend-scoped revisions and atomic Terminal Merge reuse
- Reference Image and Reference Audio retention in every Masked physical group
- 3x5 FL2VA Long Terminal Merge Masked GPU acceptance and PIG-3 subjective Audio PASS
- Shared 4.0-30.0 second chunk duration range; 5-15 seconds remains the recommended and validated range
- V3.5 refine-context contract and Advanced Second Pass Bridge
- Conditioning Bridge MODEL / CONDITIONING alignment per physical group without CONDITIONING-entry flattening
- Permanent Python-defined Reference Audio sockets, workflow save/reload widget alignment, and conditioning retention
- 1x5 T2VA, 3x5 T2VA, and 3x5 FL2VA Long Terminal Merge Second Pass GPU acceptance
- First-pass audio LATENT object passthrough through Second Pass
- H3 Continuum Assemble + Seam V3.5 RAM / Disk-backed output equivalence
- Auto backend selection with RAM and 9.49 GiB disk-backed real-runtime cases
- Exact Duration and Video Seam direct-write behavior
- Experimental 1x5 FL2VA Pixel/VAE Hi-Res Fix GPU acceptance at 576 to 1152
- Hybrid FL2VA + Reference 1x5 GPU acceptance through integrated 2x Hi-Res Fix and direct Advanced Second Pass
- Production sampler and Core VAE Decode assembly
- Reference Image 1-3
- Driving Audio absolute-time guide conditioning with original-source final output
- Persistent Video Guide Frames conditioning
- Video Guide Size: Efficient 0.4 MP / Balanced 0.6 MP / Match Output
- Run Storage save, checksum verification, and complete reuse
- Run Storage identity coverage for Driving Audio and Video Guide Frames
- Permissive prompt warning/fallback behavior
- Spectrum Interop API v1 with Actual Prefix 2 on continuation chunks
- Audio Seam Auto
- Video Seam Auto guarded transient and micro-flash correction
Protected contracts
- Sampling Contract v5
- Run Storage v3
- State, Session, Assembly Plan, Driving Audio, and Second Pass/O1
- Existing six public node IDs, sockets, and widget order
- AUDIO-R1 adds only the Reference Audios helper and the Sampler's optional bundle socket
Latest verified automated result: 633 passed.
Current verified source checks (2026-09-03)
- Full pytest: 1117 passed, 0 failed (one external pynvml deprecation warning)
- JavaScript syntax: 7/7
- Python compileall: PASS
- Development and Registry manifests: regenerated from their established file lists; verification requires missing, extra, and mismatch all equal to zero
- Historical V3.8 workflow check: one Registry workflow only; no Hi-Res Fix standard path. The final 2026-09-07 distribution uses the supplied Spectrum graph in JSON and ZIP forms instead of the former Core-only template.
- Public workflow graph: no orphan links or required-input validation errors
- Runtime verifier, isolated import, public export/display, and protected-contract checks are recorded by the release-hygiene result report
Still Image Guide, legacy Main Hi-Res Fix, and Auto 2 remain experimental. Still Image Guide hard-anchor transition quality is not Production-accepted. Main 3x5 2x is not accepted on the tested RTX 5060 Ti 16 GiB because the terminal 77T Second Pass group exceeded VRAM; longer Reference/Hybrid acceptance remains pending.
Registry package policy
- Include production runtime modules, the two runtime-required tools modules, and tools/verify_runtime.py for package verification.
- Exclude tests, runner/probe/diagnostic tools, internal state/worklog documents, development manifests, Labs assets, and historical workflows.
- Include `examples/workflows/MiniMax_H3_Continuum_V38.json` and `examples/workflows/MiniMax_H3_Continuum_V38.zip`: one identical, user-supplied graph in two formats, not two workflow variants. Spectrum, rgthree, KJNodes, and ComfyUI-Easy-Use are external requirements, not bundled dependencies.
- Preserve the supplied JSON and ZIP bytes, including prompt, media filenames, titles, and settings. Exclude unrelated backup ZIPs without deleting them.
- The Development `MANIFEST.sha256` is a source integrity record and is excluded from the Registry archive. `REGISTRY_MANIFEST.sha256` must cover the actual staged archive files with zero missing, extra, or mismatched paths.
Detailed evidence: docs/VALIDATION_RESULTS.md
Required final Release Track gate (not performed by this document)
1. Build an isolated stage by the current `.comfyignore` rules.
2. Import only from the stage; verify all seven public nodes and production helpers.
3. Run the official comfy-cli validate and pack commands.
4. Re-expand the archive and prove source/stage/archive SHA parity, no internal files, and no secrets or local-path leakage.
5. Keep Release / Registry readiness HOLD unless every gate passes.
+1119
View File
File diff suppressed because it is too large Load Diff
+544 -26
View File
@@ -1,11 +1,527 @@
# ComfyUI-H3-Continuum 3.7.0
# ComfyUI-H3-Continuum 3.8.0
![H3 Continuum V3.7 Tail 6 Second Pass refinement](docs/images/v37-tail6-second-pass.png)
H3 Continuum is a Production Sampler for generating, reviewing, partially regenerating, and resuming long-form MiniMax H3 video without restarting the entire work. V3.8 has two product layers: **Main / Production** and **Advanced**.
## Install or update first
Long-form MiniMax H3 video generation for ComfyUI with Continuum-aware Second Pass refinement, optional Hi-Res Fix, low-memory disk-backed assembly, restartable chunks, persistent references, and optional Spectrum interoperability.
For a new Git installation:
## V3.7 High-Resolution Refinement Foundation
```bash
cd ComfyUI/custom_nodes
git clone https://github.com/ukr8b3g-cmyk/ComfyUI-H3-Continuum.git
```
For an existing Git checkout:
```bash
cd ComfyUI/custom_nodes/ComfyUI-H3-Continuum
git pull --ff-only origin main
```
Restart ComfyUI after cloning or pulling. If ComfyUI Manager installed the node, use its **Update** action instead of mixing Manager updates with a second Git checkout.
Download the current V3.8 workflow: [JSON](examples/workflows/MiniMax_H3_Continuum_V38.json) or [ZIP containing the same JSON](examples/workflows/MiniMax_H3_Continuum_V38.zip). This is one Spectrum-default graph, also usable with [LightX2V Turbo](https://github.com/ModelTC/Minimax-H3-Turbo). Install its external Spectrum, rgthree, KJNodes, and ComfyUI-Easy-Use nodes before opening it; switching Spectrum off does not remove those node dependencies. See [Spectrum and Turbo setup](#turbo-lora-and-spectrum-in-supplied-workflows) below.
## You can ask an AI to read this manual
This README is intentionally detailed. You do not have to memorize it. Give its GitHub URL to a web-enabled AI and describe what you want to make, your GPU/VRAM, whether you have a First Image or audio, and whether you want to review every chunk. Ask it to answer with the **exact V3.8 labels** used below.
Example request:
```text
Read the current ComfyUI-H3-Continuum V3.8 README. I have a 16 GB GPU and want
to create a 30-second I2VA video, reviewing every chunk. Tell me exactly which
Continuum inputs and controls to use, what must stay fixed between Queue runs,
and what output length I should expect after each action. Do not use older V3.7 UI.
```
- [ChatGPT Free](https://help.openai.com/en/articles/9275245-chatgpt-free-tier-faq) currently includes web search and file uploads, subject to separate limits. If a repository URL is not read correctly, paste this README or upload it as a file.
- [Gemini on desktop](https://support.google.com/gemini/answer/16176929) has an explicit **Add file → More Uploads → Import code** path for one GitHub repository, up to 5,000 files and 100 MB. Pasting a GitHub URL into an ordinary prompt is not the same as importing the repository.
- [Grok Free](https://x.ai/pricing) currently includes limited real-time web search and connectors. A GitHub-specific full-repository importer is not guaranteed, so paste/upload this README if the URL alone is not enough.
Plans, limits, and web-access behavior can change. Do not send private workflows, local paths, tokens, or credentials to a public AI service. The README and the UI remain the source of truth; an AI summary can still be wrong.
## V3.8 supported surface
V3.8 exports exactly seven searchable nodes:
- **H3 Continuum Sampler V3.8** — the Main sampler
- **H3 Continuum Finalize** — decoded Video/Audio assembly with optional seam handling
- **H3 Continuum Load Image**
- **H3 Continuum Load Audio**
- **H3 Continuum Load Video**
- **H3 Continuum Second Pass** — the Advanced bridge for external latent processing or upscaling
- **H3 Continuum Reference Audios** — an ordered Reference Audio 1/2/3 bundle helper
The current frontend uses `Show Advanced Settings` / `Hide Advanced Settings` to change presentation without changing generation values. Saved drafts that still contain the former frontend-only `H3 Continuum View` property are migrated to the matching collapsed/expanded view and the legacy property is removed. If the frontend extension is unavailable, the complete Python-defined interface remains visible and executable.
The supported flow is:
```text
H3 Continuum Sampler V3.8
-> Core Video/Audio Decode
-> H3 Continuum Finalize
-> Create Video
-> Save Video
```
Core Decode, Save, and upscaling remain external. Hi-Res Fix is not part of the V3.8 standard workflow; use Second Pass as the bridge when an external latent processor or upscaler is needed. External processors may change only Video LATENT spatial geometry while preserving physical groups, B/C/T, finite values, first-pass Audio, and the original Assembly Plan. Finalize accepts public `IMAGE`/`AUDIO` outputs and does not require a specific decoder class. SageAttention, Sol-Attn, and Spectrum remain external MODEL wrappers. See the [V3.8 Open Integration Contract](docs/V38_OPEN_INTEGRATION_CONTRACT.md).
## Complete V3.8 UI reference
This section covers every user-facing control and socket on the seven public V3.8 nodes. Names such as `Power Lora Loader (rgthree)`, Spectrum, SageAttention, Core VAE Decode, and Core Save Video belong to ComfyUI or another extension. They may be used in a supplied workflow, but they are not Continuum controls.
### H3 Continuum Sampler V3.8: required graph inputs
| Input | What it does | Normal use |
|---|---|---|
| `model` | MiniMax H3 diffusion model, including any upstream MODEL wrappers or selected LoRA | Required |
| `clip` | MiniMax H3 text encoder | Required |
| `video_vae` | Encodes connected image conditioning; Continuum does not use it for final decoding | Required by the node; unused by pure T2VA |
| `sampler` | ComfyUI sampling algorithm | Required |
| `sigmas` | Noise schedule and effective step count | Required |
| `Sequence Prompt` | Complete text, list, timeline, or JSON sequence prompt | Required |
The Sampler returns six outputs: a list of `video_latents`, a list of `audio_latents`, one `assembly_plan`, a text `status`, the selected `driving_audio` when used, and a `refine_context` for the Advanced Second Pass. Raw latent lists normally go through Core Video/Audio Decode before Finalize.
### H3 Continuum Sampler V3.8: optional media inputs
| Input | Role | Important distinction |
|---|---|---|
| `first_frame` | First Image for I2VA or FL2VA | Can also supply the output aspect ratio when `Size Source = First Image` |
| `last_frame` | Optional final-image constraint for FL2VA | Can trigger a Long Terminal Merge; the final pair may become one atomic review unit |
| `reference_image_1`–`reference_image_3` | Ordered appearance, identity, subject, or scene references | They never become the implicit size source |
| `Video Guide Frames` | A video loader's IMAGE frame batch, applied as a persistent guide | It does not carry the source video's audio; frames are interpreted at 24 fps |
| `Driving Audio` + `Driving Audio VAE` | Original audio timeline used as native guide conditioning | The selected source audio becomes final audio; generated audio and Audio Seam are bypassed |
| `Reference Audio (Optional)` + `Reference Audio VAE (Optional)` | Legacy single conditioning-only audio reference | Generated audio remains final audio |
| `Audio References (Optional)` | Ordered bundle from `H3 Continuum Reference Audios` | Do not connect this together with the legacy single Reference Audio path |
| `Still Image Guide (Optional)` | Compatibility socket inherited from the V3.7 guide contract | Experimental; not part of the seven-node V3.8 standard workflow |
#### First Image, Last Image, and Reference Images
![First Image enabled and Last Image bypassed](docs/images/v38-manual/first-last-image-bypass.png)
- **First Image** establishes the opening image and is the normal visual starting point for I2VA/FL2VA. It is also the only media input that can drive `Size Source = First Image`.
- **Last Image** constrains the sequence ending. Leave it `OFF` for T2VA and ordinary I2VA. With a connected Last Image, extending or regenerating the sequence may rebuild the terminal pair.
- **Reference Images 1–3** guide identity or appearance throughout generation. Their prompt order follows their connected order; they do not replace First Image or Last Image.
![Three optional Reference Image loaders](docs/images/v38-manual/reference-images-three-bypass.png)
Every `H3 Continuum Load Image` has `Enable Image`. `ON` loads through ComfyUI Core. `OFF` uses native node bypass and makes that optional path behave as unconnected without deleting the node or cable. This is why one reusable workflow can expose First, Last, and three Reference Image slots without forcing every slot to be active.
| Public loader | Controls | Outputs |
|---|---|---|
| `H3 Continuum Load Image` | `Enable Image`, `image` file | `IMAGE`, `MASK` |
| `H3 Continuum Load Audio` | `Enable Audio`, `audio` file | `AUDIO` |
| `H3 Continuum Load Video` | `Enable Video`, `Video` file, `Force Rate` | `images`, `audio` |
#### Video, audio, and their bypass switches
![Continuum Video and Audio loaders with Enable controls](docs/images/v38-manual/input-video-audio-bypass.png)
- `H3 Continuum Load Video`: `Enable Video`, `Video`, and `Force Rate`. `Force Rate = 0` uses source FPS; a positive value drops/duplicates frames to that rate while preserving nominal duration and audio. Connect `images` to `Video Guide Frames` when visual video guidance is wanted. Connect `audio` to `Driving Audio` only when the source audio should guide and become the final output.
- `H3 Continuum Load Audio`: `Enable Audio` and the audio file. Use it for Driving Audio or Reference Audio according to the socket you connect.
- The node titled `Audio Switch` in the example image is ComfyUI Core's `If/Else Switch` (`ComfySwitchNode`); `Fast Groups Bypasser (rgthree)` belongs to the rgthree extension. Neither is a Continuum node or a requirement of Continuum. The Continuum loaders already provide their own native ON/OFF controls.
`Audio Continuity` is different from both audio inputs: it passes the previously generated audio context into the next generated chunk. It does not import a source track. Driving Audio replaces final generated audio; Reference Audio only conditions generation.
### Main Sampler controls
| Displayed control | Meaning | Recommended starting point |
|---|---|---|
| `Prompt Format` | `Auto`, `Fixed`, `List`, or `Timeline` interpretation of `Sequence Prompt` | `Auto` unless you need to force one parser |
| `Continuity` | Prior Video context retained at each chunk boundary | `Balanced — 22 frames` for Standard audiovisual continuation |
| `Base Seed` | Base for deterministic per-chunk seed derivation | Keep the value unchanged when continuing, comparing, or selecting Takes |
| `Control After Generate` | What ComfyUI does to `Base Seed` after a Queue | `fixed` for `Review Each Chunk`, resume, and controlled comparisons |
| `Audio Continuity` | Carries generated-audio context across boundaries | `true` for normal audiovisual generation |
| `Chunks` | Planned total chunk count, from 1 to 16 | Enter the final total, not the number to add next |
| `Seconds per Chunk` | Duration shared by every chunk | 5–15 seconds is the validated range; see duration notes below |
| `Total Length` | Read-only `Chunks × Seconds per Chunk` | Check only; it never edits either input |
| `Size Source` | `First Image` or `Manual` output geometry | First Image for I2VA/FL2VA; Manual for T2VA or exact dimensions |
| `Resolution` | First-Image sizing preset | `Draft — 0.30 MP` for tests, `Balanced — 0.60 MP` for more detail, or `Native 768` for the H3-native short edge |
| `Custom MP` | Custom First-Image pixel budget | Visible only when `Resolution = Custom` |
| `Width` / `Height` | Exact output canvas in 32-pixel steps | Visible/editable only in Manual mode; 32–16384 is accepted |
| `Run` | `Generate Full Video` or `Review Each Chunk` | Use Review when you want a human decision after each physical group |
| `Progress` | Saved raw chunks, safe resume, and Take history | Review turns it On automatically; enable it for resume/regeneration |
| `Ready to Queue` | Plain-language summary of the next Queue | Read it before pressing ComfyUI's top-right blue `Run` button |
| `Show Advanced Settings` / `Hide Advanced Settings` | Shows or hides technical controls | Visibility only; it does not change their values |
`Continuity = Balanced — 22 frames` with `Continuation Backend = Standard` and `Audio Continuity = true` uses the current Masked AV route. `Fast — 5 frames`, `Strong — 39 frames (Experimental)`, and `Auto — conservative` safely resolve to the older Reference Context route while generated-audio continuity is on. With Audio Continuity off, Standard uses the Video-only masked route.
#### Choose First Image sizing or Manual sizing
![First Image sizing with Draft 0.30 MP](docs/images/v38-manual/sampler-size-first-image-draft.png)
`Size Source = First Image` preserves the connected First Image aspect ratio. `Resolution` then chooses its pixel area:
| Preset | Target |
|---|---|
| `Draft — 0.30 MP` | Fastest and lowest-memory First Image starting point |
| `Balanced — 0.60 MP` | More detail with greater memory and processing cost |
| `Native 768` | 768 px short-edge target with a 1344 px long-edge cap |
| `Custom` | `Custom MP` selected by the user; separate from the Native 768 cap |
![Size Source First Image tooltip](docs/images/v38-manual/size-source-first-image-tooltip.png)
`Size Source = Manual` ignores the preset and uses exact Width/Height values. Both must be multiples of 32. Manual is the normal choice for T2VA and also supports a 32×32 diagnostic canvas when only generated audio is being checked.
![Manual Size Source with explicit Width and Height](docs/images/v38-manual/size-source-manual-640.png)
If First Image mode is selected but no usable First Image reaches the Sampler, V3.8 uses the stored Manual Width/Height as a safe fallback and reports the dimensions in `status`. Select `Size Source = Manual` to inspect or edit those values; Width/Height are hidden in the First Image facade. Reference Images and Video Guide never become implicit size sources. The historical `Auto / Landscape / Portrait / Square` values are migration/API compatibility values, not current Main choices.
Size selection is built into the V3.8 Sampler. A separate megapixel, empty-latent, or image-size node is not required for the normal Continuum workflow.
#### Choose a chunk duration
- **5 seconds** is a valid H3 duration and the fastest practical choice for workflow checks, Review UI checks, and quick Takes.
- **8–10 seconds** usually reduces the number of handoffs while keeping each Queue easier to review and rerun.
- **15 seconds** is the [upstream MiniMax H3 native maximum per generation](https://github.com/MiniMax-AI/cli/blob/main/skill/h3-video/SKILL.md) and minimizes the number of boundaries, but it increases per-chunk time and memory. Longer is not automatically higher quality.
- Continuum accepts 4–30 seconds for compatibility and experimentation. Values above 15 seconds are not the same as an upstream native-duration recommendation and can be expensive at high resolution.
For an audio-only listening diagnostic, use T2VA, `Size Source = Manual`, and a very small canvas such as 32×32, then play the saved video and ignore its picture. This is useful for hearing music or boundary continuity; it is not evidence of normal-resolution video quality.
### Advanced Sampler controls
| Control | When it appears | Meaning |
|---|---|---|
| `Continuation Backend` | Advanced open | `Standard` is the V3.8 path; `Compatibility` restores the older Reference Context route for comparison |
| `Regenerate From` | Advanced open and Progress On | `Auto` resumes the longest compatible prefix; `Chunk N` reuses earlier chunks and rebuilds N through the target |
| `Variation Nonce` | Explicit `Regenerate From = Chunk N` | `0`: automatic variation selection with interrupted-run resume; `1` or higher: a fixed variation value. Base Seed and the other generation settings stay unchanged |
| `Run Name (Optional Override)` | Advanced open and Progress On | Stable name for resume and Render History; blank uses the Sampler's automatic identity |
| `Reference Image Size` | Advanced open and a Reference Image connected | `Match Output` is practical; `Max Identity` preserves more reference detail and may use more memory |
| `Video Guide Size` | Advanced open and Video Guide connected | `Efficient — 0.4 MP`, `Balanced — 0.6 MP`, or `Match Output` |
Frontend-managed IDs, selected Take IDs, one-shot review actions, diagnostics, preview, and legacy compatibility values are deliberately not editable as ordinary node widgets. The corresponding settings or action buttons below are the supported interface.
### Review-state controls
When `Run = Review Each Chunk`, `Progress` is On, and a review unit is ready, the settings view changes to this action view:
| Button | What the next top-right ComfyUI `Run` does |
|---|---|
| `Use it and continue` | Accepts the current result, reuses it, and generates one next physical group |
| `Try this chunk again` | Keeps the earlier accepted prefix and creates another Take of the current review unit |
| `Use it and finish the rest` | Accepts the current result and generates every remaining group without further review pauses |
| `Back to Settings` | Shows the normal settings; does not queue, reset, or discard the review |
| `Return to Review` | Returns from settings to the pending review; does not undo edited values |
| `Render History — N Takes` | Opens or closes stored Take browsing; N is Take count, not chunk count |
| `Previous Take` / `Next Take` | Changes the selected stored Take only |
| `Use This Take` | Makes the selected Take canonical on the next Queue; no new sampling is required |
| `Continue From Here` | Branches from the selected Take and generates the next review unit |
The action button selects intent and gains a `✓`; it does not start generation. Press ComfyUI's top-right blue `Run` button afterward. Full step-by-step examples begin in [Review, continue, and revise a chunked video](#review-continue-and-revise-a-chunked-video).
### H3 Continuum Reference Audios
`H3 Continuum Reference Audios` bundles up to three standalone audio references behind one `Audio References (Optional)` Sampler socket. Connect the references without gaps and use `<Audio 1>`, `<Audio 2>`, and `<Audio 3>` in the same order in the prompt. One shared Core Audio VAE encodes each reference independently. This path never replaces generated final audio and does not change the separate Driving Audio contract. Existing workflows may keep using the legacy single `Reference Audio (Optional)` socket; do not connect the legacy and bundled paths together.
Its complete interface is `Reference Audio 1 (Optional)`, `Reference Audio 2 (Optional)`, `Reference Audio 3 (Optional)`, one shared `Reference Audio VAE`, and the `audio_references` output. Leave no gap in the connected order: do not connect Audio 1 and Audio 3 while leaving Audio 2 empty.
The small arrow/triangle seen beside `audio_references` is ComfyUI's connection direction/cable rendering, not an additional option. Place this helper to the left of the Sampler or use a reroute node if the cable crosses the node body.
### H3 Continuum Finalize
Finalize is normally left wired in the workflow rather than operated repeatedly. It assembles the decoded physical groups into the exact requested timeline. Required inputs are decoded `images`, decoded `audio`, and the Sampler's `assembly_plan`; optional `driving_audio` preserves the selected source track.
| Control | Meaning | Normal choice |
|---|---|---|
| `Audio Seam` | `Auto` corrects decoded audio boundaries only; `Off` leaves them unchanged | `Auto` unless diagnosing audio |
| `Video Seam` | `Auto`, experimental `Auto 2`, `Analyze Only`, or `Off` | Keep the supplied workflow value; use Analyze Only when measuring without altering frames |
| `Buffer Backend` | `Auto`, `RAM`, or `Disk-backed` storage for the assembled IMAGE buffer | `Auto` |
`Exact Total Duration` is managed as On and `Report Detail` is controlled from ComfyUI Settings. Driving Audio bypasses generated audio and Audio Seam, but Video Seam can still apply. Finalize outputs final `images`, final `audio`, and a text `report` for the downstream Save Video node.
### H3 Continuum Second Pass
Second Pass is the Advanced bridge after the complete first pass. It takes `model`, `clip`, `sampler`, low-denoise `sigmas`, externally processed `video_latents`, the matching first-pass `audio_latents`, the original `assembly_plan`, and a separate `refine_seed`. Optional `refine_context` restores the physical group's First/Last/Reference conditioning; optional `video_vae` is used only when that context requires image re-encoding.
Its outputs are `refined_video_latents`, bit-exact first-pass `audio_latents`, an `updated_assembly_plan`, and `status`. Complete Review first: Second Pass is not supported on a partial Review sequence. It is not an automatic Hi-Res button and does not include an upscaler.
### ComfyUI Settings added by Continuum
| Setting | Default | Effect |
|---|---:|---|
| `H3 Continuum: Sampling Preview` | On | Shows live sampling previews; Off only reduces preview overhead |
| `H3 Continuum: Developer Diagnostics` | Off | Enables developer-only logging/assertions; leave Off for normal use |
| `H3 Continuum: Detailed Report` | Off | Adds read-only detail to Sampler status and Finalize report; generated tensors are unchanged |
### Turbo LoRA and Spectrum in supplied workflows
![Example third-party LoRA selector with one LightX2V Turbo LoRA enabled](docs/images/v38-manual/turbo-lora-choices.png)
The four MiniMax H3 Turbo files shown in the example come from the LightX2V MiniMax-H3-Turbo project: [GitHub](https://github.com/ModelTC/Minimax-H3-Turbo) and [Hugging Face files](https://huggingface.co/lightx2v/Minimax-h3-Turbo). `FL2VA` files are for T2VA/I2VA/first-last workflows; `Ref2VA` is for Reference-to-Video. `_768p` identifies the training-resolution family. Select **one LoRA matching the task**—do not enable all four together merely because they are listed.
| File shown | Intended path | Distilled target recorded by the file/repository |
|---|---|---|
| `minimax_h3_fl2v_turbo_8step_v1.0_comfyui_bf16.safetensors` | FL2VA / T2VA, 544p family | 8-step; the upstream table also lists 4-step inference as an option for this checkpoint |
| `minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors` | FL2VA / T2VA, 768p family | 8-step |
| `minimax_h3_ref2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors` | Ref2VA, 768p family | 8-step |
| `minimax_h3_fl2v_turbo_4step_v1.2_768p_comfyui_bf16.safetensors` | FL2VA / T2VA, 768p family | 4-step |
The number in a Turbo filename is its distilled NFE target. Use the matching upstream recommendation unless a provided workflow explicitly documents a tested exception. In particular, using a 4-step LoRA with `Steps = 6` is a workflow-specific experiment, not the LightX2V default. `Euler`/`simple`, the actual Steps value, and the selected LoRA must be recorded together when comparing results.
`Power Lora Loader (rgthree)`, KJNodes SageAttention, ComfyUI-Easy-Use, and Spectrum are external components. Continuum does not install, enable, or tune them. The [V3.8 workflow](examples/workflows/MiniMax_H3_Continuum_V38.json) is the single supplied graph, distributed unchanged as JSON and ZIP. Its saved default is Spectrum enabled, no Turbo LoRA enabled, `res_multistep`, `simple`, and `Steps = 20`. All four custom-node packages are required to open the complete graph, including when switching it to Turbo.
The supplied prompt, media selections, and node titles have deliberately been preserved. Choose files available on your computer, disable unused optional inputs, and enter your own prompt before generating. Models, LoRAs, images, and audio are not included. A custom title such as `Save 3x5s Video` is only a saved label: actual duration follows the Sampler's `Chunks` and `Seconds per Chunk`, not that title.
The same graph can be used as the quick Turbo path: disable Spectrum, enable exactly one task-matched LightX2V Turbo LoRA, then select the sampler and Steps intended for that LoRA or for a separately documented tested variation. The supplied graph lists the FL2VA Turbo 4-step v1.2 768p file but leaves it disabled in the Spectrum default. The previously tested `Euler` / `simple` / `Steps = 6` setup with that 4-step LoRA is a workflow-specific variation, not the LightX2V upstream default. Do not enable Spectrum and a Turbo LoRA together merely because both controls are present.
### Known long-continuation limitation: Issue #13
[Issue #13](https://github.com/ukr8b3g-cmyk/ComfyUI-H3-Continuum/issues/13) remains open. Repeated continuation can increase contrast, edge energy, or apparent sharpness on some prompts and trajectories. V3.8 Standard has **no active production mitigation** for this issue; it preserves the accepted Masked AV behavior.
An experimental prefix-amplitude renormalization produced a strong improvement in one `6 × 5 s` run, but a later frozen `4 × 8 s` A/B/C gate did not reproduce the target drift and therefore applied gains of `1.0`; Standard and the experimental arm were bit-exact. The older Compatibility route did not justify replacing Standard and raised a separate boundary-audio concern. The accurate release statement is therefore: **the issue is not proven fixed, the current Standard path is unchanged, and experimental mitigation stays Default Off**. Report the first and worst affected chunk, workflow JSON, prompt, seed, model/LoRA, Steps/SIGMAS, size, Continuity, and Audio Continuity when reproducing it.
> **V3.8 support boundary:** V3.8 exports only the seven public nodes listed above. Some retain earlier IDs, including Finalize (`H3ContinuumAssembleSeamV35`) and Second Pass (`H3ContinuumSecondPassV35`); this does not make all older workflows compatible. A saved workflow that uses an ID outside the current seven-node surface can load as an unknown node. Use the matching historical GitHub Release/tag for that workflow instead of restoring its unsupported IDs in V3.8. See [V3.8 Release and Migration Policy](docs/V38_RELEASE_AND_MIGRATION.md).
The accepted 16GB GPU gates reached about `15.5-15.6 GiB` in the most complex cases. Actual use varies by GPU, driver, backend, model precision, resolution, and connected nodes; this is not a universal 16GB guarantee.
### Review, continue, and revise a chunked video
> **Live UI verification:** The repaired Review flow was rechecked in ComfyUI on 2026-09-07. The current walkthrough used Turbo4, actual `Steps = 4`, Euler/simple, `Draft — 0.30 MP`, and Spectrum Off. Chunk 1 reached the three-action review screen; `Use it and continue` then reused the accepted first chunk, generated only Chunk 2, and reached `Saved sequence is complete`. `Try this chunk again` was also live-validated after the Review repair. Timings below are measurements from that machine, not speed guarantees.
Start here when you already have a working V3.8 workflow and want to keep good chunks, retry a result, or extend a sequence. These instructions use the labels displayed on **H3 Continuum Sampler V3.8**. The **blue `Run` button at the top right of ComfyUI** starts execution. It is different from the Sampler's `Run` setting (`Review Each Chunk` or `Generate Full Video`). Continuum's review messages still say “press Queue”; on the frontend shown here, that means clicking the top-right blue `Run` button. Older frontends may label that button `Queue`.
![ComfyUI's top-right blue Run button starts the selected action](docs/images/v38-manual/live-execute-button.png)
Choose the task you need:
- [Prepare the settings for continuation](#1-prepare-the-settings-for-continuation)
- [Understand the first, shorter output](#2-generate-and-review-the-first-chunk)
- [Keep the result and generate the next chunk](#3-keep-the-result-and-generate-the-next-chunk)
- [Try the current chunk again](#4-try-the-current-chunk-again)
- [Keep the result and finish everything remaining](#5-keep-the-result-and-finish-everything-remaining)
- [Go back to settings without losing the review](#6-go-back-to-settings-without-losing-the-review)
- [Choose an earlier Take or branch from it](#7-choose-an-earlier-take-or-branch-from-it)
- [Regenerate from a particular chunk](#8-regenerate-from-a-particular-chunk)
- [Add more chunks to a completed sequence](#9-add-more-chunks-to-a-completed-sequence)
- [Understand continuation time and check reuse](#10-understand-continuation-time-and-check-reuse)
- [Troubleshoot a missing action or unexpected result](#11-troubleshoot-a-missing-action-or-unexpected-result)
#### Before you begin: total length is not the next Queue's output length
`Chunks` is the **total number of chunks you want**, not the number to add on the next Queue. `Seconds per Chunk` is the duration of each chunk. `Total Length` is the planned final duration; it is not a progress counter.
For example, `Chunks = 6` and `Seconds per Chunk = 5` means a 30-second target. With `Run = Review Each Chunk`, the first Queue normally creates only Chunk 1: a 5-second video. Continuing produces a 10-second video, then 15 seconds, and so on, until the target is complete. Each saved output contains the completed sequence so far, not just the newest 5 seconds.
The screenshots show **two chunks as a small example**. The same controls apply to three, four, five, six, or another supported total.
> **Last Image exception:** The examples below assume ordinary, separately generated chunks. When Last Image uses Long Terminal Merge, the final pair is generated and reviewed together. Continuing or retrying that pair operates on both chunks as one unit. Do not expect a separate review stop between them.
#### 1. Prepare the settings for continuation
1. Find `Base Seed` and keep its current number. You do not need to copy the number in the screenshot.
2. Directly below it, set `Control After Generate` to `fixed`.
![Base Seed and Control After Generate set to fixed](docs/images/v38-manual/seed-fixed.png)
3. Set `Chunks` to your intended **final total**. Use `2` for the screenshot's example, or your own total such as `6`.
4. Set `Seconds per Chunk` to the duration you want. The example uses `5`.
5. Check `Total Length`: two chunks of 5 seconds should show `10 seconds`; six should show `30 seconds`.
6. Set `Run` to `Review Each Chunk`.
7. Set `Progress` to `On — Resume and Takes available`.
8. If `Regenerate From` is visible under `Show Advanced Settings`, leave it at `Auto` for normal continuation.
9. Check that the green `Ready to Queue` card describes the total and says `Review each chunk`.
![Review settings with fixed seed, two 5-second chunks, Review Each Chunk, and Progress On](docs/images/v38-manual/live-review-settings.png)
**Keep these settings while continuing:** `Base Seed`, `Control After Generate = fixed`, `Seconds per Chunk`, and `Progress = On — Resume and Takes available`. Keep the same workflow, prompt, input media, model, sampler, step schedule, size, and continuation settings too. Leave `Run Name (Optional Override)` unchanged. Changing generation inputs can make saved chunks incompatible; keeping the seed alone does not guarantee reuse.
For ordinary continuation, do not increase `Chunks` after every Queue. If the goal is six chunks, leave it at `6` until those six are complete.
#### 2. Generate and review the first chunk
1. Click the top-right blue `Run` button once.
2. Wait for the workflow, including video saving, to finish.
3. Play the resulting video. In the 5-second example, the first output is **5 seconds**, even though `Total Length` says 10 or 30 seconds.
4. Look at the Sampler. While more chunks remain, it should show `Chunk 1 is ready for review` and the actions below.
![Chunk 1 ready for review with continue, retry, finish, and Back to Settings buttons](docs/images/v38-manual/live-review-actions-steps4.png)
The shorter output is intentional: Continuum is waiting for your decision before spending time on later chunks. If your total is only one chunk, it is already complete; there is no next chunk within that target.
`Render History — 68 Takes` in this screenshot is a count of stored Takes from that run's history. It does **not** mean the target is 68 chunks. Your count will differ.
#### 3. Keep the result and generate the next chunk
1. Click `Use it and continue` on the review panel.
2. Confirm the button now shows `✓ Use it and continue`. The card says `Selected: Use it and continue. Press Queue to run this action.`
![Use it and continue selected; Queue is still required](docs/images/v38-manual/live-continue-selected-steps4.png)
3. Click the top-right blue `Run` button. Clicking the review button alone does not start generation.
4. Wait for completion and play the new output. The accepted chunks are reused; the next chunk is newly generated.
5. If the target is not yet complete, review the new chunk and repeat from step 1.
**Example:** With `Chunks = 6` and three 5-second chunks already completed, this action reuses Chunks 1–3 and generates Chunk 4. The saved video becomes 20 seconds, and you review Chunk 4 next. It does not immediately generate Chunks 5–6.
With the screenshot's `Chunks = 2`, continuing after Chunk 1 completes the target and produces a 10-second video. There is no third chunk unless you increase the target as described in [section 9](#9-add-more-chunks-to-a-completed-sequence).
![The two-chunk target is complete after only Chunk 2 is generated](docs/images/v38-manual/live-sequence-complete-steps4.png)
At completion, `Try this chunk again` means “make another Take of the last reviewed chunk,” here Chunk 2. It does not mean that Continuum discarded Chunk 1. Use `Back to Settings` to change the target or `Render History` to inspect stored Takes.
#### 4. Try the current chunk again
Use this when the **chunk currently being reviewed** is the one you want to replace.
1. Keep `Base Seed` unchanged and `Control After Generate = fixed`. Do not switch to `randomize` to get another Take.
2. Click `Try this chunk again` on the review panel.
3. Confirm that this action has the `✓`, then click the top-right blue `Run` button.
4. Play the new result. Continuum keeps the earlier accepted chunks and creates another Take of the reviewed chunk, with its own variation managed internally.
5. If you like it, use `Use it and continue`. Otherwise, repeat `Try this chunk again` and the top-right blue `Run` button, or select an older Take from `Render History`.
**Example:** While reviewing Chunk 3 of a six-chunk target, retrying reuses Chunks 1–2 and generates a new Chunk 3. The output is still 15 seconds, not 20 or 30 seconds. Chunks 4–6 have not been generated on this path yet. The older Take remains in history.
![Try this chunk again selected; the top-right Run button executes the retry](docs/images/v38-manual/live-retry-selected.png)
To replace an earlier chunk after moving past it, use [Render History](#7-choose-an-earlier-take-or-branch-from-it) or [Regenerate From](#8-regenerate-from-a-particular-chunk), not the current-chunk retry button.
#### 5. Keep the result and finish everything remaining
1. Play and approve the chunk currently being reviewed.
2. Leave `Chunks` at the final total you want.
3. Click `Use it and finish the rest`.
4. Confirm its `✓`, then click the top-right blue `Run` button.
5. Wait for all remaining chunks and the final video to finish. This Queue does not pause for a review after each remaining chunk.
These three buttons are different even though all require `Queue`:
| While reviewing Chunk 3 of a six-chunk, 5-second-per-chunk target | Reused chunks | Newly generated chunks on the next Queue | Saved duration |
|---|---|---|---|
| `Use it and continue` | 1–3 | 4 | 20 seconds |
| `Try this chunk again` | 1–2 | A new Take of 3 | 15 seconds |
| `Use it and finish the rest` | 1–3 | 4–6 | 30 seconds |
For a two-chunk target after Chunk 1, `Use it and continue` and `Use it and finish the rest` produce the same remaining amount: only Chunk 2 is left. Their difference becomes clear with a larger target.
#### 6. Go back to settings without losing the review
1. On the review panel, click `Back to Settings`.
2. The normal controls appear again. You can inspect `Chunks`, `Run`, `Progress`, and the other settings.
3. Click `Show Advanced Settings` only if you need controls such as `Regenerate From` or `Run Name (Optional Override)`.
4. To go back without changing the operation, click `Return to Review`.
![Back to Settings keeps the completed sequence and exposes Return to Review](docs/images/v38-manual/live-settings-complete-steps4.png)
![Return to Review above Regenerate From, Run Name, and Continuation Backend](docs/images/v38-manual/return-to-review.png)
**Neither navigation button queues work, deletes a Take, resets the run, nor cancels a selected action.** `Return to Review` also does not undo settings you edited. Before the next Queue, select the action you actually want and check its `✓`.
`Show Advanced Settings` and `Hide Advanced Settings` only show or hide controls; they do not turn those settings on or off. `Back to Settings` is not a “start over” button.
#### 7. Choose an earlier Take or branch from it
A **Take** is a stored version of a generated result. A **branch** is an alternative continuation from a chosen result; the old history is retained.
1. On the review panel, click `Render History — … Takes`.
2. Use `Previous Take` and `Next Take` to choose a stored result. Read the displayed chunk and branch information; selecting an entry by itself does not replace your current sequence.
![Render History with Take navigation and the two explicit Take actions](docs/images/v38-manual/live-render-history-steps4.png)
3. Choose one of the following actions, then click the top-right blue `Run` button:
- `Use This Take`: make the selected stored result the active result. This action runs no new sampling; the output path can still decode and save the selected sequence.
- `Continue From Here`: keep the sequence through the selected Take and generate the next review unit on a new continuation path.
4. Review the resulting output before continuing again.
**Example:** To keep an older Chunk 2 and make a new Chunk 3, select that Chunk 2 Take and use `Continue From Here`, then the top-right blue `Run` button. Do not select Chunk 3 if Chunk 3 is the part you want replaced. Later chunks from the old path are not automatically attached to the new one.
Keep `Regenerate From = Auto` when using Take actions. Do not combine an explicit `Regenerate From` selection with `Use This Take` or `Continue From Here`. If the selected Take already completes the configured total, `Continue From Here` has no next chunk to generate.
#### 8. Regenerate from a particular chunk
Use this when you know the **first chunk that must be redone**. Unlike retrying the current review, this can rebuild a longer section of an existing sequence.
1. Click `Back to Settings` if you are on the review panel.
2. Keep `Base Seed`, the total `Chunks`, and `Seconds per Chunk` unchanged. Keep `Control After Generate = fixed` and `Progress = On — Resume and Takes available`.
3. Click `Show Advanced Settings`.
4. Set `Regenerate From` to the first chunk to redo, such as `Chunk 3`. Earlier chunks can be reused only if their inputs remain compatible.
5. Set `Variation Nonce`, which appears for explicit regeneration. Keep `Base Seed` fixed. `0` selects a new variation automatically after a completed regeneration; a compatible interrupted regeneration resumes its existing variation instead. A value of `1` or higher fixes the variation: keep it to reproduce/resume that variation, or change it to request another. Repeating the same positive value with identical inputs does not request a different result. This is separate from `Try this chunk again`, which advances the review variation automatically.
![Regenerate From exposes Variation Nonce for an explicit regeneration](docs/images/v38-manual/live-regenerate-from-chunk2.png)
6. Set `Run` to `Generate Full Video` to rebuild everything from the selected chunk through your target in one Queue.
![Run set to Generate Full Video while Progress stays On](docs/images/v38-manual/full-video-progress.png)
7. Click the top-right blue `Run` button, wait for completion, and check the new full-length output.
8. Before ordinary continuation or review actions, set `Regenerate From` back to `Auto` so that the next Queue is not another explicit request to redo that section.
**Example:** With a completed six-chunk sequence, `Regenerate From = Chunk 3` and `Run = Generate Full Video` reuse compatible Chunks 1–2 and regenerate Chunks 3–6. This is **four newly generated chunks**, not only Chunk 3. Later chunks depend on the changed continuation and must follow the new path.
If you want a review pause instead, choose `Run = Review Each Chunk` in step 6. The next Queue generates the first requested review unit, not the whole remaining section. After reviewing it, select `Use it and continue` to proceed one unit at a time, or `Use it and finish the rest` to complete the section. Keep earlier-chunk inputs unchanged if you want those chunks reused.
#### 9. Add more chunks to a completed sequence
For a compatible saved run without a Last Image constraint, increasing the target can reuse completed chunks. This requires saved progress, not just an existing MP4 file.
1. Keep the same Sampler/workflow and `Run Name (Optional Override)`. Do not create a new run identity.
2. Keep `Base Seed` unchanged and `Control After Generate = fixed`.
3. Keep `Progress = On — Resume and Takes available`, and keep the saved progress files available.
4. Keep `Seconds per Chunk` and the generation inputs unchanged.
5. Set `Regenerate From = Auto`.
6. Change **only the target count** in `Chunks`: for example, change `3` to `5` to add two chunks. Do not set it to `2`.
7. Choose `Run = Review Each Chunk` for one new review unit per Queue, or `Run = Generate Full Video` to finish all missing chunks.
8. Check `Total Length`, then click the top-right blue `Run` button and check the reuse report described below.
With compatible progress for three 5-second chunks, the new target is 25 seconds. Review mode should first produce Chunk 4 and a 20-second output; continuing again completes Chunk 5. Full-video mode should produce Chunks 4–5 and the 25-second output in one Queue.
**Do not assume append-only reuse with Last Image.** Extending a sequence changes where its final-image constraint belongs. The former last chunk, or a terminal pair, may need regeneration. Likewise, changing the model, prompt, media, dimensions, schedule, or continuation settings can invalidate saved progress. `Progress = On` enables compatibility checking; it does not force incompatible chunks to be reused.
The extension path is covered by CPU compatibility tests, including two-to-three chunks and Last Image invalidation. It is not the same GPU test as the two-chunk review timing example below; arbitrary extensions and media combinations have not all been GPU-verified.
#### 10. Understand continuation time and check reuse
Continuing does not mean saving only the new segment. With compatible saved progress, the normal workflow:
1. Reuses the accepted chunks' stored Video/Audio latents without sampling them again.
2. Samples the requested new chunk or remaining section.
3. Decodes the completed sequence so far, runs `H3 Continuum Finalize`, and saves the combined video again.
The full-output work grows as the sequence gets longer. Consequently, the next Queue can take as long as the first, or longer, even though earlier chunks are **not** being sampled again. Loading, preparation, decoding, assembly, saving, and other workflow overhead all contribute to total time.
The latest live GPU check used Turbo4, Euler/simple, actual `Steps = 4`, Spectrum Off, and `Draft — 0.30 MP` with `Chunks = 2`, `Seconds per Chunk = 5`, and Review enabled:
| Queue | Sampler work | H3 Continuum Sampler node time | Saved video |
|---|---|---:|---:|
| First | Generate Chunk 1 | 103.802 s | 5 seconds |
| After `Use it and continue` | Reuse Chunk 1; generate Chunk 2 | 43.738 s | 10 seconds |
Each Queue sampled one chunk with four steps. The second Queue did not sample Chunk 1 again; it sampled only the requested next chunk, then decoded, finalized, and saved the combined 10-second sequence. The first Queue also included cold-start/model preparation effects, so the difference must not be treated as a general speed ratio. Full-sequence decode and save work still occurs on continuation.
To inspect your own run:
1. Open ComfyUI Settings and search for `H3 Continuum: Detailed Report`.
2. Enable that setting before the Queue you want to inspect.
3. After completion, inspect the Sampler's `status` output through a text-display node in your workflow.
4. In the two-chunk example's second Queue, look for `1 reused, 1 generated, 2 total`. Detailed fields should show `sampled_physical_groups=1` and, with four steps, `sampling_steps_total=4`, not `8`.
The report field names are diagnostic text, not controls you need to set. For a larger target, use the reported reused/generated counts rather than timing alone. Terminal Merge can combine two chunks into one sampled group, so its group count differs from its chunk count.
#### 11. Troubleshoot a missing action or unexpected result
| What you see | What to check or do |
|---|---|
| A 5-second video despite a longer `Total Length` | In `Review Each Chunk`, this is the expected first output. Review it, select an action, then click the top-right blue `Run` button. |
| No next-chunk action | Check whether the configured total is already complete. Otherwise, wait for Queue completion and verify `Run = Review Each Chunk` and `Progress = On — Resume and Takes available`. If you opened settings, click `Return to Review`. |
| No review panel even though an incomplete Review run finished successfully | Inspect the Sampler's `status` and any ComfyUI error. This is not a reason to assume all chunks finished or to change `Base Seed`; the frontend must receive the saved review state. |
| Clicking an action appears to do nothing | Check its `✓`, then click ComfyUI's top-right blue `Run` button. The action button only selects what Queue will do. |
| `Set Control After Generate to fixed` | Set that exact control to `fixed` and retain the original `Base Seed` used for the saved chunks. |
| Settings disappeared behind the review panel | Click `Back to Settings`. Use `Return to Review` to come back; neither navigation button resets the run. |
| The next Queue takes as long as the first | Check reused/generated counts. Full-sequence decoding and saving still run; elapsed time alone cannot tell you whether chunks were resampled. |
| Earlier chunks are generated again | Check `Progress`, saved files, run identity, `Base Seed`, and changed generation inputs. Check that `Regenerate From` is `Auto` unless you intentionally requested regeneration. |
| Retrying changed more than one chunk | A terminal pair is one review unit. Also distinguish `Try this chunk again` from `Regenerate From`, which rebuilds the chosen chunk and its following section. |
| You want to stop choosing an action after every chunk | At the review panel, select `Use it and finish the rest`, then click the top-right blue `Run` button. Keep `Chunks` at your intended final total. |
Driving Audio can be used with Review and Smart Regenerate. The Continuum Image, Audio, and Video loaders support native bypass for optional media paths.
> **Second Pass limitation:** Finish the reviewed sequence before running Second Pass. Second Pass / `refine_context` is not supported on a partial Review sequence.
## Historical implementation notes (pre-V3.8; not the standard workflow)
The version-labelled sections below document earlier releases and compatibility work. Their node-registration and saved-workflow guarantees apply to those historical packages, not to V3.8. They do not change the current seven-node surface or the V3.8 standard path described above. Open historical workflows with their matching Release/tag.
### V3.7 High-Resolution Refinement Foundation
V3.7 adds **H3 Continuum Sampler V3.7** and completes two foundations for resolution-changing Second Pass workflows without changing V3.6 Production defaults or the existing SIGMAS socket.
@@ -35,7 +551,7 @@ In this gate, Tail 6 finished in about 64% of the Tail 10 time: roughly 1 minute
V3.7 can map one Still Image Guide from an absolute frame to its owning physical group and rebuild it from the original image during a high-resolution Second Pass. Its positioning, Terminal Merge ownership, Run Storage identity, and non-owner isolation passed correctness testing. Core Add Guide uses hard-anchor semantics, however, so a Guide can cause an abrupt trajectory change at the anchor and can redirect later motion. **Still Image Guide is Experimental and remains on Production HOLD.** It should not be treated as a smooth transition control.
## V3.6.1 Maintenance Hotfix
### V3.6.1 Maintenance Hotfix
V3.6.1 fixes focused fail-open/compatibility issues without changing the accepted Balanced 22 Masked AV path. Mixed Timeline/List prompts now report `H3C-P105`; Timeline parsing ignores only standalone `---` lines, keeps existing uncovered-chunk fallback, and never stops generation because of prompt syntax.
@@ -43,7 +559,7 @@ With `Continuation Backend = Standard` and Audio Continuity enabled, `Balanced
Run Storage now treats every absent Last Frame spelling as the same empty identity. A normal no-Last-Frame run can therefore extend from two to three chunks as `2 reused, 1 generated`, including narrowly compatible V3.6.1 caches whose former final chunk stored `none`. A real connected Last Frame and the Long Terminal Merge atomic pair remain strict. Turning Run Storage Off also resets the hidden Regenerate From and Variation Nonce values to `Auto` and `0` before queueing.
## V3.6 Masked AV Continuation
### V3.6 Masked AV Continuation
![H3 Continuum V3.6 Masked AV Continuation](docs/images/v36-masked-av-continuation.png)
@@ -64,7 +580,7 @@ Internal transport identifiers are not exposed in the UI. Run Storage identity f
- In the tested FL2VA Terminal Group 2 pairs, Standard removed 2,874 packed rows (`8.01%`) and reduced median Sampling time by `4.06%` versus Compatibility. Performance varies by model, hardware, and workflow.
- `chunk_seconds` now accepts 4.0–30.0 seconds with a 5.0-second default and 0.1-second step. The 5–15 second range remains recommended and validated; longer high-resolution chunks can substantially increase VRAM use and runtime.
V3.5.3, V3.5, and V3.4 Node IDs and saved workflows remain registered. V3.5.3 continues to use its original Reference Context behavior and is not silently redirected to the V3.6 backend.
In the historical V3.6 package, V3.5.3, V3.5, and V3.4 Node IDs remained registered for saved workflows. V3.5.3 retained its original Reference Context behavior rather than being silently redirected to the V3.6 backend. This is not a V3.8 registration guarantee.
## V3.5.3 Maintenance Hotfix
@@ -99,7 +615,7 @@ Prompt/CLIP figures measure only the conditioning subphase, not total generation
The measured Sage-only production baselines on the tested RTX 5060 Ti 16 GB / 64 GB system were 168.069 seconds for 1×5-second 576×576 T2VA and 379.765 seconds for 3×5-second 640×640 FL2VA Long Terminal Merge. These are configuration-specific baselines, not universal speed guarantees. Sampling remained the dominant cost; Continuum Assemble + Seam stayed below 1%.
> **V3.7.0 is the current release.** V3.6.1 remains the maintenance/compatibility baseline. Older Node IDs, backend socket keys, and saved-workflow loading remain intentionally supported. Production defaults are unchanged, and Still Image Guide remains Experimental.
> **V3.8.0 is the current release candidate.** Historical implementation modules remain in source because V3.8 reuses them internally. Only the seven current public nodes are exported, including the earlier IDs retained for those nodes. Use the matching historical Release/tag for workflows requiring other IDs. Still Image Guide remains Experimental.
## V3.5.1 Reference Audio & Compatibility Update
@@ -110,7 +626,7 @@ V3.5.1 added two focused features without changing the V3.4 Sampling, Conditioni
The Reference Audio sockets are permanently defined by Python `INPUT_TYPES`. Dynamic socket changes and the UI-only `Hidden / Show` control were removed to prevent workflow save/reload value shifts. Node IDs, backend keys, Sampling, Conditioning, standard Seed handling, and other widgets are unchanged.
All V3.4 node IDs and backend socket keys remain registered intentionally for saved-workflow compatibility. Existing V3.4/V3.5 workflows continue to load; V3.5.1 clarified the displayed input names without rewriting saved links.
In the historical V3.5.1 package, V3.4 node IDs and backend socket keys remained registered for saved-workflow compatibility. V3.4/V3.5 workflows continued to load there; V3.5.1 clarified the displayed input names without rewriting saved links. V3.8 instead uses the seven-node support boundary above.
### Reference inputs at a glance
@@ -253,7 +769,7 @@ For the failed 3 x 5s case, First Pass and the 37T Second Pass group completed.
## V3.4 compatibility baseline
V3.4 nodes are retained specifically so saved workflows do not break. Their Node IDs, public sockets, Sampling, Conditioning, Terminal Merge, Assembly, Seam, and Run Storage behavior were not replaced by V3.5. Users who do not need Second Pass or disk-backed assembly can continue using V3.4 normally.
The historical V3.5 package retained V3.4 nodes for saved workflows; it did not replace their Node IDs, public sockets, Sampling, Conditioning, Terminal Merge, Assembly, Seam, or Run Storage behavior. Those historical workflows remain available through the corresponding Release/tag. V3.8 does not export IDs outside its current seven public nodes, even when their implementation modules remain in source.
![H3 Continuum V3.4 workflow overview](docs/images/v34-workflow-overview.png)
@@ -280,19 +796,12 @@ V3.4 therefore prioritizes:
This is a usability and reliability decision, not a claim that the experimental timeline paths are impossible. They are hidden from the stable interface while the public workflow stays focused on predictable user-controlled inputs.
## Example workflows
## Example workflow
- [V3.6 recommended template](examples/workflows/MiniMax_H3_Continuum_V36.json)
- [V3.5 compatibility template](examples/workflows/MiniMax_H3_Continuum_V35.json)
- [V3.5.1 LBH + Conditioning Bridge connection example](examples/workflows/MiniMax_H3_Continuum_V351_LBH_Conditioning_Bridge.json)
- [V3.4 standard](examples/workflows/MiniMax_H3_Continuum_V34.json)
- [V3.4 Turbo](examples/workflows/MiniMax_H3_Continuum_V34_turbo.json)
- [V3.8 workflow JSON](examples/workflows/MiniMax_H3_Continuum_V38.json) — Spectrum enabled by default; switch the same graph to LightX2V Turbo as described above
- [V3.8 workflow ZIP](examples/workflows/MiniMax_H3_Continuum_V38.zip) — contains exactly the same JSON, not another variant or a custom-node installer
The V3.6 template is the recommended starting point. It selects the Standard continuation backend; Hi-Res Fix is disabled by default, the V3.5 Assemble backend remains Auto, and First Frame, Last Frame, and Reference Images 1-3 share one megapixel control. `Video Guide Size` controls the frame batch used by `Video Guide Frames`; the video loader remains responsible for decoding and frame-rate conversion. The V3.5 template remains unchanged for compatibility.
The V3.4 templates remain valid for saved-workflow compatibility.
The templates include optional external nodes such as Spectrum, Video Helper Suite, rgthree, EasyUse, and RTX Video Super Resolution. Install, replace, connect, or bypass them according to your installation. Media and acceleration choices remain under user control.
The declared Registry payload includes this one graph in both formats; it is **not dependency-free**. Spectrum, rgthree, KJNodes, and ComfyUI-Easy-Use must be installed separately. Historical workflow files remain in GitHub source but are excluded from the Registry payload. For an older saved workflow, use its matching historical Release/tag as described in the [migration policy](docs/V38_RELEASE_AND_MIGRATION.md). Registry packaging validation/publication is separate from this GitHub source update.
## V3.4 feature details
@@ -373,7 +882,7 @@ Hard stops remain only for states that cannot execute safely, including corrupt
### Cleaner interface
The public nodes focus on normal production controls. Developer diagnostics and detailed reports are available through ComfyUI settings. The current release path uses the V3.7 sampler with the V3.5 low-memory assembler. With `guide` disconnected, it preserves the V3.6 Production defaults.
The public nodes focus on normal production controls. Developer diagnostics and detailed reports are available through ComfyUI settings. The current release path uses `H3 Continuum Sampler V3.8`; older sampler and assembler notes below are retained for historical compatibility context.
<img width="389" alt="H3 Continuum Sampler V3.7 with optional Guide input" src="docs/images/v37-sampler-node.png" />
@@ -381,11 +890,11 @@ The public nodes focus on normal production controls. Developer diagnostics and
### Timeline paths
Experimental Timeline Video and earlier timeline-audio paths are no longer public V3.4 inputs. They are hidden rather than destructively removed. Existing V3.3 workflows can continue through legacy nodes, but new stable workflows should use `Driving Audio` and `Video Guide Frames`.
Experimental Timeline Video and earlier timeline-audio paths remain in historical implementation code but are not exported by V3.8. Open V3.3 workflows with their historical package; new V3.8 workflows should use `Driving Audio` and `Video Guide Frames`.
## Installation
Requires ComfyUI 0.32.0 or later. Package validation passed on ComfyUI 0.33.3, the V3.6.1 GPU smoke test passed on ComfyUI 0.34.0, and the V3.7 Conditioning/RefineSchedule correctness gates passed on ComfyUI 0.34.2; the latest ComfyUI release is not required.
V3.8 is verified against ComfyUI 0.34.2. Historical acceptance records below may mention older ComfyUI versions; they are not the current installation target.
### Updating an existing installation
@@ -398,6 +907,8 @@ git pull --ff-only origin main
Restart ComfyUI after the update. If the node was installed with ComfyUI Manager, use its **Update** action instead of running `git pull` manually. Do not mix Manager updates and a separate Git checkout for the same installation.
After the backend restart, search for `H3 Continuum Sampler V3.8`. The complete V3.8 search surface contains the seven nodes listed above. If they are missing, check the startup console for the `H3 Continuum 3.8.0 loaded` message and any `ComfyUI-H3-Continuum` import error.
Search for H3 Continuum or Continuum in ComfyUI Manager, or install manually:
~~~bash
@@ -618,7 +1129,8 @@ To generate a different second part while keeping the first part:
1. Keep the same Run Name, Base Seed, model, LoRA, resolution, sampler, SIGMAS/steps, references, and Continuation settings.
2. Set `Regenerate From` to `Chunk 2`.
3. Queue the workflow again.
3. Leave `Variation Nonce = 0` for automatic new variations after completed regenerations, or choose a different positive value for an explicit variation. A compatible interrupted regeneration at `0` resumes its existing variation; reusing the same positive value does not request a different result.
4. Queue the workflow again.
Continuum loads the stored Chunk 1 instead of Sampling it again, uses its finalized end as the continuation context, and Samples a new Chunk 2. The report should show `1 reused, 1 generated`. The complete output is then decoded and assembled again; the saved first chunk is reused, while boundary Seam processing is evaluated during the new assembly.
@@ -705,7 +1217,11 @@ Use a 24 fps source for `Video Guide Frames`. `Load Video (Upload)` may accept f
## Current validation status
The V3.6 release gate includes the complete PIG-0 through PIG-5 Production Integration acceptance: backend-scoped Run Storage, real-cache Save/Resume/Regenerate From, atomic Terminal Merge reuse, Reference Image/Audio retention, bit-exact protected prefixes, GPU workflow output, numeric Audio Seam analysis, and subjective Audio PASS. Final automated validation is `527 passed`; the complete package checklist is recorded in `PACKAGE_VALIDATION.txt`. Source/runtime registration, native PackedLayout, Fixed 3x5 prompt planning, JavaScript UI harnesses, Prompt/CLIP cache equality, Video Guide bit-exact A/B, V3.5 Second Pass/Hi-Res, and V3.5.3 distribution-integrity checks remain covered.
The current V3.8 public-surface suite verifies the exact seven-ID export, the single supplied Spectrum graph and its identical ZIP payload, declared external dependencies, Registry exclusions, preserved legacy V3.8 widget/socket order with the AUDIO-R1 socket appended, and presentation-only `Show Advanced Settings` / `Hide Advanced Settings` behavior, including migration of the former `H3 Continuum View` property. Registry payload hashes are recorded in `REGISTRY_MANIFEST.sha256`; source-only files are also covered by `MANIFEST.sha256`. Git preserves exact bytes to avoid platform-dependent hash changes. Historical implementation paths remain covered by module-local regression tests without exporting additional V3.8 nodes.
**CPU launch audit — 2026-09-07, before the final distribution rename:** the full guarded suite passed **1,154/1,154 tests**, with no failures, errors, skips, or recorded CUDA initialization requests. Isolated ComfyUI Core 0.34.5 CPU checks passed seven-node registration and native PackedLayout; both the former Core-only template and the supplied Spectrum graph passed graph/schema checks. CUDA remained uninitialized. The final distribution uses the unchanged Spectrum graph under the generic V38 filename. These are CPU/software-contract results, not a new GPU-quality acceptance or proof that a running installed backend has loaded the latest source.
**Historical V3.6 acceptance:** the V3.6 release gate included PIG-0 through PIG-5 Production Integration acceptance: backend-scoped Run Storage, real-cache Save/Resume/Regenerate From, atomic Terminal Merge reuse, Reference Image/Audio retention, bit-exact protected prefixes, GPU workflow output, numeric Audio Seam analysis, and subjective Audio PASS. Its automated validation result was `527 passed`; this is a historical count, not the current V3.8 CPU total. The package checklist and historical acceptance records are in `PACKAGE_VALIDATION.txt`. Regression coverage also includes source/runtime registration, native PackedLayout, Fixed 3x5 prompt planning, JavaScript UI harnesses, Prompt/CLIP cache equality, Video Guide bit-exact A/B, V3.5 Second Pass/Hi-Res, and V3.5.3 distribution-integrity checks.
V3.4 compatibility paths have been exercised locally with:
@@ -735,6 +1251,8 @@ No OOM was observed in the cited recent local V3.4 checks, including two-chunk 8
## Limits
- Second Pass / `refine_context` is not supported while a Review sequence is partial. Finish Review before starting Second Pass.
- The 16GB GPU Gate passed with small VRAM headroom; memory use depends on the complete environment and workflow.
- Continuation does not guarantee frame-perfect identity or motion.
- Video Guide Frames guides H3; it does not reproduce every source frame.
- Driving Audio preserves selected audio, but visual lip synchronization remains model-dependent.
+167 -17
View File
@@ -1,8 +1,150 @@
# ComfyUI-H3-Continuum 3.7.0
# ComfyUI-H3-Continuum 3.8.0
MiniMax H3を複数チャンクで連続生成し、直前チャンク末尾の**映像latent / 音声latentを直接**次チャンクへ継承するComfyUIカスタムノードです。チャンク間でVideo/Audio VAEのDecode→Encodeは行いません。
## V3.7 高解像度Refinement基盤
## インストール・更新
新規導入:
```bash
cd ComfyUI/custom_nodes
git clone https://github.com/ukr8b3g-cmyk/ComfyUI-H3-Continuum.git
```
既存のGit導入を更新:
```bash
cd ComfyUI/custom_nodes/ComfyUI-H3-Continuum
git pull --ff-only origin main
```
ComfyUIを再起動してください。Managerから導入した場合はManagerのUpdateを使い、同じノードを重複配置しないでください。
V3.8 Workflow:[JSON](examples/workflows/MiniMax_H3_Continuum_V38.json)/[同じJSONを含むZIP](examples/workflows/MiniMax_H3_Continuum_V38.zip)。Spectrumを初期設定とする1本です。[LightX2V Turbo](https://github.com/ModelTC/Minimax-H3-Turbo)にも切り替えられますが、完全なgraphを開くにはSpectrum・rgthree・KJNodes・ComfyUI-Easy-Useが必要です。外部ノードは別途導入してください。
## V3.8の公開範囲
H3 Continuumは、長尺映像を最初からやり直さずに生成・確認・部分再生成・再開するProduction Samplerです。V3.8は`Main / Production`と`Advanced`の2層に整理しました。
V3.8で検索可能な公開ノードは次の7つです。
- `H3 Continuum Sampler V3.8`
- `H3 Continuum Finalize`
- `H3 Continuum Load Image`
- `H3 Continuum Load Audio`
- `H3 Continuum Load Video`
- `H3 Continuum Second Pass`
- `H3 Continuum Reference Audios`
Main Sampler内の`Show Advanced Settings`/`Hide Advanced Settings`で詳細設定を開閉します。旧node property `H3 Continuum View`を含む保存Workflowは対応する開閉状態へ移行し、旧propertyを削除します。これは表示状態だけの変更です。Python input、widget順、保存済みwidget値、backend引数、Sampling identity、Run Storage identityは変更しません。Frontend extensionが読み込まれない場合も、Python定義の全widgetが表示された状態で実行できます。
標準経路は`Sampler V3.8 -> Core Video/Audio Decode -> Finalize -> Create Video -> Save Video`です。Finalizeの`IMAGE`/`AUDIO`出力をCoreの`Create Video`で`VIDEO`へまとめてから保存します。Core Decode、Save、Upscalerは外付けとし、外部latent processorやupscalerはSecond Passをbridgeとして接続します。外部processorが変更できるのはVideo LATENTの空間解像度だけで、physical group、B/C/T、finite値、First Pass Audio、元のAssembly Planを維持する必要があります。Finalizeは公開`IMAGE`/`AUDIO`型を受け取り、特定decoder classへ依存しません。SageAttention、Sol-Attn、Spectrumは外部MODEL wrapperのままです。詳細は[V3.8 Open Integration Contract](docs/V38_OPEN_INTEGRATION_CONTRACT.md)を参照してください。旧Hi-Res FixはV3.8標準Workflowに含めません。
### Reference Audio 1/2/3
`H3 Continuum Reference Audios`は、最大3本の単独Reference Audioを1本の`Audio References (Optional)` socketへまとめます。入力は間を空けずに接続し、Promptでは接続順どおりに`<Audio 1>`、`<Audio 2>`、`<Audio 3>`を使用します。共通のCore Audio VAEで各Audioを個別encodeします。生成後の最終Audioを置換せず、Driving Audio契約も変更しません。既存Workflowは従来の単数`Reference Audio (Optional)`をそのまま使用できますが、単数経路とbundle経路は同時接続しないでください。
> **V3.8 support boundary:** V3.8からexportするのは上記7ノードだけです。Finalizeの`H3ContinuumAssembleSeamV35`、Second Passの`H3ContinuumSecondPassV35`など、公開ノードの一部は旧IDを維持していますが、すべての旧Workflowに互換性があるという意味ではありません。現在の7ノード以外のIDを含む保存Workflowはunknown nodeになる場合があります。その場合は対応するhistorical Release/tagを使用してください。詳細は[V3.8 Release/Migration Policy](docs/V38_RELEASE_AND_MIGRATION.md)を参照してください。
複雑な16GB GPU受入Gateでは約`15.5~15.6 GiB`を使用しました。GPU、driver、backend、model精度、解像度、接続ノードで変動するため、すべての16GB GPUでの動作保証ではありません。
### サイズの決め方を直接選択
| Preset | 目安 |
|---|---|
| `Draft` | 約0.30 MP |
| `Balanced` | 約0.60 MP |
| `Native 768` | 短辺768を目標。極端なAspectでは長辺1344 capを優先 |
| `Custom MP` | Megapixelを直接指定。Native 768のcapとは別 |
Mainの`Size Source`は次の2択です。
- `First Image`:接続したFirst Imageの縦横比を維持し、Presetの目標面積から最終Width/Heightを算出します。
- `Manual`:Width/Heightを32 pixel単位で直接指定します。この場合、Presetは適用しません。
MainのWidth/Heightは`Manual`のときだけ表示・編集できます。`First Image`ではResolutionを表示し、画像の縦横比からサイズを決めます。有効なFirst ImageがSamplerへ届かない場合は、保持しているManual Width/Heightへフォールバックし、その寸法をStatusへ表示します。手動寸法を確認・変更する場合は`Size Source = Manual`を選びます。Reference ImageやVideo Guideからサイズを暗黙取得することはありません。
旧V3.8の`Auto / Landscape / Portrait / Square`はWorkflow/API互換用として内部で受け付けます。FrontendはAutoをFirst Imageへ、3つの固定Aspectを同じ解決結果のManual Width/Heightへ移行します。
### 10秒を5秒ずつ確認しながら作る
ここでは、画面に表示される名前だけを使って手順を説明します。
#### 最初に知っておくこと
`Chunks = 2`、`Seconds per Chunk = 5`は、完成目標が合計10秒という意味です。ただし、`Run = Review Each Chunk`では10秒を一度に生成しません。最初のQueueでは、確認用に**Chunk 1の5秒だけ**を生成します。これは正常動作です。
Chunk 1を確認した後に操作を選び、もう一度QueueするとChunk 2へ進みます。`Chunks = 1`では最初の5秒が最後なので、次へ進む操作はありません。
#### 手順1:生成前の設定
`H3 Continuum Sampler V3.8`で、上から次の順に設定します。
1. `Control After Generate`を`fixed`にします。`randomize`、`increment`、`decrement`では続きを再利用できません。
2. `Chunks`を`2`にします。
3. `Seconds per Chunk`を`5`にします。
4. `Total Length`が`10 seconds`になったことを確認します。`Total Length`は確認表示で、直接変更する項目ではありません。
5. `Run`を`Review Each Chunk`にします。
6. `Progress`を`On — Resume and Takes available`にします。
7. 緑色の`Ready to Queue`欄に、`2 × 5s = 10 seconds`と`Review each chunk`が表示されていることを確認します。`Set Control After Generate to fixed`と表示された場合は、Queueする前に手順1を直します。
#### 手順2:最初の5秒を作る
1. ComfyUIの`Queue`を押します。
2. Chunk 1だけが生成されます。出力動画が5秒でも正常です。
3. Queueの処理が完了すると、Samplerの表示が自動的に`Chunk 1 is ready for review`へ切り替わります。
#### 手順3:Chunk 1の動画を確認する
保存された5秒の動画を再生し、そのまま採用するか、作り直すかを決めます。この時点ではまだ合計10秒の動画は完成していません。
#### 手順4:次の操作を1つ選ぶ
| 画面上のボタン | 次のQueueで行うこと |
|---|---|
| `Use it and continue` | 現在の5秒を採用し、次のChunkを1つ生成します。 |
| `Try this chunk again` | 現在のChunkだけを別のTakeとして作り直します。 |
| `Use it and finish the rest` | 現在までを採用し、残りのChunkをまとめて生成します。 |
ボタンを選んだだけでは生成は始まりません。選択したボタンに`✓`が付いたことを確認してから、ComfyUIの`Queue`を押します。
`Try this chunk again`はContinuum側で別Takeを作るため、作り直しでも`Control After Generate`は`fixed`のままにしてください。
#### 手順5:2本目の5秒を作り、10秒を完成させる
1. `Use it and continue`を選びます。
2. ComfyUIの`Queue`をもう一度押します。
3. 採用済みのChunk 1を再利用し、Chunk 2を生成します。
4. Samplerから後ろのDecode、`H3 Continuum Finalize`、Save Videoまで通常どおり実行されると、合計10秒の完成動画が出力されます。
設定を確認し直したい場合は`Back to Settings`を押します。未処理のReviewへ戻る場合は`Return to Review`を押します。どちらも生成を自動開始せず、選択済みのTakeや保存済みChunkも削除しません。
#### 迷ったときの確認
- 最初のQueueで5秒だけ出た:`Review Each Chunk`の正常動作です。
- 次へ進むボタンが出ない:Queueが完了しており、`Progress = On — Resume and Takes available`、`Chunks = 2`以上であることを確認してください。正常なら完了後に自動表示されます。
- ボタンを押しても生成されない:操作を選んだ後、ComfyUIの`Queue`をもう一度押してください。
- `Set Control After Generate to fixed`と表示された:`Control After Generate`を`fixed`にしてください。別SeedのChunk 1が増えることを防ぐ安全チェックです。
- 1回で10秒すべて作りたい:`Run`を`Generate Full Video`にします。
Long Terminal Mergeのpairは分割せず、1つのReview単位として扱います。
Driving AudioはReview/Smart Regenerateと併用できます。Continuum Image/Audio/Video Loaderは任意入力向けのnative bypassに対応します。
> **Reviewの制限:** Review途中のpartial sequenceでは、Second Pass/`refine_context`を正式対応範囲に含めません。Reviewを完了してsequenceを確定してからSecond Passを実行してください。
### Take・Branch・安全な継続
Run Storageを有効にすると、Production表示に**Render History / Takes**が表示されます。
Takeを選択してもcanonical結果は変わりません。**Use This Take**でそのrevisionを
canonicalにし、**Continue From Here**で選択したTakeまでを保持して後続groupだけを
再生成します。どちらの操作も自動Queueは行いません。
## 歴史的な実装・受入記録(V3.8標準Workflowではありません)
以下の節は旧リリースと互換性作業の記録です。上記のV3.8標準経路を変更するものではありません。
### V3.7 高解像度Refinement基盤
V3.7では`H3 Continuum Sampler V3.7`を追加し、解像度を変更するSecond Passに必要な2つの基盤を完成させました。V3.6のProduction初期値と既存SIGMAS socketは変更していません。
@@ -18,7 +160,7 @@ Conditioning Adapterは、First/Last Image、Continuation context、Still Imag
V3.7では、Still Image Guide 1枚をabsolute frameからowner physical groupへ割り当て、高解像度Second Passでも元画像から再encodeできます。位置変換、Terminal Merge ownership、Run Storage identity、non-owner groupの非干渉はCorrectness PASSです。一方、Core Add Guideはhard anchorとして働くため、anchor位置で急なtrajectory変化が起き、その後のmotionも別の軌道へ分岐する場合があります。**Still Image GuideはExperimentalで、Production昇格はHOLDです。** 滑らかなtransition制御としては扱わないでください。
## V3.6.1 Maintenance Hotfix
### V3.6.1 Maintenance Hotfix
V3.6.1は、受入済みBalanced 22 Masked AV経路を変更せず、限定的なfail-open/互換性問題を修正します。Timeline/List記法が混在したPromptは`H3C-P105`を表示し、Timeline解析ではstandalone `---`行だけを除去します。未指定Chunkの既存fallbackとFixed Promptのfail-open動作は維持し、Prompt構文だけを理由に生成を停止しません。
@@ -26,7 +168,7 @@ V3.6.1は、受入済みBalanced 22 Masked AV経路を変更せず、限定的
Run Storageは、Last Frame未接続を表す値をすべて同じ空identityとして扱います。通常のLast Frameなし2チャンク生成を3チャンクへ延長すると、旧最終Chunkが`none`だったV3.6.1 cacheを含めて`2 reused, 1 generated`になります。実Last Frame接続時とLong Terminal Mergeのatomic pairは従来どおり厳密です。Run StorageをOffへ変更した場合は、Queue前にhiddenのRegenerate FromとVariation Nonceも`Auto`と`0`へ戻します。
## V3.6 Masked AV Continuation
### V3.6 Masked AV Continuation
V3.6では`H3 Continuum Sampler V3.6`を追加しました。標準backendは、前Chunkで確定したVideo/Audio latent prefixを次のH3 Target内へ直接配置し、CoreのNoise Maskで保持します。V3.5のReference Context方式のように、同じ過去フレームを別Reference blockとして追加しないため、H3が処理するpacked sequenceを短縮できます。
@@ -80,7 +222,7 @@ Prompt/CLIPの数値はconditioning区間だけで、総生成時間ではあり
RTX 5060 Ti 16 GB/RAM 64 GBの検証環境で測定したSage-only Production baselineは、576×576 T2VA 1×5秒が168.069秒、640×640 FL2VA Long Terminal Merge 3×5秒が379.765秒です。環境・設定固有の測定値であり、すべての環境に対する速度保証ではありません。Samplingが最大コストで、Continuum Assemble + Seamは1%未満でした。
**V3.7.0が現在の公開版です。** V3.6.1はmaintenance/compatibility baselineとして維持します。旧Node ID、backend socket key、保存済みWorkflow読込は維持し、Production初期値は変更していません。Still Image GuideはExperimentalです。
**V3.8.0が現在のRelease Candidateです。** V3.8が内部利用する旧module/classはsourceへ維持します。exportするのは現在の公開7ノードだけで、その一部は旧IDを維持しています。それ以外のIDを必要とする旧保存Workflowは、対応するhistorical Release/tagを使用してください。Still Image Guideは引き続きExperimentalです。
## V3.5.1 Reference Audio/互換性更新
@@ -199,21 +341,20 @@ Hi-Res Fixを接続しなければV3.4 Sampling経路は変わりません。強
詳しいsocket接続・OFF時のpassthrough・既知の制限は[英語版V3.5接続ガイド](docs/V35_HIRES_FIX.md)を参照してください。
## 推奨テンプレートワークフロー
## 公開テンプレートワークフロー
- [V3.6推奨テンプレート](examples/workflows/MiniMax_H3_Continuum_V36.json)
- [V3.5互換テンプレート](examples/workflows/MiniMax_H3_Continuum_V35.json)
- [V3.5.1 LBH+Conditioning Bridge接続例](examples/workflows/MiniMax_H3_Continuum_V351_LBH_Conditioning_Bridge.json)
- [V3.8 Workflow JSON](examples/workflows/MiniMax_H3_Continuum_V38.json) — Spectrum初期設定の現行graph 1本
- [V3.8 Workflow ZIP](examples/workflows/MiniMax_H3_Continuum_V38.zip) — 同じJSONのみを格納。カスタムノードのインストーラーではありません
V3.6テンプレートはContinuation BackendがStandard、Hi-Res Fixが初期OFF、AssembleのBuffer BackendがAutoです。First Frame、Last Frame、Reference Image 1~3は1つのmegapixel設定を共有します。`Video Guide Size`は`Video Guide Frames`に使うframe batchを調整し、decodeとframe-rate変換はVideo loader側で行います。現在のProduction構成はV3.6 SamplerとV3.5の低メモリAssembleを組み合わせます。V3.5テンプレートは互換用として変更せず維持します。
Registry配布予定の対象もこのJSONとZIPです。依存なしのテンプレートではなく、Spectrum・rgthree・KJNodes・ComfyUI-Easy-Useが必要です。Turboへ切り替えてもgraph内の外部ノードは残ります。SpectrumをOFFにし、用途に合うLightX2V Turbo LoRAを1本だけONにしてsampler/Stepsを合わせます。初期状態はSpectrum ON、Turbo LoRA OFF、res_multistep/simple/20 Stepsです。
![H3 Continuum Sampler V3.6](docs/images/v36-sampler-node.png)
配布元のprompt、画像・音声名、ノード表示名、設定は変更していません。手元にあるファイルを選び、不要な入力をOFFにし、promptを入力してください。モデルやメディアは同梱しません。`Save 3x5s Video`などの保存済み表示名は生成時間を決めません。実際の長さはSamplerのChunksとSeconds per Chunkで決まります。
![H3 Continuum Assemble + Seam V3.5](docs/images/v35-assemble-seam-node.png)
旧Workflowは開発履歴としてsource repositoryへ保持しますが、V3.8 Registry packageからは除外します。旧保存Workflowは[Migration Policy](docs/V38_RELEASE_AND_MIGRATION.md)に従い、対応するhistorical Release/tagで開いてください。Registryの正式pack検証・公開はGitHub sourceの更新とは別工程です。
## V3.4互換
V3.4ノードは保存済みワークフローを壊さないため残しています。Node ID、公開socket、Sampling、Conditioning、Terminal Merge、Assembly、Seam、Run StorageをV3.5へ置換していません。Second PassやDisk-backed Assembleを必要としない場合は、従来どおりV3.4を使用できます。
V3.4の実装moduleは内部継承とhistorical testのためsourceへ保持しています。V3.8からexportするのは現在の公開7ノードに含まれるIDだけです。それ以外のIDを必要とするV3.4保存Workflowは、対応するhistorical packageを使用してください。
## V3.4.0 Stable
@@ -246,7 +387,10 @@ Reference入力のバイパスされたソケットは無視され、有効な
1. Run Name、Base Seed、model、LoRA、解像度、sampler、SIGMAS/steps、Reference、Continuity設定を初回と同じに保ちます。
2. `Regenerate From`を`Chunk 2`にします。
3. Workflowをもう一度Queueします。
3. `Variation Nonce = 0`なら、完了済みの再生成に対して新しいバリエーションを自動選択します。互換性のある未完了runを再開する場合は、既存のバリエーションを引き継ぎます。`1以上`は指定値を固定するため、同じ入力で別の結果を求める場合は別の正の値へ変更します。Base Seedは固定のままにします。
4. Workflowをもう一度Queueします。
Review画面の`Try this chunk again`は、この手動指定とは別に、内部のバリエーションを自動で進めます。
Continuumは保存済みChunk 1を再Samplingせずに読み込み、その確定済み末尾をContinuation contextとして新しいChunk 2をSamplingします。Reportの目安は`1 reused, 1 generated`です。その後、10秒全体を再Decode/Assemblyします。第1ChunkのSampling結果は再利用され、境界のSeam処理は新しいAssembly時に再評価されます。
@@ -297,7 +441,7 @@ outputs: images / audio / result
### Legacy互換
旧`H3ContinuumSamplerV2`は削除せずLegacy/Coreノードとして登録を維持します。既存WorkflowのノードID、入力順、出力順は変更していません。
当時のV2.1.7では、旧`H3ContinuumSamplerV2`をLegacy/Coreノードとして登録し、既存WorkflowのノードID、入力順、出力順を維持していました。これはV3.8の公開範囲を示す説明ではありません。このIDを使う旧Workflowは対応するhistorical Release/tagで開いてください。
## Continuity
@@ -322,15 +466,21 @@ UNET -> SageAttention -> Sol-Attn -> LoRA -> Spectrum -> H3 Continuum Sampler
## インストール
ComfyUI 0.32.0以上が必要です。ComfyUI 0.33.3でパッケージ検証、0.34.0でV3.6.1 GPU Smoke、0.34.2でV3.7 Conditioning/RefineSchedule Correctness Gateを検証済みです。ComfyUIの最新版は必須ではありません。
V3.8はComfyUI 0.34.2で検証しています。以下の歴史的な受入記録には旧ComfyUI版も登場しますが、現在のインストール目標ではありません。V3.8の依存を満たす限り、ComfyUIの最新版は必須ではありません。
ZIPを展開して、`ComfyUI-H3-Continuum`フォルダーを`ComfyUI/custom_nodes/`へ置き、ComfyUIを再起動します。
再起動後は`H3 Continuum Sampler V3.8`を検索してください。V3.8の検索面は上記7ノードだけです。
旧`ComfyUI-H3-Continuum-Join`が残っている場合は同時ロードを避けるため削除または退避してください。同梱`install_windows.bat`は旧名・新名の既存フォルダーを日時付きでバックアップします。
## 検査
V3.6 release gateはPIG-0~PIG-5を完了し、backend別Run Storage、実cache Save/Resume/Regenerate From、Terminal Mergeのatomic再利用、Reference Image/Audio保持、保護prefix bit-exact、GPU Workflow、Audio Seam数値検証、実聴Audio PASSを含みます。最終自動検証は`527 passed`で、完全なpackage checklistは`PACKAGE_VALIDATION.txt`へ記録しています。source/runtime登録、PackedLayout、Fixed 3×5 Prompt Plan、JavaScript UI harness、Prompt/CLIP cache一致、Video Guide bit-exact A/B、V3.5 Second Pass/Hi-Res、V3.5.3配布整合性の回帰も維持します。
現在のV3.8 Public Surface suiteは、正確な7 ID export、Spectrum graph 1本とZIP内JSONの同一性、外部依存、Registry除外、既存V3.8 widget/socket順を維持したAUDIO-R1 socket末尾追加、`Show Advanced Settings`/`Hide Advanced Settings`による表示切替と旧`H3 Continuum View` propertyからの移行を確認します。Registry配布対象のハッシュは`REGISTRY_MANIFEST.sha256`、source側の対象ファイルは`MANIFEST.sha256`で管理します。Gitの改行変換は無効にして配布バイト列を維持します。旧実装はmodule-local testで維持しますが、それによってV3.8の公開ノードが増えることはありません。
**配布名の最終整理前のCPU総検証(2026-09-07):1,154/1,154 PASS。** failure、error、skip、記録されたCUDA初期化要求はいずれも0件でした。ComfyUI Core 0.34.5の隔離CPU検査で7ノード登録とnative PackedLayoutを確認し、旧Core-onlyテンプレートと提供されたSpectrum graphのgraph/schemaも確認しました。CUDAは未初期化のままです。最終配布ではSpectrum graphを変更せず汎用のV38ファイル名に統一します。これはCPU上のソフトウェア契約の検証であり、新たなGPU画質PASSや、起動中の実行環境へ最新版が反映されたことを示すものではありません。
**過去のV3.6受入記録:** PIG-0~PIG-5を完了し、backend別Run Storage、実cache Save/Resume/Regenerate From、Terminal Mergeのatomic再利用、Reference Image/Audio保持、保護prefix bit-exact、GPU Workflow、Audio Seam数値検証、実聴Audio PASSを含みます。当時の自動検証は`527 passed`であり、現在のV3.8 CPUテスト件数ではありません。package checklistと過去の受入記録は`PACKAGE_VALIDATION.txt`にあります。source/runtime登録、PackedLayout、Fixed 3×5 Prompt Plan、JavaScript UI harness、Prompt/CLIP cache一致、Video Guide bit-exact A/B、V3.5 Second Pass/Hi-Res、V3.5.3配布整合性の回帰も維持します。
Main Hi-Res Fixの3×5秒2xは、RTX 5060 Ti 16 GiBで37T groupの1152×1152 Second Pass完了後、Terminal Mergeの77T group最初の推論時にCUDA OOMとなり未受入です。Reference/Hybrid固有の1×5秒Second Passは受入済みですが、長尺Reference/Hybridは未確認です。Disk-backedが保証する低メモリ範囲はContinuum Assemblyであり、Core Decodeや下流ノードが別の全量copyを作る可能性は残ります。
+105
View File
@@ -0,0 +1,105 @@
dca65fb1393e67f59c6f81f9411e3e745eb8f1097e9a2adf7ffc6f4e3901ca9f __init__.py
be0b8d39e5343680ebea815c3a4fb6ce7a32e065f30e43e013040a40f702cef3 .comfyignore
3e7a1ec3380be2a222c8a3e9b8a6bb184d3a760478957f48186438f15235bdba branch_provenance.py
2a1340ac613def60f0a2c1c7e382c87486b49b14ebc3c6ef34ae14af633295d2 CHANGELOG.md
c1ed3a0342730450958fb62fd21854a876991f3a4aefb24e5383b0c73cd2312d compatibility.py
4d62508f900af9f93ec320afb900c27cc9a300d1e0c0a94714258498c5ede5fc conditioning.py
64967f4987e3ad9316f3a47f0dcf582eeff39ee0c3485f4184d3532d495534ae constants.py
cf255b8a635471229aebadc926acfdcacb65963adbcb9e0f9505d04eada2c6b5 continuation.py
b30fe4640359bebfcdeeb94dbeec94cb346c8e3646509e1dcdb87d7021ba04ff docs/N2B_BRANCH_PROVENANCE_CONTRACT_V1.md
717577efdec5e61600504b77bc2a099ef022c4fe2333e936c3310c7182d8f2a0 docs/V38_OPEN_INTEGRATION_CONTRACT.md
1d2838cc47694609289ea15132872ad48e1b6c8274da4b7bf188dd3ebf066121 docs/V38_RELEASE_AND_MIGRATION.md
cedd7b07901d6065079ef37380f0062d535a39c98c8f614e1b26582f549d7183 driving_audio.py
e490c87e4995930f95c8fffc4c678111d7897e74003e1962b9b4a247ba43f4ac examples/workflows/MiniMax_H3_Continuum_V38.json
8c109973e5b49cf52b32e0ebb2b5ae6a4e349191e66c2696ff43ce76fefeb07c graph_contract.py
bf0556b076dbaca67c3405a7d86c333ca7fdf3d4381529b0a9edc906519943e9 guide_timeline.py
1473c384082700f422f2cf9141e0d012d87d2b43ac8a8a433edc7172e6ca7bf6 hardening.py
7c8b1226592dcd9d0ec6cc1579956e380fedc9b2672386c29db82169a6cf5f10 INSTALL_JA.txt
23bddc5a41d2e997f4fbf789c7128e32f4f197f1405b2aef1c76794f57482446 install_windows.bat
fcf80acf6479ece00066eeb59f75d5246cb7b17b75ba84938b73ae17a5083903 install_windows.ps1
6aa3f5780baa7bb0c0672b5f01a2f77e5f209da93f6373468cb274ea2f643d4b layout_adapter.py
c44abbd789091bbead01250dbd5453e60539d2665c69f162335fdbd2936019c2 LICENSE
d3e213005670e94dee33a240349a4d245cf9a3b6602099f11ed30cf5a32e2c21 media.py
8b360a1c47a8ee5a95656ffbc83bfc16de69678ecec2c1d8cace46b5ea4e911e metadata.ini
2d611f7201889851eac6459f8aa2b37baf342b345241979ca6042b61b252dff9 model_patch.py
a4ce23167b83e8d72b86a802dfde4f4045828433c7c13aab799bd64831dc04a4 nodes.py
57dcb61cc3e83b2ca97616919ac6ee17d4c62caf845c38161573f56dad12f8fe PACKAGE_INFO_JA.txt
000a56a942b13d11973994ab32cd2a1abc424a3fe1d95a323240077bd8092bdf PACKAGE_VALIDATION.txt
b470819f16fc179654dc1600721a63f0a5a14e777f4c004d574b499da6886ba5 public_api.py
96f98d727b72d6aefd431061572e187c303365a3e5b4d20cbb2bcf030aa30112 pyproject.toml
88aa955161d04d14ebd8d90d6cb6c6206097160a671eb4d1bfe9b3e76ebc6c13 README_JA.md
bd71498ddb59edc250ca623ee7cc6fb0c3a728025c879cda81390d435e5c6eac README.md
44127adcfa30ee84bff9cd4b2d0c695355209550e76982d374122008728aa5bc reference_audio.py
5cb9bfd6810d3a93a637451980a4cc5c1436e5b84cfd1c7a111cd192e876351b reference_video.py
131bdfbb7a7173c9e7826859c0e648bfb69bd18bf20fa5528c0e18a63f888b26 reference.py
467edb2c188d024c2392aafe7423b3f835e16b10f570da76e2f7dda8a962c1c5 requirements.txt
a65d657466491aba8b2d1004e87071cee2819869813e646789df736a3ccf479e run_storage.py
6056de6c0a5322a8a51ba5a114538dca2ef67788cd1afba10fedd483b95f6afa state_io.py
3a359a0467725cc292ccb4c86cf0c3d30bb6a114d01f5345792b09ea3d45441d state.py
43ec4023dc06c941e5d7a04db4b8a89fb58d744ceb986f6eb9bf534d4fdcb87b temporal.py
0dbe8a5f71c92f3523942343b40787104c8b96781461ba3ba82934a6bdbe5834 THIRD_PARTY_NOTICES.md
f218e1a93c42467c6057c5c1d04d57cc82f6331b97ec9257e4e2dfb9c831876a timeline_video.py
0bc369ee428b8a5bc8e370a81fbab427262a1fdb7805a78c442c91698d65efba tools/__init__.py
e5a84569953ee63b9625f4f2e3195ec368204fddcfc746564cfbd0e8449bb8e9 tools/p20_file_backed_tensor_poc.py
556bce17d14303d1e8a36a85dc13da24c46eedd86f3eacdb102289574faf0626 tools/verify_runtime.py
ffd61f3f31c9b6430e1169007ee906c8f5000eba63ee44e2976ad4f5f1112671 v2/__init__.py
2003902c87bba09cfa143f5a9e4248f3a78c0fb544449a75fd40ba2cacb35655 v2/context_diagnostics.py
cde27db19b677e318cc4dfb4235be7a11429c19945f4083052a91fe117e74c82 v2/decoder.py
31012ec48a64c7467ad869c79982b7f8502c1785c33f51ee1b5727ce8b4243fb v2/diagnostics.py
2ebff4502381f675d06bba4b127b81bc3201e7579ddcd46fa5051cbdf3facd55 v2/h3_builder.py
aea01a48a8c03a25ed97ea05e5b137f89e388832d1be7d38f2da2be3d1b9830b v2/motion.py
aefa29b9d51a05f9a972d75404fd786300202251887e67f55530e97ccd9519f5 v2/nodes.py
dc2b901789e4b024dbcbc4024c63eb8cbc564d77003ce8c35c0584851ba6dfbd v2/prompts.py
4080f1875b958b316e8e76852c4be5527a6de5c71d604e7642d3098478eb4a36 v2/sampling.py
2fd811794c4cc0f2ce050250b80484876454926b9f20fce6af3a97d728e5acdf v2/seam_guard.py
be0d8585fa57e0ccd6d02577bbc7299629e5bfe20e186747f571fccc98b67d7e v2/seam_types.py
12cfcc0c71ca087fe39a5ce2922959a62b2bb311bfe664f05c4480affce03708 v2/seeds.py
3a98f8a21756f3813f52197946e761227507b14c40703c9fb1bb108c1e4ddbe7 v2/sequence.py
13213e7709fd02bb810af3c18e4cd7d010f8cdfb121a4b99866a9f2333331089 v2/session_io.py
3ea23dbce6fcd217b6e81235855479b9b16fed7a21693cf156f9014555c4fe13 v2/session.py
78c830cdf49034c6e3b2cd3da5914d5cfc5638eb63ec6dbd1bab13c50d6d4caf v3/__init__.py
ea2922567df90436dd6fa21696833a49dd0cbfeee142a5fedc3a7c303824d473 v3/adaptive_continuity.py
b3dc61503d35d9ef0a0dc7fed1c9b2fdc00fcb2072d4e39f64ae0826f9ec7dca v3/assembly_v35.py
7815230e0a9540bc2edeaf818e940b7a1fdd817fd217ba8a4f9cb21aaf6a308e v3/assembly.py
3f62fdb35e804f42d7cbf0828b4e87e69a2b99246c3f7467fe4fa698f1d803c9 v3/conditioning_bridge_nodes.py
92b92c51b87182d420ce0468f57797fbb6fe4123d04080b73d6d89581ff96c31 v3/driving_nodes.py
2f395da6a41981713f99ba40b73d14f2274b8ca34a73cf2b275a444993765b99 v3/easy_audio_nodes.py
64b3e54b42e5156642f9957ccc374fd190d9fc7145637984e702534fb1bf80b4 v3/easy_image_nodes.py
ac859cb1a6e23b8ceae300d818c24fe1346b649a0d663017a9b3ac64aa96fca3 v3/easy_nodes.py
bf6bae0c9e14883728860470af86e14395dba40a7377cd874d4dc4548ae53c65 v3/easy_video_nodes.py
6cc7ed74666084c55beb9075304e92a9defafd81b9c6678239ca3859a08cddd7 v3/file_backed_buffer.py
cb53e1b104415032ec79b7e7aa1c99848e63da3eedaa251eeba102970e4172b5 v3/hires_fix_nodes.py
0858487e2b8c0060a856273ffc65d23165b2f253d183f506e27e419aea0da561 v3/latent_resize_nodes.py
5b8a54e67a608e757a505abc712effb33312636e3bb235835a485a506e80eeee v3/masked_continuation.py
91a868d2e392b018b01d0396209849c146b0d560ceb109fcdd87dea7f3d786aa v3/memory_action_policy.py
85477badd85281cfb77582fdd5b34228a9f6b68376f1b7743af2ca7d4b55aa36 v3/memory_attribution.py
b528e34e24407896e3728d693a40393b46ec7bce236d455721712dfe2fe75adb v3/nodes.py
a3411c7a295308d21623551cf4aeca5bef511eb5f063f31ac84032e3bdf4e16d v3/packed_row_planner.py
b7c4a35a5e73f528492bc6946b97b687c412f1d3f5f976c19d45c6dc20288c9a v3/pixel_vae_resize.py
34ea38c03b6322288d88fc8595e3655a7a7afddb51709142a954eb7349f71ac2 v3/plan.py
ec71e3965f445756d54d005c0e27bea520e26dbac44e1ee3d3867bfe2da100b0 v3/ref_encode_cache.py
9076c47aa5145c81f34793d6c90410656065248f37d9990a92a6a4061b358811 v3/refine_context.py
519586b1b3f48c73d329f7a2aaa8a1bfc6fe31ac2ecb64f2b1fdf9c19026001a v3/refine_sampling.py
43f33f989eb70ca87b916fc33267732a2be3dd4581fc72af17c53f840b53ca49 v3/refine_schedule.py
afc149dc347b4c1502ddf32ea4229e633799cd34d2b2c6f98bf8a47910a9ef77 v3/refine_scope.py
ac373d9783d3a7bb968e8117843d246d6a090b66a819015348bff84e7747442c v3/refine_target.py
45ae91f13e8f71405d2f46045c8acc6eabbc9500c194cf5d0ba541bb085cd135 v3/refine_window.py
ae909b43ad17934c85881d3b0bea81e7b45c215eeb4d1f9f6a9ea72faf633ddf v3/reliability_v38.py
520a4ae849f83450855ce0023c582db5f91d29d8694a99aa8cf491351c837cff v3/resolution.py
c21602eb983d497f0eb559197f4f1408b9b5ebb8dcd3aab65e746641f77bcfd4 v3/review_control.py
452022107cea233aa84d5366ec4943ac5aadbd5fcf786113f1d542a641eac8f7 v3/second_pass_nodes.py
71791b8032c9857b5fcdcaf1ce004a48c0e1c9e074a1de867ec0547e3ec5e313 v3/reference_video.py
66501234756c2b558ce84f887bd540e7f843ed574c8a8b2522950bd1985d7acc v3/second_pass.py
6e71e944313339f14e14e11cec682593159ca5542aa5d38095371da781d60224 v3/targeted_refine_sampling.py
5a044bdd70c546e4446e0c26af92aae88049ffa2e0e2d01b52033a83a3152d0e v3/targeted_second_pass.py
4178dcfa442abdb06ce276e05bd7bcbaa6da28469ba5e57d3da3c663de4e4a9d v3/video_seam_v35.py
2f07ace1462644f0bee553827b3571535de4d0c2d9ef847bd9e0ca73a4eed5cb v3/video_seam.py
d1957fa668a0332e483330bc79fc53095712420e401035a4f80cf6b532677d51 version.py
c2883272b05a9a9146b5c6cf614ddae8a3e6893cd910902023aae61360195289 web/easy_bypass_toggle.js
092088096307d33ac016b82b4774ca38845a2ff2f63b97ac6da8c5aca4fea413 web/easy_load_audio.js
9db0aa94f634578a962d5db49e5c70356040a59df968e3a2e531b327a623081f web/easy_load_image.js
873efcbd15c2d9fa10c9d5fc51a796ad3a18c0c6acceecf499c4b956aa845c6c web/easy_load_video.js
0c68d13a1f8beb7431a32b471f8b0612c42fcc4bf72dd97611a025d158008662 web/easy_v38.js
7b318be7e0a6ffa7a0b924f149ee90c10e4ebfb731da2bc40297bad0ecf63269 web/project_id.js
0cf8d49bcb71b30437dc893f6218dc4cfb1cd244b647e4fbc2861dea2271a33a web/reference_audio_ui.js
83d28cc0cd549066962dc21ceae05d2b189fe22391b556887eab2cc1800e1e80 examples/workflows/MiniMax_H3_Continuum_V38.zip
+1024
View File
File diff suppressed because it is too large Load Diff
+222
View File
@@ -0,0 +1,222 @@
"""Pure Branch Provenance Contract v1 helpers.
The contract describes immutable physical-group revisions independently from
the sampling contract that produced their tensors. A display label such as
``Take B`` is deliberately not persisted as identity.
"""
from __future__ import annotations
import hashlib
import json
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from typing import Any
BRANCH_PROVENANCE_VERSION = 1
TAKE_ACTION_AUTOMATIC = "Automatic"
TAKE_ACTION_USE = "Use This Take"
TAKE_ACTION_CONTINUE = "Continue From Here"
TAKE_ACTION_OPTIONS = (
TAKE_ACTION_AUTOMATIC,
TAKE_ACTION_USE,
TAKE_ACTION_CONTINUE,
)
class BranchProvenanceError(ValueError):
"""Raised when persisted branch ancestry is ambiguous or inconsistent."""
def _canonical(value: Any) -> str:
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
def _hash(value: Any) -> str:
return hashlib.sha256(_canonical(value).encode("utf-8")).hexdigest()
@dataclass(frozen=True)
class PhysicalGroup:
start: int
end: int
physical_group: int
def as_metadata(self) -> dict[str, int]:
return {
"start": self.start,
"end": self.end,
"physical_group": self.physical_group,
}
def physical_groups(*, chunks: int, terminal_merge_enabled: bool) -> tuple[PhysicalGroup, ...]:
if isinstance(chunks, bool) or not isinstance(chunks, int) or chunks < 1:
raise BranchProvenanceError("chunks must be a positive integer")
if type(terminal_merge_enabled) is not bool:
raise BranchProvenanceError("terminal_merge_enabled must be a boolean")
if terminal_merge_enabled and chunks < 2:
raise BranchProvenanceError("Terminal Merge requires at least two chunks")
terminal_start = chunks - 1 if terminal_merge_enabled else None
groups: list[PhysicalGroup] = []
chunk = 1
while chunk <= chunks:
if terminal_start is not None and chunk == terminal_start:
groups.append(PhysicalGroup(chunk, chunks, chunk))
break
groups.append(PhysicalGroup(chunk, chunk, chunk))
chunk += 1
return tuple(groups)
def _record_identity(record: Mapping[str, Any]) -> dict[str, Any]:
entry = record.get("entry") or {}
return {
"sequence_index": int(record.get("sequence_index", -1)),
"storage_revision_id": str(record.get("storage_revision_id", "")),
"filename": str(record.get("filename", "")),
"file_size": int(record.get("file_size", -1)),
"file_sha256": str(record.get("file_sha256", "")),
"seed": int(record.get("seed", entry.get("seed", -1))),
"prompt_hash": str(record.get("prompt_hash", entry.get("prompt_hash", ""))),
}
def make_group_revision(
*,
parent_revision_id: str | None,
group: PhysicalGroup,
variation_nonce: int,
created_utc: str,
storage_revision_id: str,
generation_contract_sha256: str,
lineage_sha256: str,
records: Iterable[Mapping[str, Any]],
branch_cut: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
if not isinstance(group, PhysicalGroup):
raise BranchProvenanceError("group must be a PhysicalGroup")
nonce = int(variation_nonce)
if nonce < 0 or nonce > 0xFFFFFFFF:
raise BranchProvenanceError("variation_nonce is outside uint32")
record_values = [_record_identity(record) for record in records]
expected_positions = list(range(group.start - 1, group.end))
if [record["sequence_index"] for record in record_values] != expected_positions:
raise BranchProvenanceError("physical group records are incomplete or non-atomic")
if not all(record["storage_revision_id"] for record in record_values):
raise BranchProvenanceError("physical group record source is missing")
seed_identity = _hash(
[
{
"sequence_index": record["sequence_index"],
"seed": record["seed"],
"prompt_hash": record["prompt_hash"],
}
for record in record_values
]
)
identity = {
"branch_provenance_version": BRANCH_PROVENANCE_VERSION,
"parent_revision_id": None if parent_revision_id is None else str(parent_revision_id),
"group": group.as_metadata(),
"variation_nonce": nonce,
"seed_identity": seed_identity,
"storage_revision_id": str(storage_revision_id),
"generation_contract_sha256": str(generation_contract_sha256),
"lineage_sha256": str(lineage_sha256),
"records": record_values,
}
revision_id = _hash(identity)[:24]
result = {
"revision_id": revision_id,
**identity,
"created_utc": str(created_utc),
"revision_order": f"{created_utc}|{revision_id}",
}
if branch_cut is not None:
result["branch_cut"] = {
"selected_revision_id": str(branch_cut.get("selected_revision_id", "")),
"after_physical_group": int(branch_cut.get("after_physical_group", 0)),
}
return result
def validate_group_revision(value: Mapping[str, Any]) -> dict[str, Any]:
if not isinstance(value, Mapping):
raise BranchProvenanceError("group revision must be an object")
if int(value.get("branch_provenance_version", -1)) != BRANCH_PROVENANCE_VERSION:
raise BranchProvenanceError("group revision provenance version is unsupported")
group_value = value.get("group")
if not isinstance(group_value, Mapping):
raise BranchProvenanceError("group revision physical group is missing")
group = PhysicalGroup(
start=int(group_value.get("start", 0)),
end=int(group_value.get("end", 0)),
physical_group=int(group_value.get("physical_group", 0)),
)
if group.start < 1 or group.end < group.start or group.physical_group != group.start:
raise BranchProvenanceError("group revision physical group is invalid")
rebuilt = make_group_revision(
parent_revision_id=value.get("parent_revision_id"),
group=group,
variation_nonce=int(value.get("variation_nonce", -1)),
created_utc=str(value.get("created_utc", "")),
storage_revision_id=str(value.get("storage_revision_id", "")),
generation_contract_sha256=str(value.get("generation_contract_sha256", "")),
lineage_sha256=str(value.get("lineage_sha256", "")),
records=value.get("records") or [],
branch_cut=value.get("branch_cut"),
)
if str(value.get("revision_id", "")) != rebuilt["revision_id"]:
raise BranchProvenanceError("group revision immutable identity is invalid")
if str(value.get("seed_identity", "")) != rebuilt["seed_identity"]:
raise BranchProvenanceError("group revision seed identity is invalid")
rebuilt["revision_order"] = str(
value.get("revision_order", rebuilt["revision_order"])
)
return rebuilt
def resolve_chain(
catalog: Mapping[str, Mapping[str, Any]],
head_revision_id: str,
) -> list[dict[str, Any]]:
head = str(head_revision_id)
if not head:
raise BranchProvenanceError("selected revision ID is empty")
reverse: list[dict[str, Any]] = []
seen: set[str] = set()
current: str | None = head
while current is not None:
if current in seen:
raise BranchProvenanceError("group revision ancestry contains a cycle")
seen.add(current)
raw = catalog.get(current)
if raw is None:
raise BranchProvenanceError(
f"group revision parent is missing: {current}"
)
revision = validate_group_revision(raw)
reverse.append(revision)
parent = revision.get("parent_revision_id")
current = None if parent is None else str(parent)
chain = list(reversed(reverse))
expected_start = 1
lineage = str(chain[0].get("lineage_sha256", ""))
for revision in chain:
group = revision["group"]
if int(group["start"]) != expected_start:
raise BranchProvenanceError("group revision ancestry is not a contiguous prefix")
if str(revision.get("lineage_sha256", "")) != lineage:
raise BranchProvenanceError("group revision ancestry crosses sampling lineages")
expected_start = int(group["end"]) + 1
return chain
def active_revision_map(chain: Iterable[Mapping[str, Any]]) -> dict[str, str]:
active: dict[str, str] = {}
for revision in chain:
validated = validate_group_revision(revision)
active[str(validated["group"]["physical_group"])] = validated["revision_id"]
return active
+25 -1
View File
@@ -184,9 +184,33 @@ def run_native_layout_self_test() -> str:
va, _vb = target_video
if not torch.equal(layout.position_ids[ra:rb], layout.position_ids[va : va + (rb - ra)]):
raise CompatibilityError("layout self-test could not align video context")
audio_refs = [
{
"kind": "audio",
"ref_audio_t": length,
"audio_latent": torch.zeros(1, 32, 2, length),
}
for length in (2, 3, 4)
]
audio_layout = h3_model.PackedLayout(
3, 7, 2, 2, 10, keyframes=None, refs=audio_refs
)
audio_segments = [
stop - start
for start, stop, kind in audio_layout.segments
if kind == "ref_audio"
]
packed_audio_rows = torch.cat(
[h3_model.pack_audio(item["audio_latent"]) for item in audio_refs], dim=0
).shape[0]
if audio_segments != [4, 6, 8] or sum(audio_segments) != packed_audio_rows:
raise CompatibilityError(
"layout self-test found a multi-Reference-Audio packed-row mismatch"
)
return (
f"native PackedLayout self-test passed; rows={layout.position_ids.shape[0]}, "
f"position_ids_id={result['position_ids_id']}"
f"position_ids_id={result['position_ids_id']}, "
f"reference_audio_rows={packed_audio_rows}"
)
def ensure_native_h3_base_model(base_model: Any) -> None:
+69
View File
@@ -0,0 +1,69 @@
# Branch Provenance Contract v1
Status: V3.8 N2b implementation contract.
## Purpose
Branch Provenance records which immutable physical-group revision is active at
each point in a Run Storage chain. It allows a user to select an older Take and
generate only the physical groups after that Take without deleting the former
branch or confusing equal nonces with equal ancestry.
Take labels are presentation only. Internal identity is always `revision_id`.
## Physical-group revision
Every completed physical group records:
- `revision_id`: immutable SHA-256-derived identity;
- `parent_revision_id`: the immediately preceding physical-group revision;
- `group`: one-based `start`, `end`, and `physical_group` values;
- `variation_nonce` and `seed_identity`;
- `storage_revision_id` and `generation_contract_sha256`;
- `lineage_sha256` and immutable chunk record identities;
- `created_utc` plus deterministic `revision_order`;
- optional `branch_cut` metadata.
Terminal Merge `[N-1,N]` is one physical group. A chain that contains only one
logical half is invalid.
## Canonical chain
`project.json` has exactly one `canonical_chain`, one
`canonical_head_revision_id`, and an `active_revisions` map. Browsing Takes does
not change them. `Use This Take` or `Continue From Here`, followed by the normal
Queue action, creates a finalized Schema v3 storage revision and atomically
switches the canonical chain.
`Continue From Here` keeps the selected prefix exactly and starts a new existing
sampling nonce boundary at the next physical group. The Sampling Contract itself
remains version 5 and is not extended with provenance fields.
## Run Storage Schema v3
Schema v3 separates `revision_id` (storage execution identity) from
`sampling_revision_id` (the unchanged Sampling Contract identity). A finalized
manifest contains Branch Provenance v1 metadata with its complete active chain,
branch selection/cut when applicable, and a monotonic `canonical_sequence`.
The write order is:
1. save and fsync new chunk payloads;
2. validate all logical records in the completed physical group;
3. atomically write the finalized manifest and its active chain;
4. atomically replace `project.json` with the new canonical head.
A failure before step 4 leaves the preceding canonical project head intact.
If `project.json` is corrupt, the highest validated `canonical_sequence` in a
finalized manifest is the recovery source. In-progress and interrupted revisions
are not Render History Take candidates.
## Schema v2 compatibility
Schema v2 manifests remain readable and are never rewritten merely by loading
them. Their contiguous records are interpreted in memory as a legacy chain with
one canonical physical-group revision per group. The first Schema v3 save uses a
separate storage revision directory, so the legacy manifest and payloads remain
unchanged.
No automatic Take garbage collection is part of N2b.
@@ -0,0 +1,254 @@
# V3.8 初心者向けマニュアル設計・撮影台本
状態: Computer Use実画面検証PASS/4-step・0.30 MP・Spectrum OFFでContinue完走/README反映中(2026-09-07)
最新結果: 提供された00058を、Turbo4、実Steps 4、Euler/simple、Draft 0.30 MP、Spectrum OFF、2×5秒でUIから再検証した。Chunk 1の三択レビュー画面が出現し、`Use it and continue`選択後に右上の青い`Run`を押すと、受理済みChunk 1を再SamplingせずChunk 2だけをSampling(Sampler表示43.738秒)し、10秒の`Saved sequence is complete`へ到達した。修正後の`Try this chunk again`も別の実画面試験でPASS済み。現在フロントエンドの実行ボタンは右上の青い`Run`で、ノード内の`Run`設定やカード内の旧`Queue`表記と区別する。
## 現在の制作範囲(以下の旧撮影案より優先)
- 完成原稿は英語の `../README.md`。日本語READMEの翻訳は最終段階まで保留。単純な初回生成説明は増やさず、任意チャンク数での継続・再試行・残り生成・設定へ戻る・履歴・指定位置以降の再生成・完成後の延長を中心にする。
- 継続操作だけでなく、V3.8が公開する7ノードの全ユーザー向けsocket/control/outputをREADMEで説明する。SamplerのMain/Advanced/Review状態、Continuum Settings、Load Image/Audio/Video、Reference Audios、Finalize、Second Passを省略しない。非表示の内部IDは「UI」扱いせず、frontend管理であることだけを示す。
- UIの文字列、変更する値、維持する値、Queue操作、その回に新規生成される範囲、保存動画の長さを順番に説明する。2チャンクは例であり固定条件ではない。fixed seed、Chunksは追加数でなく合計数、Terminal Merge例外を省略しない。
- 提供された実画面6枚を加工せず `images/v38-manual/` へ保存済み。`seed-fixed.png`、`review-settings.png`、`review-actions.png`、`continue-selected.png`、`return-to-review.png`、`full-video-progress.png`。Spectrum設定の画像はこの章に使用しない。元画像とのSHA一致・PNG形式・READMEリンクを確認済み。
- 今回追加した公開用実画面はreview三択、continue選択、sequence完了、Back to Settings後の完了設定、Render History内部、Regenerate FromとVariation Nonce。既存画像を新規撮影と称さない。全画面ではなく操作部分の実スクリーンショットを使用する。finish選択は三択画面で場所と意味を説明し、必要になった場合だけ追加撮影する。
- 追加提供された7枚を、Video/Audio loaderとbypass、Reference Image 1–3、First/Last Image、First Image + Draft 0.30 MP、LightX2V Turbo LoRA一覧、First Image tooltip、Manual Width/Heightとして無加工コピーした。LoRA loader、Spectrum、画像中のAudio Switch/Fast Groups Bypasserは外部workflow要素として分離し、Continuum公開UIと誤認させない。
- README冒頭に「Web対応AIへこのREADMEを読ませる」案内を置く。ChatGPT/Gemini/Grokの現行公式情報に限定し、URLだけでrepository全文を読めるとは保証しない。GeminiのImport codeと、失敗時のREADME貼付/uploadを案内する。
- Size Source/Resolution/Manual Width・HeightはV3.8 Sampler本体に搭載されたため、通常workflowに外部MP/size nodeは不要と説明する。32×32は音声だけを聴く診断用であり、映像品質の推奨値にはしない。
- Issue #13はOpen、StandardにはProduction mitigationなし、R6-Aは一条件で改善したが最終4×8ではno-opだった、という証拠範囲を固定する。「解決済み」「全く改善方法がない」のどちらにも誇張しない。
- ユーザーが `http://127.0.0.6:8188/` で起動した `00058` ワークフローを使用した。ユーザー所有backendは停止しない。
- READMEの測定例は今回の4-step実測へ更新し、旧6-step値と混在させない。commit/pushは今後の明示依頼時のみ。
作成日: 2026-09-06
対象: `H3 Continuum Sampler V3.8`の現在のMain UI
再開時の正本: この文書と`PROJECT_STATE.md`
## この文書を読めば撮影準備から再開できる
この文書は、V3.8の初心者向け画像マニュアルを作るための設計書兼撮影台本です。完成マニュアルそのものではありません。ドリフト軽減策、公開UI、標準Workflowが固まったあと、この台本に沿ってComputer Useで実画面を確認し、スクリーンショットを撮影します。
撮影開始の指示を受けた担当者は、最初に次を読みます。
1. `AGENTS.md`
2. `PROJECT_STATE.md`
3. この文書
4. `README_JA.md`の「10秒を5秒ずつ確認しながら作る」
5. `examples/workflows/MiniMax_H3_Continuum_V38.json`
撮影開始前に、表示ラベル、標準Workflow、公開ノード数、Review/Take動作がこの台本と一致するか確認します。違いがある場合は、古い画面を撮影せず、先に台本を現在のUIへ合わせます。
## 完成マニュアルは初回手順と目的別の逆引きに分ける
読者はComfyUIの基本操作を知っているものの、Continuumのチャンク、Review、Take、保存再開は初めてという利用者を想定します。モデルの入手、ComfyUI本体の導入、一般的なSampler解説は別資料へ任せます。
完成版では、最初に読む範囲と必要時だけ読む範囲を分けます。
- 初回に読む: 1~4章
- 必要なときに読む: 5章以降
予定する章は次のとおりです。
1. V3.8で最初の動画を作る
2. 長さと出力サイズを決める
3. 10秒を5秒ずつ確認しながら作る
4. 完成動画をFinalizeして保存する
5. 現在のチャンクだけを作り直す
6. 保存されたTakeを選ぶ
7. 選んだ地点から続きを作る
8. List/Timeline Promptを使う
9. Audio Continuityと参照素材を使う
10. Second Passを完成後のsequenceへ使う
11. 症状から原因を探す
12. 用語集と報告テンプレート
マニュアル冒頭には、V3.8が「生成、チャンクごとの確認、部分再生成、保存再開」を行うProduction Samplerであることを短く示します。V3.7以前の画面やNode IDをV3.8の手順へ混ぜません。
## 1操作につき1枚の画面と1つの期待結果を示す
各手順は次の順番で書きます。
1. 目的を1文で示す
2. 変更する項目を画面上の正確な表示名で示す
3. 操作対象を番号付きスクリーンショットで示す
4. なぜ必要かを1文で添える
5. Queue後に見える正常な結果を示す
6. 次に選べる操作へつなぐ
7. 失敗時は対応する逆引き項目へ案内する
1枚へ多数の番号を詰め込みません。特にReviewでは「ボタンを選ぶ」と「ComfyUIのQueueを押す」を別ステップとして扱います。選択しただけで生成が始まらないことを、本文と画面の両方で明示します。
## 撮影はUIと長尺品質が固定されたあとに始める
本撮影は、次の条件がそろってから開始します。
- 公開対象のV3.8 UIラベルと配置が確定している
- 標準Workflowが確定している
- 現在進行中のドリフト調査について、ローンチ時の扱いが決まっている
- READMEと実画面のReview手順が一致している
- `Review Each Chunk`、再生成、Take選択、再開の正常系が通る
- 画面更新、警告表示、失敗時の案内が確認済みである
- 撮影に使うruntimeとsourceの一致を確認できる
構成と本文の下書きは先に進められます。UIが変わる可能性のある段階では、最終スクリーンショットと座標依存の注釈を確定しません。
## 撮影環境を固定して画面差し替えを減らす
撮影前に次の条件を記録します。
| 項目 | 撮影時に記録する内容 |
|---|---|
| Continuum | version、source commitまたはtree識別情報 |
| ComfyUI | versionまたはcommit |
| Workflow | 正本ファイル名とSHA-256 |
| Browser | 種類、表示倍率 |
| Viewport | 幅、高さ |
| Theme | light/dark |
| Sampler view | 現在のMain UIとAdvancedの開閉状態 |
| Input | 使用する画像、音声、動画の識別名 |
| Generation | Seed、Model、LoRA、Sampler、Steps、SIGMAS |
| Output | Width、Height、fps、Chunks、Seconds per Chunk |
撮影用Workflowは、個人名、ローカルの機密パス、過去の不要な履歴を含まない専用コピーを使います。ComfyUI Coreノードは標準表示名のまま撮影し、Continuum専用に見える名前へ変更しません。
## 撮影台本はQuick Startから始める
最初の撮影セットは、`2 × 5s = 10 seconds`のReview手順です。以下のShot IDを画像名にも使います。
| Shot ID | 撮影する状態 | 画面で確認する要素 | 本文で伝えること |
|---|---|---|---|
| V38-M01 | 標準Workflow全体 | Sampler、Core Decode、Finalize、Core Save Video | 最小の接続全体 |
| V38-M02 | Sampler初期Main | Prompt Format、Continuity、Base Seed、Control After Generate、Audio Continuity | 最初に確認する場所 |
| V38-M03 | 長さ設定後 | Chunks `2`、Seconds per Chunk `5`、Total Length `10 seconds` | 合計10秒の指定 |
| V38-M04 | 出力サイズ設定 | Size Sourceと適用中のWidth/Height | First ImageとManualの違い |
| V38-M05 | Review準備完了 | Run `Review Each Chunk`、Progress On、緑色のReadyカード | 最初のQueue準備完了 |
| V38-M06 | Chunk 1実行中 | ComfyUI Queueと進行表示 | 最初は5秒だけ作る |
| V38-M07 | Review Ready | `Chunk 1 is ready for review`のアンバー表示 | 5秒出力は正常 |
| V38-M08 | Reviewの3操作 | Use it and continue、Try this chunk again、Use it and finish the rest | 3つの分岐 |
| V38-M09 | Continue選択後 | 選択ボタンの`✓` | 選択だけでは生成しない |
| V38-M10 | 2回目のQueue | ComfyUI Queue | 採用済みChunk 1を再利用する |
| V38-M11 | 10秒完成後 | 完成状態、Finalize、保存結果 | 2チャンクの完成 |
| V38-M12 | Settingsへ戻る | Back to Settings | Reviewを失わず設定を見る |
| V38-M13 | Reviewへ戻る | Return to Review | 保留中のReviewへ戻る |
Quick Startの撮影が終わったら、同じ撮影用Runを再利用して再生成と履歴を撮ります。
| Shot ID | 撮影する状態 | 画面で確認する要素 | 本文で伝えること |
|---|---|---|---|
| V38-R01 | 再生成選択前 | 現在のChunkとTake | 作り直す対象 |
| V38-R02 | 再生成選択後 | Try this chunk againの`✓` | 同じChunkの別Takeを作る |
| V38-R03 | 再生成完了後 | 新しいTakeとReview状態 | 前のTakeは消えない |
| V38-H01 | Render Historyを開く | Take一覧と現在の選択 | 閲覧だけではcanonicalを変えない |
| V38-H02 | 過去Takeを選ぶ | Previous/Nextまたは現在の選択表示 | 候補を比較する |
| V38-H03 | Take採用前 | Use This Take | Queue後にcanonicalを変更する操作 |
| V38-H04 | 途中から継続する前 | Continue From Hereと再利用範囲 | 選択地点より後ろだけを作り直す |
## サイズ・入力・Advancedは目的別に追加撮影する
Quick Startへすべてを詰め込まず、次の画面は独立した章で撮ります。
| Shot ID | 撮影する状態 | 必須の比較 |
|---|---|---|
| V38-S01 | Size Source `First Image` | 画像の縦横比と参照表示のWidth/Height |
| V38-S02 | Size Source `Manual` | 編集可能な32-pixel単位のWidth/Height |
| V38-I01 | First Image接続 | I2VA/FL2VAでのサイズ決定 |
| V38-I02 | Reference Image接続 | First Imageとは異なる役割 |
| V38-I03 | Video Guide接続 | Video Guide SizeとFrames |
| V38-A01 | Reference Audios | Audio 1/2/3の順序 |
| V38-A02 | Audio Continuity | On/Offの意味と最終音声との違い |
| V38-X01 | Advancedを開く | Mainにない高度な項目の位置 |
| V38-X02 | Second Pass接続 | Review完了後のsequenceに使うこと |
## 異常系は実際の表示を再現して撮る
正常系の撮影後、データを壊さない条件で次の状態を意図的に再現します。各ケースは、表示された文言と解決手順が現在の実装に一致することを確認してから掲載します。
| Shot ID | 症状または表示 | マニュアルで案内する確認 |
|---|---|---|
| V38-T01 | 最初のQueueで5秒だけ出た | Review Each Chunkの正常動作 |
| V38-T02 | 次の操作が表示されない | Queue完了、Progress On、Chunks 2以上、画面更新 |
| V38-T03 | 操作を選んでも生成されない | 選択後にQueueが必要 |
| V38-T04 | Chunksが1 | 次のChunkが存在しない |
| V38-T05 | fixedを求める案内 | Control After GenerateとSeed lineage |
| V38-T06 | First Imageが届かない | 表示中のManual canvasへのfallback |
| V38-T07 | 保存済みprefixを再利用しない | Run Name、Seed、Prompt Plan、生成契約の差 |
| V38-T08 | Review途中でSecond Passを使おうとした | sequence確定後に実行 |
| V38-T09 | 音声境界や冒頭語の欠落を報告する | Workflowと再現条件を保存して報告 |
| V38-T10 | 長尺で色・質感・identityが変化する | 現行の既知制限と報告に必要な情報 |
T09とT10は原因を決めつけません。実際のバグ、設定差、説明不足を分けられるよう、報告テンプレートへ誘導します。
## スクリーンショットは同じ規則で保存する
画像は`docs/images/v38-manual/`へ置く想定です。撮影を始めるまでは空フォルダを作りません。
ファイル名は次の形式にします。
```text
v38-m01-standard-workflow.png
v38-m05-review-ready-to-queue.png
v38-m08-review-actions.png
v38-h04-continue-from-here.png
v38-t05-control-after-generate-fixed.png
```
元画像を保管する場合は`*-raw.png`、掲載用に注釈を加えた画像は通常名とします。注釈は番号、短いラベル、必要最小限の枠線に限定します。文字やsocketを覆わず、色だけに意味を持たせません。
## Computer Use撮影は観察と確認を1ステップずつ行う
撮影時はComputer Useで現在のComfyUIウィンドウを選び、操作前に画面状態を確認します。クリックや入力後は新しい画面状態を取得し、古い座標や要素番号を再利用しません。
各Shotは次の手順で確定します。
1. 台本の前提状態を作る
2. 表示ラベルと値を画面上で読む
3. スクリーンショットを取得する
4. Shot ID、Workflow、設定、実行前後を記録する
5. 画像と本文が同じ操作を示すか確認する
6. 次のShotへ進む
ログイン、権限変更、公開投稿、ファイル送信など、画面撮影に不要な外部操作は行いません。個人情報や認証情報が見えた場合は撮影を止め、撮影用環境を整え直します。
## 完成版には再現可能なバグ報告テンプレートを付ける
問い合わせ時には、少なくとも次を添えてもらいます。
- Continuum version
- ComfyUI version
- Workflow JSON
- Prompt全文とPrompt Format
- Model、LoRA、Sampler、Steps、SIGMAS
- SeedとControl After Generate
- ChunksとSeconds per Chunk
- ContinuityとAudio Continuity
- RunとProgress
- Width/HeightとSize Source
- 使用したFirst/Last/Reference Image、Video Guide、Driving/Reference Audioの有無
- どのChunk境界で起きたか
- Status/Report全文
- 問題が分かる短い出力またはスクリーンショット
音声の冒頭語が欠ける場合は、期待した台詞、実際に聞こえた台詞、欠落したChunk番号も記録します。ドリフトの場合は、開始Chunkと最も目立つChunkを示します。
## 撮影後は画面だけで手順を判断しない
完成判定では、画像の見た目に加えて実際の動作を確認します。
- すべての画像が現在のV3.8 UIである
- 表示名が実装と完全に一致する
- Quick Startを初見の利用者が順番どおり実行できる
- Review操作を選ぶ工程とQueueする工程が分かれている
- 再生成で前のTakeが保持される
- Continue From Hereの再利用範囲が正しい
- Coreノードの標準表示名を変更していない
- 画像内に個人情報や不要なローカルパスがない
- 英語版と日本語版で同じ画像を安全に共有できる
- README、完成マニュアル、実画面の説明が矛盾しない
撮影・本文作成後は、手順を最初から一度再実行します。画像と文章だけを見て再現できない箇所は、UI改善候補、マニュアル修正、実装バグのいずれかへ分類します。
## 次回の開始指示
ユーザーから「V3.8マニュアルの撮影を開始」「初心者向けマニュアルを作成」などの指示があった場合は、この文書を正本として再開します。まず撮影開始条件を確認し、未確定のUIやドリフト表示方針があれば、その部分だけを保留します。条件がそろっていればV38-M01から順に進めます。
公開、commit、push、Civitai掲載は、この台本の作成や撮影開始には含まれません。別の明示指示が必要です。
+84
View File
@@ -0,0 +1,84 @@
# V3.8 Open Integration Contract
This document defines the supported boundary between H3 Continuum V3.8 and
external processing, decoder, and acceleration nodes. It does not add a public
node or change the Sampling, State, Session, Run Storage, or Assembly Plan
schemas.
## Supported pipeline
```text
H3 Continuum Sampler V3.8
-> external latent processor or latent upscaler (optional)
-> H3 Continuum Second Pass
-> Core Video/Audio Decode
-> H3 Continuum Finalize
-> Core Save Video
```
Pixel upscalers remain outside the latent boundary. If a workflow decodes to
pixels for processing, it must encode the result back to one H3 video LATENT per
physical group before Second Pass.
## External processor contract
An external processor may change only the spatial geometry of the video
latents. It must preserve:
- physical-group count and order;
- one indivisible entry for every Long Terminal Merge group;
- video batch, 24 channels, and temporal latent length;
- one common target H/W across every physical group;
- the matching first-pass audio latent list and its order;
- the original Assembly Plan input.
Spatial video dimensions may be preserved or enlarged. Smaller dimensions,
NaN/Inf values, changed B/C/T geometry, a changed group count/order, or a changed
audio shape are rejected before Second Pass Sampling.
Second Pass rebuilds supported conditioning for the target geometry, samples
complete physical groups, and returns a copied Assembly Plan with only target
geometry and Second Pass execution metadata added. It does not mutate the input
plan or Run Storage. The accepted first-pass audio LATENT objects are returned
unchanged; temporary audio produced during video refinement is discarded.
## Decoder boundary
H3 Continuum has no decoder allowlist. Any Core or third-party Video/Audio VAE
path, including a TensorRT-backed VAE, is compatible when it implements the
public ComfyUI contracts and produces the normal decoded types consumed by
Finalize:
- `IMAGE`: `[frames, height, width, channels]` per physical group;
- `AUDIO`: a mapping with `waveform` and positive `sample_rate` per physical
group.
Finalize depends on those public decoded types and the Assembly Plan, not on a
decoder class name. Decoder fallback, tiling, device placement, and acceleration
are owned by the decoder or ComfyUI Core.
## Acceleration boundary
SageAttention, Sol-Attn, Spectrum, and comparable accelerators remain external
MODEL wrappers. Continuum uses ComfyUI's public ModelPatcher wrapper APIs,
preserves existing wrapper/model options on call-local clones, and publishes
only the documented `h3_continuum` interoperability hint when continuation
context exists.
Continuum does not select an attention backend, import accelerator-private
functions, or globally monkey-patch an accelerator. Missing optional accelerator
markers are informational and never become package dependencies.
## Ownership summary
| Owner | Responsibility |
|---|---|
| Continuum | Physical-group identity/order, temporal ownership, conditioning reconstruction, Second Pass validation/Sampling, first-pass audio passthrough, target-geometry plan copy, Finalize assembly |
| External processor | Spatial Video LATENT transformation while preserving B/C/T, group order, and finite values |
| Core or decoder node | Video/Audio VAE decode/encode behavior, tiling, fallback, device lifecycle |
| Accelerator wrapper | Sage/Sol/Spectrum backend selection and wrapper lifecycle |
| User workflow | Correctly wire the matching Video LATENT list, first-pass Audio LATENT list, and original Assembly Plan |
The contract deliberately avoids an All-in-One node. New processors and
decoders can integrate through public ComfyUI types without requiring a
Continuum release, provided these invariants remain true.
+35
View File
@@ -0,0 +1,35 @@
# V3.8 Release and Migration Policy
## Supported release
V3.8 is the current supported H3 Continuum product. Its package exports seven Node IDs:
```text
H3ContinuumSamplerV38
H3ContinuumReferenceAudios
H3ContinuumAssembleSeamV35
H3EasyLoadImage
H3EasyLoadAudio
H3ContinuumLoadVideo
H3ContinuumSecondPassV35
```
The assembler, loader, and Second Pass IDs are retained while their V3.8 display names are simplified. AUDIO-R1 adds one modular Reference Audios helper and appends one optional Sampler bundle socket. The Resolution / Size Source UX keeps the old Aspect input hidden for compatibility and appends Size Source, Width, and Height; saved fixed-Aspect workflows migrate to an equivalent Manual canvas. Sampling, Run Storage, State/Session, and Assembly contracts are unchanged.
## Saved workflows from older releases
Only the seven IDs listed above are exported by V3.8, including the retained Finalize, loader, and Second Pass IDs. Other public Node IDs from V3.7 and earlier are not exported. ComfyUI can therefore show an unknown node when a saved workflow refers to an ID outside this list. This is an intentional support boundary, not a request to replace the unknown node with a superficially similar V3.8 node.
- Use tag `v3.7.0` for V3.7 workflows.
- Use tag `v3.6.0` for V3.6 workflows.
- V3.4/V3.5 archives will be finalized during Release Preparation. Until then, use the matching historical commit or release asset already associated with that workflow.
Do not mix a historical workflow's private schema with the V3.8 package. Install the matching historical package, open and render the workflow there, or rebuild the graph explicitly with the V3.8 public nodes.
## V3.8 workflow and external integration
The declared Registry payload and GitHub distribution use `examples/workflows/MiniMax_H3_Continuum_V38.json` and `examples/workflows/MiniMax_H3_Continuum_V38.zip`. The ZIP contains exactly the same JSON: one graph, not two variants. This is the user-supplied Spectrum workflow, not the former dependency-free Core template. It requires external Spectrum, rgthree, KJNodes, and ComfyUI-Easy-Use nodes, which Continuum does not bundle or install. Its saved default is the Spectrum path; users may switch the same graph to one task-matched LightX2V Turbo LoRA after disabling Spectrum, but all custom-node types remain in the graph.
The supplied JSON and ZIP are preserved byte-for-byte, including prompt, media filenames, custom titles, and settings. Select local files and disable unused inputs before rendering. A saved title such as `Save 3x5s Video` does not control duration; the Sampler settings do. The output path uses Core Video/Audio Decode, Finalize, Core Create Video, and Core Save Video (with the supplied Easy Use cleanup wrapper before Save). External latent processors and upscalers connect through H3 Continuum Second Pass; the old integrated Hi-Res Fix is not part of the V3.8 standard workflow. The supported processor, decoder, and accelerator boundaries are defined in [V3.8 Open Integration Contract](V38_OPEN_INTEGRATION_CONTRACT.md). Registry validate/pack and publication remain separate gates; a GitHub source commit does not claim they have run.
Tests, runner/probe/diagnostic tools, internal development documents, Labs nodes, and historical workflows remain available in the GitHub source for development and audit purposes but are excluded from the Registry archive. The archive retains `tools/__init__.py` and `tools/p20_file_backed_tensor_poc.py`, which are runtime dependencies of the Production file-backed buffer path, plus `tools/verify_runtime.py` for verification. `MANIFEST.sha256` validates its declared source files; the staged archive instead carries `REGISTRY_MANIFEST.sha256`. These development assets are not part of the supported V3.8 searchable node surface.
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 718 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 282 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
+18 -7
View File
@@ -104,18 +104,29 @@ def build_upstream_graph_contract(
safe = True
reasons: list[str] = []
specs = [
("model", True),
("clip", True),
("video_vae", bool(require_video_vae)),
("model", "model", True),
("clip", "clip", True),
("video_vae", "video_vae", bool(require_video_vae)),
]
if require_reference_audio_vae:
specs.append(("reference_audio_vae", True))
reference_audio_route = "reference_audio_vae"
direct_link = inputs.get(reference_audio_route)
if not (
isinstance(direct_link, (list, tuple))
and len(direct_link) == 2
and isinstance(direct_link[0], (str, int))
and isinstance(direct_link[1], int)
):
reference_audio_route = "audio_references"
# Keep the established descriptor key. The bundled route fingerprints
# the helper and therefore its Audio VAE plus every ordered source.
specs.append(("reference_audio_vae", reference_audio_route, True))
if require_audio_vae:
specs.append(("audio_vae", True))
for name, required in specs:
specs.append(("audio_vae", "audio_vae", True))
for name, input_name, required in specs:
if not required:
continue
link = inputs.get(name)
link = inputs.get(input_name)
if not (
isinstance(link, (list, tuple))
and len(link) == 2
+2 -1
View File
@@ -466,7 +466,8 @@ def format_memory_snapshot(label: str, *values: Any) -> str:
cuda_reserved: int | None = None
cuda_free: int | None = None
try:
if torch.cuda.is_available():
# Reading diagnostics must not initialize CUDA in an otherwise CPU run.
if torch.cuda.is_initialized():
cuda_allocated = int(torch.cuda.memory_allocated())
cuda_reserved = int(torch.cuda.memory_reserved())
cuda_free = int(torch.cuda.mem_get_info()[0])
+5 -1
View File
@@ -37,8 +37,12 @@ Get-ChildItem -LiteralPath $source -Force | Where-Object { $exclude -notcontains
}
$python = Join-Path $ComfyUIRoot "venv\Scripts\python.exe"
$verifier = Join-Path $destination "tools\verify_runtime.py"
if (Test-Path $python) {
& $python (Join-Path $destination "tools\verify_runtime.py") --comfy-root $ComfyUIRoot
if (-not (Test-Path $verifier -PathType Leaf)) {
throw "Runtime verifier is missing from the installed package: $verifier"
}
& $python $verifier --comfy-root $ComfyUIRoot
if ($LASTEXITCODE -ne 0) {
throw "Runtime verification failed. See the output above."
}
+1 -1
View File
@@ -1,4 +1,4 @@
[project]
name = H3 Continuum
version = 3.7.0
version = 3.8.0
description = Native MiniMax H3 masked AV continuation, Second Pass, and disk-backed assembly.
+10
View File
@@ -159,11 +159,15 @@ def _wrapper_factory(
strict: bool,
debug: bool,
validation_profiler: LayoutValidationProfiler | None = None,
packed_row_planner: Any = None,
) -> Callable[..., Any]:
branch_baselines: dict[tuple[Any, ...], tuple[Any, ...]] = {}
def apply_model_wrapper(executor, *args, **kwargs):
payload = kwargs.get("minimax_payload")
if packed_row_planner is not None:
from .v3.packed_row_planner import observe_layout_fail_soft
observe_layout_fail_soft(packed_row_planner, payload)
has_continuum = payload_has_continuum(payload)
has_mixed_keyframe_refs = (
isinstance(payload, dict)
@@ -233,6 +237,7 @@ def configure_continuum_model(
strict: bool,
debug: bool,
validation_profiler: LayoutValidationProfiler | None = None,
packed_row_planner: Any = None,
):
try:
from comfy.patcher_extension import WrappersMP
@@ -264,6 +269,7 @@ def configure_continuum_model(
strict=bool(strict),
debug=bool(debug),
validation_profiler=validation_profiler,
packed_row_planner=packed_row_planner,
),
)
model_options = dict(getattr(patched, "model_options", None) or {})
@@ -279,6 +285,7 @@ def patch_model(
strict: bool,
debug: bool,
validation_profiler: LayoutValidationProfiler | None = None,
packed_row_planner: Any = None,
):
"""Clone once, then install the Continuum wrapper on that clone."""
if not hasattr(model, "clone"):
@@ -290,6 +297,7 @@ def patch_model(
strict=strict,
debug=debug,
validation_profiler=validation_profiler,
packed_row_planner=packed_row_planner,
)
def continuum_interop_request(*, chunk_index: int, context_frames: int) -> dict[str, Any]:
@@ -310,6 +318,7 @@ def clone_model_for_chunk(
chunk_index: int,
context_frames: int | None,
validation_profiler: LayoutValidationProfiler | None = None,
packed_row_planner: Any = None,
):
"""Create a call-local MODEL and attach an optional read-only Spectrum hint."""
if not hasattr(model, "clone"):
@@ -322,6 +331,7 @@ def clone_model_for_chunk(
strict=bool(strict),
debug=bool(debug),
validation_profiler=validation_profiler,
packed_row_planner=packed_row_planner,
)
if debug:
parent = getattr(chunk_model, "parent", None)
+48 -25
View File
@@ -382,6 +382,38 @@ from .v3.driving_nodes import (
NODE_CLASS_MAPPINGS.update(V34_NODE_CLASS_MAPPINGS)
NODE_DISPLAY_NAME_MAPPINGS.update(V34_NODE_DISPLAY_NAME_MAPPINGS)
from .v3.easy_nodes import (
NODE_CLASS_MAPPINGS as V38_EASY_NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS as V38_EASY_NODE_DISPLAY_NAME_MAPPINGS,
)
NODE_CLASS_MAPPINGS.update(V38_EASY_NODE_CLASS_MAPPINGS)
NODE_DISPLAY_NAME_MAPPINGS.update(V38_EASY_NODE_DISPLAY_NAME_MAPPINGS)
from .v3.easy_image_nodes import (
NODE_CLASS_MAPPINGS as EASY_IMAGE_NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS as EASY_IMAGE_NODE_DISPLAY_NAME_MAPPINGS,
)
NODE_CLASS_MAPPINGS.update(EASY_IMAGE_NODE_CLASS_MAPPINGS)
NODE_DISPLAY_NAME_MAPPINGS.update(EASY_IMAGE_NODE_DISPLAY_NAME_MAPPINGS)
from .v3.easy_audio_nodes import (
NODE_CLASS_MAPPINGS as EASY_AUDIO_NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS as EASY_AUDIO_NODE_DISPLAY_NAME_MAPPINGS,
)
NODE_CLASS_MAPPINGS.update(EASY_AUDIO_NODE_CLASS_MAPPINGS)
NODE_DISPLAY_NAME_MAPPINGS.update(EASY_AUDIO_NODE_DISPLAY_NAME_MAPPINGS)
from .v3.easy_video_nodes import (
NODE_CLASS_MAPPINGS as EASY_VIDEO_NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS as EASY_VIDEO_NODE_DISPLAY_NAME_MAPPINGS,
)
NODE_CLASS_MAPPINGS.update(EASY_VIDEO_NODE_CLASS_MAPPINGS)
NODE_DISPLAY_NAME_MAPPINGS.update(EASY_VIDEO_NODE_DISPLAY_NAME_MAPPINGS)
from .v3.second_pass_nodes import (
NODE_CLASS_MAPPINGS as V35_NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS as V35_NODE_DISPLAY_NAME_MAPPINGS,
@@ -416,29 +448,20 @@ from .v3.hires_fix_nodes import (
NODE_CLASS_MAPPINGS.update(V35_HIRES_FIX_NODE_CLASS_MAPPINGS)
NODE_DISPLAY_NAME_MAPPINGS.update(V35_HIRES_FIX_NODE_DISPLAY_NAME_MAPPINGS)
# The stable facade and its pack helpers are the public workflow surface. Keep
# every older identifier registered so saved workflows still load, while
# ComfyUI's native deprecated-node filter hides legacy building blocks.
_primary_node_ids = {
"H3ContinuumSamplerV34",
"H3ContinuumSamplerV35",
"H3ContinuumSamplerV36",
"H3ContinuumStillImageGuideV37",
"H3ContinuumSamplerV37",
"H3ContinuumAssembleSeamV34",
"H3ContinuumAssembleSeamV35",
"H3ContinuumHiResFixV35",
"H3ContinuumLatentResizeV35",
"H3ContinuumSecondPassV35",
"H3ContinuumConditioningBridgeV35",
"H3ContinuumClipOverrides",
"H3ContinuumResult",
# V3.8 exports only its audited launch surface. The imports and merged mappings
# above intentionally stay in place because the V3.8 implementation still
# inherits and reuses historical modules internally.
_PUBLIC_NODE_DISPLAY_NAMES = {
"H3ContinuumSamplerV38": "H3 Continuum Sampler V3.8",
"H3ContinuumReferenceAudios": "H3 Continuum Reference Audios",
"H3ContinuumAssembleSeamV35": "H3 Continuum Finalize",
"H3EasyLoadImage": "H3 Continuum Load Image",
"H3EasyLoadAudio": "H3 Continuum Load Audio",
"H3ContinuumLoadVideo": "H3 Continuum Load Video",
"H3ContinuumSecondPassV35": "H3 Continuum Second Pass",
}
for _node_id, _node_class in NODE_CLASS_MAPPINGS.items():
if _node_id in _primary_node_ids:
continue
_node_class.DEPRECATED = True
_node_class.CATEGORY = f"{CATEGORY}/Legacy"
_display_name = NODE_DISPLAY_NAME_MAPPINGS.get(_node_id, _node_id)
if not _display_name.startswith("[Legacy]"):
NODE_DISPLAY_NAME_MAPPINGS[_node_id] = f"[Legacy] {_display_name}"
NODE_CLASS_MAPPINGS = {
node_id: NODE_CLASS_MAPPINGS[node_id]
for node_id in _PUBLIC_NODE_DISPLAY_NAMES
}
NODE_DISPLAY_NAME_MAPPINGS = dict(_PUBLIC_NODE_DISPLAY_NAMES)
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "comfyui-h3-continuum"
version = "3.7.0"
version = "3.8.0"
description = "Integrated N-chunk continuation for ComfyUI native MiniMax H3 video and audio"
readme = "README.md"
requires-python = ">=3.10"
+91 -13
View File
@@ -104,6 +104,34 @@ def _validate_image(name: str, image: torch.Tensor) -> torch.Tensor:
return image[:, :, :, :3]
def resolve_reference_image_size(
source_width: int,
source_height: int,
*,
output_width: int,
output_height: int,
size_mode: str,
) -> tuple[int, int]:
"""Resolve Reference Image geometry without resizing or reading pixels."""
if size_mode not in REFERENCE_SIZE_OPTIONS:
raise ReferenceConditioningError(f"unknown Reference Size: {size_mode!r}")
source_width = int(source_width)
source_height = int(source_height)
if size_mode == REFERENCE_SIZE_MATCH_OUTPUT:
target_area = float(int(output_width) * int(output_height))
scale = min(1.0, math.sqrt(target_area / float(source_width * source_height)))
else:
scale = min(
1.0,
float(_MAX_IDENTITY_SHORT_EDGE) / min(source_width, source_height),
)
return (
_round_canvas(source_width * scale),
_round_canvas(source_height * scale),
)
def _resize_reference(
image: torch.Tensor,
*,
@@ -111,17 +139,15 @@ def _resize_reference(
output_height: int,
size_mode: str,
) -> torch.Tensor:
if size_mode not in REFERENCE_SIZE_OPTIONS:
raise ReferenceConditioningError(f"unknown Reference Size: {size_mode!r}")
source_height = int(image.shape[1])
source_width = int(image.shape[2])
if size_mode == REFERENCE_SIZE_MATCH_OUTPUT:
target_area = float(int(output_width) * int(output_height))
scale = min(1.0, math.sqrt(target_area / float(source_width * source_height)))
else:
scale = min(1.0, float(_MAX_IDENTITY_SHORT_EDGE) / min(source_width, source_height))
target_width = _round_canvas(source_width * scale)
target_height = _round_canvas(source_height * scale)
target_width, target_height = resolve_reference_image_size(
source_width,
source_height,
output_width=int(output_width),
output_height=int(output_height),
size_mode=size_mode,
)
if target_width == source_width and target_height == source_height:
return image.contiguous()
try:
@@ -193,6 +219,46 @@ def encode_reference_latents(video_vae: Any, assets: ReferenceAssets) -> Referen
return replace(assets, latents=latents)
def encode_reference_latents_cached(
video_vae: Any,
assets: ReferenceAssets,
*,
cache_event=None,
) -> ReferenceAssets:
"""Encode V3.8 Reference Images with the process-local VAE cache."""
if all(latent is not None for latent in assets.latents):
return assets
from .v3.ref_encode_cache import (
get_ref_encode_cache,
make_ref_encode_cache_key,
)
cache = get_ref_encode_cache()
latents: list[torch.Tensor] = []
for image, image_hash, existing in zip(
assets.images,
assets.image_hashes,
assets.latents,
strict=True,
):
if existing is not None:
latents.append(existing)
continue
key = make_ref_encode_cache_key(
"reference_image",
REFERENCE_PREPROCESS_VERSION,
image_hash,
)
latent = cache.lookup(video_vae, key, event_sink=cache_event)
if latent is None:
latent = video_vae.encode(image)
if cache.supports_vae(video_vae):
cache.store(video_vae, key, latent, event_sink=cache_event)
latents.append(latent)
return replace(assets, latents=tuple(latents))
def build_hybrid_presentation_items(
reference_items: list[dict[str, Any]],
*,
@@ -293,9 +359,15 @@ def encode_reference_prompt(
if timeline_video_assets is not None:
reference_items.append(dict(timeline_video_assets.item))
if reference_audio_assets is not None:
from .reference_audio import reference_audio_item
from .reference_audio import (
reference_audio_asset_items,
reference_audio_item,
)
reference_items.append(reference_audio_item())
reference_items.extend(
reference_audio_item()
for _ in reference_audio_asset_items(reference_audio_assets)
)
presentation_items = build_hybrid_presentation_items(
reference_items,
first_image=first_image,
@@ -321,9 +393,15 @@ def encode_reference_prompt(
if timeline_video_assets is not None:
refs.append(dict(timeline_video_assets.block))
if reference_audio_assets is not None:
from .reference_audio import reference_audio_block
from .reference_audio import (
reference_audio_asset_items,
reference_audio_block,
)
refs.append(reference_audio_block(reference_audio_assets))
refs.extend(
dict(reference_audio_block(item))
for item in reference_audio_asset_items(reference_audio_assets)
)
return [
[tensor, {**dict(metadata), "minimax_refs": list(refs)}]
for tensor, metadata in conditioning
+288 -24
View File
@@ -13,6 +13,8 @@ import torch
REFERENCE_AUDIO_CONTRACT_VERSION = 1
REFERENCE_AUDIO_PREPROCESS_VERSION = 1
REFERENCE_AUDIO_BUNDLE_CONTRACT_VERSION = 1
REFERENCE_AUDIOS_TYPE = "H3_CONTINUUM_AUDIO_REFERENCES"
_AUDIO_TAG = re.compile(r"<Audio\s+(\d+)>")
@@ -60,6 +62,36 @@ class ReferenceAudioAssets:
return self.source.combined_hash
@dataclass(frozen=True)
class ReferenceAudioBundle:
"""Ordered Reference Audio sources plus their shared Core Audio VAE."""
sources: tuple[ReferenceAudioSource, ...]
reference_audio_vae: Any
combined_hash: str
@property
def count(self) -> int:
return len(self.sources)
@property
def contract(self) -> dict[str, Any]:
return {
"reference_audio_bundle_contract_version": (
REFERENCE_AUDIO_BUNDLE_CONTRACT_VERSION
),
"count": self.count,
"items": [
{
"audio_index": index,
"reference_audio": source.contract,
}
for index, source in enumerate(self.sources, start=1)
],
"combined_hash": self.combined_hash,
}
def _canonical_hash(value: Any) -> str:
payload = json.dumps(
value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
@@ -90,32 +122,30 @@ def _validate_waveform(name: str, waveform: Any) -> torch.Tensor:
return waveform.detach().to(device="cpu").contiguous()
def prepare_reference_audio_source(
reference_audio_1: Any,
def _prepare_reference_audio_source(
reference_audio: Any,
reference_audio_vae: Any,
*,
name: str,
) -> ReferenceAudioSource | None:
if reference_audio_1 is None:
if reference_audio is None:
return None
if reference_audio_vae is None:
raise ReferenceAudioError(
"reference_audio_vae is required when reference_audio_1 is connected"
"reference_audio_vae is required when reference audio is connected"
)
if not isinstance(reference_audio_1, dict):
raise ReferenceAudioError("Reference Audio 1 must be a ComfyUI AUDIO value")
waveform = _validate_waveform(
"Reference Audio 1", reference_audio_1.get("waveform")
)
sample_rate_value = reference_audio_1.get("sample_rate")
if not isinstance(reference_audio, dict):
raise ReferenceAudioError(f"{name} must be a ComfyUI AUDIO value")
waveform = _validate_waveform(name, reference_audio.get("waveform"))
sample_rate_value = reference_audio.get("sample_rate")
if isinstance(sample_rate_value, bool):
raise ReferenceAudioError("Reference Audio 1 sample_rate must be positive")
raise ReferenceAudioError(f"{name} sample_rate must be positive")
try:
source_sample_rate = int(sample_rate_value)
except (TypeError, ValueError) as exc:
raise ReferenceAudioError(
"Reference Audio 1 sample_rate must be positive"
) from exc
raise ReferenceAudioError(f"{name} sample_rate must be positive") from exc
if source_sample_rate <= 0:
raise ReferenceAudioError("Reference Audio 1 sample_rate must be positive")
raise ReferenceAudioError(f"{name} sample_rate must be positive")
resolved_rate = int(getattr(reference_audio_vae, "audio_sample_rate", 32000))
if resolved_rate <= 0:
raise ReferenceAudioError("Reference Audio VAE sample rate must be positive")
@@ -129,11 +159,11 @@ def prepare_reference_audio_source(
).contiguous()
except Exception as exc:
raise ReferenceAudioError(
"Reference Audio 1 could not be resampled for the Audio VAE"
f"{name} could not be resampled for the Audio VAE"
) from exc
if not bool(torch.isfinite(resampled).all().item()):
raise ReferenceAudioError(
"Reference Audio 1 contains NaN or infinity after resampling"
f"{name} contains NaN or infinity after resampling"
)
source_shape = tuple(int(value) for value in waveform.shape)
resampled_shape = tuple(int(value) for value in resampled.shape)
@@ -165,6 +195,96 @@ def prepare_reference_audio_source(
)
def prepare_reference_audio_source(
reference_audio_1: Any,
reference_audio_vae: Any,
) -> ReferenceAudioSource | None:
"""Prepare the unchanged legacy single-Reference-Audio path."""
if reference_audio_1 is None:
return None
if reference_audio_vae is None:
# Preserve the established user-facing legacy validation text exactly.
raise ReferenceAudioError(
"reference_audio_vae is required when reference_audio_1 is connected"
)
return _prepare_reference_audio_source(
reference_audio_1,
reference_audio_vae,
name="Reference Audio 1",
)
def prepare_reference_audio_bundle(
reference_audio_1: Any,
reference_audio_2: Any,
reference_audio_3: Any,
reference_audio_vae: Any,
) -> ReferenceAudioBundle | None:
"""Prepare up to three ordered Core-native standalone audio references."""
values = (reference_audio_1, reference_audio_2, reference_audio_3)
connected = tuple(value is not None for value in values)
if not any(connected):
return None
first_gap = next((index for index, present in enumerate(connected) if not present), 3)
if any(connected[first_gap + 1 :]):
raise ReferenceAudioError(
"Reference Audio inputs must be connected in order without gaps so "
"<Audio 1>, <Audio 2>, and <Audio 3> keep their exact Core numbering"
)
sources = tuple(
_prepare_reference_audio_source(
value,
reference_audio_vae,
name=f"Reference Audio {index}",
)
for index, value in enumerate(values, start=1)
if value is not None
)
contract_base = {
"reference_audio_bundle_contract_version": (
REFERENCE_AUDIO_BUNDLE_CONTRACT_VERSION
),
"count": len(sources),
"items": [
{
"audio_index": index,
"reference_audio": source.contract,
}
for index, source in enumerate(sources, start=1)
],
}
return ReferenceAudioBundle(
sources=sources,
reference_audio_vae=reference_audio_vae,
combined_hash=_canonical_hash(contract_base),
)
def resolve_reference_audio_input(
reference_audio_1: Any,
reference_audio_vae: Any,
audio_references: Any,
) -> tuple[ReferenceAudioSource | ReferenceAudioBundle | None, Any]:
"""Resolve legacy or bundled input without silently mixing contracts."""
if audio_references is not None:
if not isinstance(audio_references, ReferenceAudioBundle):
raise ReferenceAudioError(
"Audio References must come from H3 Continuum Reference Audios"
)
if reference_audio_1 is not None:
raise ReferenceAudioError(
"Use either legacy Reference Audio or Audio References, not both"
)
return audio_references, audio_references.reference_audio_vae
return (
prepare_reference_audio_source(reference_audio_1, reference_audio_vae),
reference_audio_vae,
)
def encode_reference_audio(
reference_audio_vae: Any,
source: ReferenceAudioSource,
@@ -189,16 +309,71 @@ def encode_reference_audio(
return ReferenceAudioAssets(source=source, audio_latent=latent)
def encode_reference_audio_cached(
reference_audio_vae: Any,
source: ReferenceAudioSource,
*,
cache_event=None,
) -> ReferenceAudioAssets:
"""Cache Reference Audio only when its established output is already CPU."""
from .v3.ref_encode_cache import (
get_ref_encode_cache,
make_ref_encode_cache_key,
)
cache = get_ref_encode_cache()
key = make_ref_encode_cache_key(
"reference_audio",
REFERENCE_AUDIO_PREPROCESS_VERSION,
source.combined_hash,
)
latent = cache.lookup(reference_audio_vae, key, event_sink=cache_event)
if latent is not None:
return ReferenceAudioAssets(source=source, audio_latent=latent)
assets = encode_reference_audio(reference_audio_vae, source)
if cache.supports_vae(reference_audio_vae):
cache.store(
reference_audio_vae,
key,
assets.audio_latent,
event_sink=cache_event,
)
return assets
def encode_reference_audio_input(
reference_audio_vae: Any,
source: ReferenceAudioSource | ReferenceAudioBundle,
*,
cache_enabled: bool,
cache_event=None,
) -> ReferenceAudioAssets | tuple[ReferenceAudioAssets, ...]:
"""Encode one legacy source or each ordered bundle source independently."""
encoder = encode_reference_audio_cached if cache_enabled else encode_reference_audio
if isinstance(source, ReferenceAudioBundle):
if cache_enabled:
return tuple(
encoder(reference_audio_vae, item, cache_event=cache_event)
for item in source.sources
)
return tuple(encoder(reference_audio_vae, item) for item in source.sources)
if cache_enabled:
return encoder(reference_audio_vae, source, cache_event=cache_event)
return encoder(reference_audio_vae, source)
def validate_reference_audio_prompts(
prompts: list[str], source: ReferenceAudioSource | None
prompts: list[str], source: ReferenceAudioSource | ReferenceAudioBundle | None
) -> str:
found: set[int] = set()
for prompt in prompts:
found.update(int(value) for value in _AUDIO_TAG.findall(str(prompt)))
warnings: list[str] = []
active_count = 1 if source is not None else 0
active_count = source.count if isinstance(source, ReferenceAudioBundle) else int(source is not None)
unavailable = sorted(
value for value in found if source is None or value != 1
value for value in found if not 1 <= value <= active_count
)
for value in unavailable:
warnings.append(
@@ -207,20 +382,32 @@ def validate_reference_audio_prompts(
"Core-compatible generation will continue; the tag may be ignored "
"or hallucinated."
)
if source is not None and 1 not in found:
for value in range(1, active_count + 1):
if value not in found:
warnings.append(
"H3C-P103 Warning: Reference Audio 1 is connected but the prompt contains no <Audio 1> "
"tag; audio still conditions generation, but an explicit tag is recommended."
f"H3C-P103 Warning: Reference Audio {value} is connected but the prompt "
f"contains no <Audio {value}> tag; audio still conditions generation, "
"but an explicit tag is recommended."
)
return "\n".join(warnings)
def combine_reference_audio_identity(
visual_identity_hash: str,
source: ReferenceAudioSource | None,
source: ReferenceAudioSource | ReferenceAudioBundle | None,
) -> str:
if source is None:
return str(visual_identity_hash)
if isinstance(source, ReferenceAudioBundle):
return _canonical_hash(
{
"reference_audio_identity_version": 2,
"visual_identity_hash": str(visual_identity_hash),
"ordered_reference_audio_hashes": [
item.combined_hash for item in source.sources
],
}
)
return _canonical_hash(
{
"reference_audio_identity_version": 1,
@@ -240,3 +427,80 @@ def reference_audio_block(assets: ReferenceAudioAssets) -> dict[str, Any]:
"ref_audio_t": int(assets.audio_latent.shape[-1]),
"audio_latent": assets.audio_latent,
}
def reference_audio_asset_items(
assets: ReferenceAudioAssets | tuple[ReferenceAudioAssets, ...],
) -> tuple[ReferenceAudioAssets, ...]:
if isinstance(assets, tuple):
return assets
return (assets,)
class H3ContinuumReferenceAudios:
"""Compact public helper for one to three ordered H3 Reference Audios."""
DEPRECATED = False
CATEGORY = "MiniMax H3/Continuum/Input"
DESCRIPTION = (
"Bundle up to three ordered standalone Reference Audios for the V3.8 "
"sampler. Connected inputs map directly to <Audio 1>, <Audio 2>, and "
"<Audio 3>; generated final audio is never replaced."
)
SEARCH_ALIASES = [
"H3 Continuum Reference Audios",
"MiniMax H3 multiple reference audio",
]
@classmethod
def INPUT_TYPES(cls):
audio_tooltip = (
"Optional standalone voice or sound reference. Connect inputs in order "
"without gaps; their order maps to the matching <Audio N> prompt tags."
)
return {
"optional": {
"reference_audio_1": (
"AUDIO",
{"display_name": "Reference Audio 1 (Optional)", "tooltip": audio_tooltip},
),
"reference_audio_2": (
"AUDIO",
{"display_name": "Reference Audio 2 (Optional)", "tooltip": audio_tooltip},
),
"reference_audio_3": (
"AUDIO",
{"display_name": "Reference Audio 3 (Optional)", "tooltip": audio_tooltip},
),
"reference_audio_vae": (
"VAE",
{
"display_name": "Reference Audio VAE",
"tooltip": (
"Shared Core Audio VAE used to encode every connected "
"Reference Audio. Required when any audio is connected."
),
},
),
}
}
RETURN_TYPES = (REFERENCE_AUDIOS_TYPE,)
RETURN_NAMES = ("audio_references",)
FUNCTION = "pack"
def pack(
self,
reference_audio_1=None,
reference_audio_2=None,
reference_audio_3=None,
reference_audio_vae=None,
):
return (
prepare_reference_audio_bundle(
reference_audio_1,
reference_audio_2,
reference_audio_3,
reference_audio_vae,
),
)
+70 -11
View File
@@ -61,7 +61,7 @@ def _round_canvas(value: float) -> int:
)
def _resolved_size(
def resolve_reference_video_size(
source_width: int,
source_height: int,
*,
@@ -92,6 +92,10 @@ def _resolved_size(
return target_width, target_height
# Preserve the established private helper for existing internal callers/tests.
_resolved_size = resolve_reference_video_size
@dataclass(frozen=True)
class ReferenceVideoSource:
frames: torch.Tensor
@@ -128,7 +132,12 @@ class ReferenceVideoAssets:
block: dict[str, Any]
def _resolve_reference_frame_count(source_frames: int, target_frames: int) -> int:
def resolve_reference_video_frame_count(
source_frames: int,
target_frames: int,
) -> int:
"""Resolve the used Video Guide frame count without touching frame data."""
source_count = int(source_frames)
target_count = int(target_frames)
if source_count < 5 or target_count < 5:
@@ -138,6 +147,10 @@ def _resolve_reference_frame_count(source_frames: int, target_frames: int) -> in
return min(align_frame_count_up(available_count), target_cap)
# Preserve the established private name while exposing one shared pure resolver.
_resolve_reference_frame_count = resolve_reference_video_frame_count
def _fit_reference_frames(frames: torch.Tensor, frame_count: int) -> torch.Tensor:
requested_count = int(frame_count)
current_count = int(frames.shape[0])
@@ -204,7 +217,7 @@ def prepare_reference_video_source(
)
if int(reference_video_1.shape[-1]) < 3:
raise ReferenceVideoError("Video Reference must contain RGB channels")
frame_count = _resolve_reference_frame_count(
frame_count = resolve_reference_video_frame_count(
int(reference_video_1.shape[0]),
int(target_frames),
)
@@ -217,7 +230,7 @@ def prepare_reference_video_source(
if str(size_mode) in REFERENCE_VIDEO_SIZE_OPTIONS
else REFERENCE_VIDEO_SIZE_EFFICIENT
)
target_width, target_height = _resolved_size(
target_width, target_height = resolve_reference_video_size(
int(source_shape[2]),
int(source_shape[1]),
output_width=int(output_width),
@@ -249,10 +262,9 @@ def prepare_reference_video_source(
)
def encode_reference_video(
video_vae: Any,
def _prepare_reference_video_encode_input(
source: ReferenceVideoSource,
) -> ReferenceVideoAssets:
) -> tuple[torch.Tensor, dict[str, Any]]:
available_count = min(int(source.frames.shape[0]), int(source.frame_count))
frames = source.frames[:available_count]
if (
@@ -273,16 +285,20 @@ def encode_reference_video(
"disabled",
).movedim(1, -1).contiguous()
frames = _fit_reference_frames(frames, source.frame_count)
try:
latent = video_vae.encode(frames).detach().to("cpu").contiguous()
except Exception as exc:
raise ReferenceVideoError("Video Reference VAE Encode failed") from exc
qwen_frames = frames[::_SOURCE_FPS // 2].contiguous()
item = {
"type": "video",
"data": qwen_frames,
"timestamps": [index / 2.0 for index in range(int(qwen_frames.shape[0]))],
}
return frames, item
def _build_reference_video_assets(
source: ReferenceVideoSource,
item: dict[str, Any],
latent: torch.Tensor,
) -> ReferenceVideoAssets:
block = {
"kind": "video",
"latent_t": int(latent.shape[2]),
@@ -295,6 +311,49 @@ def encode_reference_video(
return ReferenceVideoAssets(source=source, item=item, block=block)
def encode_reference_video(
video_vae: Any,
source: ReferenceVideoSource,
) -> ReferenceVideoAssets:
frames, item = _prepare_reference_video_encode_input(source)
try:
latent = video_vae.encode(frames).detach().to("cpu").contiguous()
except Exception as exc:
raise ReferenceVideoError("Video Reference VAE Encode failed") from exc
return _build_reference_video_assets(source, item, latent)
def encode_reference_video_cached(
video_vae: Any,
source: ReferenceVideoSource,
*,
cache_event=None,
) -> ReferenceVideoAssets:
"""Encode only the V3.8 Video Guide latent through the shared cache."""
from .v3.ref_encode_cache import (
get_ref_encode_cache,
make_ref_encode_cache_key,
)
frames, item = _prepare_reference_video_encode_input(source)
cache = get_ref_encode_cache()
key = make_ref_encode_cache_key(
"video_guide",
REFERENCE_VIDEO_PREPROCESS_VERSION,
source.combined_hash,
)
latent = cache.lookup(video_vae, key, event_sink=cache_event)
if latent is None:
try:
latent = video_vae.encode(frames).detach().to("cpu").contiguous()
except Exception as exc:
raise ReferenceVideoError("Video Reference VAE Encode failed") from exc
if cache.supports_vae(video_vae):
cache.store(video_vae, key, latent, event_sink=cache_event)
return _build_reference_video_assets(source, item, latent)
def combine_reference_video_identity(
visual_identity_hash: str,
source: ReferenceVideoSource | None,
+1275 -37
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,26 @@
{
"last_node_id": 420,
"last_link_id": 0,
"nodes": [
{
"id": 420,
"type": "H3ContinuumSelectiveSecondPassExperimental",
"pos": [0, 0],
"size": [360, 420],
"flags": {},
"order": 0,
"mode": 0,
"inputs": [],
"outputs": [],
"properties": {
"Node name for S&R": "H3ContinuumSelectiveSecondPassExperimental"
},
"widgets_values": [73, "Video + Audio"]
}
],
"links": [],
"groups": [],
"config": {},
"extra": {},
"version": 0.4
}
+216
View File
@@ -0,0 +1,216 @@
from __future__ import annotations
import importlib.util
import inspect
import json
from pathlib import Path
import shutil
import subprocess
import sys
from types import ModuleType, SimpleNamespace
import pytest
from ComfyUI_H3_Continuum_Join import nodes as root_nodes
from ComfyUI_H3_Continuum_Join.v3.easy_audio_nodes import (
H3EasyLoadAudio,
NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS,
)
ROOT = Path(__file__).resolve().parents[1]
BACKEND_PATH = ROOT / "v3" / "easy_audio_nodes.py"
COMMON_FRONTEND_PATH = ROOT / "web" / "easy_bypass_toggle.js"
FRONTEND_PATH = ROOT / "web" / "easy_load_audio.js"
def test_easy_load_audio_is_public_and_keeps_core_audio_contract():
schema = H3EasyLoadAudio.define_schema()
assert NODE_CLASS_MAPPINGS["H3EasyLoadAudio"] is H3EasyLoadAudio
assert root_nodes.NODE_CLASS_MAPPINGS["H3EasyLoadAudio"] is H3EasyLoadAudio
assert NODE_DISPLAY_NAME_MAPPINGS["H3EasyLoadAudio"] == "H3 Continuum Load Audio"
assert root_nodes.NODE_DISPLAY_NAME_MAPPINGS["H3EasyLoadAudio"] == (
"H3 Continuum Load Audio"
)
assert schema.node_id == "H3EasyLoadAudio"
assert schema.display_name == "H3 Continuum Load Audio"
source = inspect.getsource(H3EasyLoadAudio)
assert "def execute" not in source
assert "def fingerprint_inputs" not in source
assert "def validate_inputs" not in source
def test_easy_load_audio_inherits_and_delegates_to_runtime_core(monkeypatch):
fake_package = ModuleType("comfy_extras")
fake_audio_module = ModuleType("comfy_extras.nodes_audio")
class FakeCoreLoadAudio:
@classmethod
def define_schema(cls):
return SimpleNamespace(
node_id="LoadAudio",
display_name="Load Audio",
category="audio",
essentials_category="Audio",
description="core",
search_aliases=["audio file"],
)
@classmethod
def execute(cls, audio):
return f"loaded:{audio}"
@classmethod
def fingerprint_inputs(cls, audio):
return f"fingerprint:{audio}"
@classmethod
def validate_inputs(cls, audio):
return audio == "valid.wav"
fake_audio_module.LoadAudio = FakeCoreLoadAudio
monkeypatch.setitem(sys.modules, "comfy_extras", fake_package)
monkeypatch.setitem(sys.modules, "comfy_extras.nodes_audio", fake_audio_module)
spec = importlib.util.spec_from_file_location("h3_easy_audio_runtime_probe", BACKEND_PATH)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
assert issubclass(module.H3EasyLoadAudio, FakeCoreLoadAudio)
schema = module.H3EasyLoadAudio.define_schema()
assert schema.node_id == "H3EasyLoadAudio"
assert schema.display_name == "H3 Continuum Load Audio"
assert module.H3EasyLoadAudio.execute("voice.wav") == "loaded:voice.wav"
assert module.H3EasyLoadAudio.fingerprint_inputs("voice.wav") == (
"fingerprint:voice.wav"
)
assert module.H3EasyLoadAudio.validate_inputs("valid.wav") is True
def test_easy_load_audio_frontend_preserves_filename_player_and_mode(tmp_path):
node_executable = shutil.which("node")
if node_executable is None:
pytest.skip("Node.js is required for the frontend behavior regression")
functions = COMMON_FRONTEND_PATH.read_text(encoding="utf-8").replace(
"export ", ""
)
script = f"""
{functions}
function plainWidget(name, value) {{
return {{ name, value, options: {{}}, serialize: true }};
}}
const audioWidget = plainWidget("audio", "voice.wav");
const playerWidget = plainWidget("audioUI", {{ position: 1.25, volume: 0.8 }});
const node = {{
comfyClass: "H3EasyLoadAudio",
mode: 0,
widgets: [audioWidget, playerWidget],
addWidget(type, name, value, callback, options) {{
const widget = {{ type, name, value, callback, options, serialize: true }};
this.widgets.push(widget);
return widget;
}},
setDirtyCanvas() {{}},
serialize() {{
return {{
mode: this.mode,
widgets_values: this.widgets
.filter((widget) => widget.serialize !== false)
.map((widget) => widget.value),
}};
}},
configure(info) {{
this.mode = info.mode;
for (let index = 0; index < info.widgets_values.length; index++) {{
this.widgets[index].value = info.widgets_values[index];
}}
}},
}};
configureEasyBypassToggleNode(node, {{
nodeClass: "H3EasyLoadAudio",
widgetName: "Enable Audio",
tooltip: "audio tooltip",
}});
const toggle = findEasyBypassWidget(node);
const initial = {{ names: node.widgets.map((w) => w.name), saved: node.serialize() }};
toggle.callback(false);
const off = {{ mode: node.mode, toggle: toggle.value, saved: node.serialize() }};
toggle.callback(true);
const onAgain = {{ mode: node.mode, toggle: toggle.value, saved: node.serialize() }};
node.mode = 4;
const externalBypass = {{ mode: node.mode, toggle: toggle.value }};
node.configure({{
mode: 4,
widgets_values: ["reloaded.wav", {{ position: 2.5, volume: 0.6 }}],
}});
const reloaded = {{
mode: node.mode,
toggle: toggle.value,
audio: audioWidget.value,
player: playerWidget.value,
names: node.widgets.map((w) => w.name),
}};
console.log(JSON.stringify({{ initial, off, onAgain, externalBypass, reloaded }}));
"""
script_path = tmp_path / "easy-load-audio-frontend.js"
script_path.write_text(script, encoding="utf-8")
result = subprocess.run(
[node_executable, str(script_path)],
check=True,
capture_output=True,
text=True,
)
observed = json.loads(result.stdout)
assert observed == {
"initial": {
"names": ["Enable Audio", "audio", "audioUI"],
"saved": {
"mode": 0,
"widgets_values": [
"voice.wav",
{"position": 1.25, "volume": 0.8},
],
},
},
"off": {
"mode": 4,
"toggle": False,
"saved": {
"mode": 4,
"widgets_values": [
"voice.wav",
{"position": 1.25, "volume": 0.8},
],
},
},
"onAgain": {
"mode": 0,
"toggle": True,
"saved": {
"mode": 0,
"widgets_values": [
"voice.wav",
{"position": 1.25, "volume": 0.8},
],
},
},
"externalBypass": {"mode": 4, "toggle": False},
"reloaded": {
"mode": 4,
"toggle": False,
"audio": "reloaded.wav",
"player": {"position": 2.5, "volume": 0.6},
"names": ["Enable Audio", "audio", "audioUI"],
},
}
def test_easy_load_audio_uses_shared_non_polling_bypass_helper():
source = FRONTEND_PATH.read_text(encoding="utf-8")
common = COMMON_FRONTEND_PATH.read_text(encoding="utf-8")
assert 'from "./easy_bypass_toggle.js"' in source
assert 'widgetName: "Enable Audio"' in source
assert "setInterval" not in common
assert "setTimeout" not in common
assert "node.mode = enabled ? NODE_MODE_ALWAYS : NODE_MODE_BYPASS" in common
+300
View File
@@ -0,0 +1,300 @@
from __future__ import annotations
import importlib.util
import inspect
import json
from pathlib import Path
import shutil
import subprocess
import sys
from types import ModuleType
import pytest
from ComfyUI_H3_Continuum_Join import nodes as root_nodes
from ComfyUI_H3_Continuum_Join.v3.easy_image_nodes import (
H3EasyLoadImage,
NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS,
)
ROOT = Path(__file__).resolve().parents[1]
BACKEND_PATH = ROOT / "v3" / "easy_image_nodes.py"
FRONTEND_PATH = ROOT / "web" / "easy_load_image.js"
COMMON_FRONTEND_PATH = ROOT / "web" / "easy_bypass_toggle.js"
def test_easy_load_image_is_public_and_keeps_core_image_mask_contract():
assert NODE_CLASS_MAPPINGS["H3EasyLoadImage"] is H3EasyLoadImage
assert root_nodes.NODE_CLASS_MAPPINGS["H3EasyLoadImage"] is H3EasyLoadImage
assert NODE_DISPLAY_NAME_MAPPINGS["H3EasyLoadImage"] == "H3 Continuum Load Image"
assert root_nodes.NODE_DISPLAY_NAME_MAPPINGS["H3EasyLoadImage"] == (
"H3 Continuum Load Image"
)
assert H3EasyLoadImage.RETURN_TYPES == ("IMAGE", "MASK")
assert H3EasyLoadImage.FUNCTION == "load_image"
assert H3EasyLoadImage.DEPRECATED is False
assert "def load_image" not in inspect.getsource(H3EasyLoadImage)
def test_easy_load_image_inherits_the_runtime_core_loader(monkeypatch):
fake_core = ModuleType("nodes")
class FakeCoreLoadImage:
RETURN_TYPES = ("IMAGE", "MASK")
FUNCTION = "load_image"
@classmethod
def INPUT_TYPES(cls):
return {"required": {"image": (("core.png",), {"image_upload": True})}}
def load_image(self, image):
return f"image:{image}", f"mask:{image}"
fake_core.LoadImage = FakeCoreLoadImage
monkeypatch.setitem(sys.modules, "nodes", fake_core)
spec = importlib.util.spec_from_file_location("h3_easy_image_runtime_probe", BACKEND_PATH)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
assert issubclass(module.H3EasyLoadImage, FakeCoreLoadImage)
assert module.H3EasyLoadImage.INPUT_TYPES() == FakeCoreLoadImage.INPUT_TYPES()
assert module.H3EasyLoadImage().load_image("core.png") == (
"image:core.png",
"mask:core.png",
)
def _frontend_functions(source: str) -> str:
return source.replace("export ", "")
def test_easy_load_image_frontend_uses_mode_as_single_source_of_truth(tmp_path):
node_executable = shutil.which("node")
if node_executable is None:
pytest.skip("Node.js is required for the frontend behavior regression")
source = COMMON_FRONTEND_PATH.read_text(encoding="utf-8")
functions = _frontend_functions(source)
script = f"""
const EASY_LOAD_IMAGE_CLASS = "H3EasyLoadImage";
{functions}
function plainWidget(name, value) {{
return {{ name, value, options: {{}}, serialize: true }};
}}
const imageWidget = plainWidget("image", "first.png");
const uploadWidget = plainWidget("upload", "image");
const node = {{
comfyClass: EASY_LOAD_IMAGE_CLASS,
mode: NODE_MODE_ALWAYS,
widgets: [imageWidget, uploadWidget],
dirtyCalls: 0,
addWidget(type, name, value, callback, options) {{
const widget = {{ type, name, value, callback, options, serialize: true }};
this.widgets.push(widget);
return widget;
}},
setDirtyCanvas() {{ this.dirtyCalls += 1; }},
serialize() {{
return {{
mode: this.mode,
widgets_values: this.widgets
.filter((widget) => widget.serialize !== false)
.map((widget) => widget.value),
}};
}},
configure(info) {{
this.mode = info.mode;
for (let index = 0; index < info.widgets_values.length; index++) {{
this.widgets[index].value = info.widgets_values[index];
}}
}},
}};
configureEasyBypassToggleNode(node, {{
nodeClass: EASY_LOAD_IMAGE_CLASS,
widgetName: "Enable Image",
tooltip: "image tooltip",
}});
const toggle = findEasyBypassWidget(node);
const initial = {{
names: node.widgets.map((widget) => widget.name),
toggle: toggle.value,
saved: node.serialize(),
}};
toggle.value = false;
toggle.callback(false);
const toggledOff = {{ mode: node.mode, toggle: toggle.value, saved: node.serialize() }};
node.mode = NODE_MODE_ALWAYS;
const externalUnbypass = {{ mode: node.mode, toggle: toggle.value }};
node.mode = NODE_MODE_BYPASS;
const externalBypass = {{ mode: node.mode, toggle: toggle.value }};
node.configure({{ mode: NODE_MODE_BYPASS, widgets_values: ["reloaded.png", "image"] }});
const reloaded = {{
mode: node.mode,
toggle: toggle.value,
image: imageWidget.value,
upload: uploadWidget.value,
names: node.widgets.map((widget) => widget.name),
}};
console.log(JSON.stringify({{ initial, toggledOff, externalUnbypass, externalBypass, reloaded }}));
"""
script_path = tmp_path / "easy-load-image-frontend.js"
script_path.write_text(script, encoding="utf-8")
result = subprocess.run(
[node_executable, str(script_path)],
check=True,
capture_output=True,
text=True,
)
observed = json.loads(result.stdout)
assert observed == {
"initial": {
"names": ["Enable Image", "image", "upload"],
"toggle": True,
"saved": {"mode": 0, "widgets_values": ["first.png", "image"]},
},
"toggledOff": {
"mode": 4,
"toggle": False,
"saved": {"mode": 4, "widgets_values": ["first.png", "image"]},
},
"externalUnbypass": {"mode": 0, "toggle": True},
"externalBypass": {"mode": 4, "toggle": False},
"reloaded": {
"mode": 4,
"toggle": False,
"image": "reloaded.png",
"upload": "image",
"names": ["Enable Image", "image", "upload"],
},
}
def test_shared_bypass_helper_redraws_only_enable_row_at_full_opacity(tmp_path):
node_executable = shutil.which("node")
if node_executable is None:
pytest.skip("Node.js is required for the frontend drawing regression")
functions = _frontend_functions(
COMMON_FRONTEND_PATH.read_text(encoding="utf-8")
)
script = f"""
{functions}
function widget(name, value) {{
return {{ name, value, options: {{}}, serialize: true }};
}}
function nodeFor(nodeClass, enableName, existing) {{
const enable = existing ? widget(enableName, false) : undefined;
const node = {{
comfyClass: nodeClass,
mode: NODE_MODE_ALWAYS,
widgets: existing ? [enable, widget("file", "media.bin")] : [widget("file", "media.bin")],
drawCalls: [],
addWidget(type, name, value, callback, options) {{
const created = {{ type, name, value, callback, options, serialize: true }};
this.widgets.push(created);
return created;
}},
drawWidgets(ctx, options) {{
this.drawCalls.push({{
names: this.widgets.map((item) => item.name),
alpha: options.editorAlpha,
}});
}},
setDirtyCanvas() {{}},
}};
if (existing) {{
configureExistingEasyBypassWidgetNode(node, {{
nodeClass,
widgetNames: [enableName],
}});
}} else {{
configureEasyBypassToggleNode(node, {{
nodeClass,
widgetName: enableName,
tooltip: "enable tooltip",
}});
node.mode = NODE_MODE_BYPASS;
}}
const toggle = findEasyBypassWidget(node);
node.drawWidgets({{}}, {{ editorAlpha: 0.2, lowQuality: false }});
const bypassCalls = node.drawCalls.slice();
toggle.callback(true);
node.drawCalls = [];
node.drawWidgets({{}}, {{ editorAlpha: 1, lowQuality: false }});
return {{
bypassCalls,
enabledCalls: node.drawCalls,
mode: node.mode,
toggle: toggle.value,
clickable: typeof toggle.callback === "function",
visible: toggle.hidden !== true,
}};
}}
console.log(JSON.stringify({{
image: nodeFor("H3EasyLoadImage", "Enable Image", false),
audio: nodeFor("H3EasyLoadAudio", "Enable Audio", false),
video: nodeFor("H3ContinuumLoadVideo", "enable_video", true),
}}));
"""
script_path = tmp_path / "easy-loader-bypass-foreground.js"
script_path.write_text(script, encoding="utf-8")
result = subprocess.run(
[node_executable, str(script_path)],
check=True,
capture_output=True,
text=True,
)
observed = json.loads(result.stdout)
assert observed == {
"image": {
"bypassCalls": [
{"names": ["Enable Image", "file"], "alpha": 0.2},
{"names": ["Enable Image"], "alpha": 1},
],
"enabledCalls": [
{"names": ["Enable Image", "file"], "alpha": 1}
],
"mode": 0,
"toggle": True,
"clickable": True,
"visible": True,
},
"audio": {
"bypassCalls": [
{"names": ["Enable Audio", "file"], "alpha": 0.2},
{"names": ["Enable Audio"], "alpha": 1},
],
"enabledCalls": [
{"names": ["Enable Audio", "file"], "alpha": 1}
],
"mode": 0,
"toggle": True,
"clickable": True,
"visible": True,
},
"video": {
"bypassCalls": [
{"names": ["enable_video", "file"], "alpha": 0.2},
{"names": ["enable_video"], "alpha": 1},
],
"enabledCalls": [
{"names": ["enable_video", "file"], "alpha": 1}
],
"mode": 0,
"toggle": True,
"clickable": True,
"visible": True,
},
}
def test_easy_load_image_frontend_has_no_backend_boolean_or_polling():
source = FRONTEND_PATH.read_text(encoding="utf-8")
common = COMMON_FRONTEND_PATH.read_text(encoding="utf-8")
assert "setInterval" not in common
assert "setTimeout" not in common
assert "node.mode = enabled ? NODE_MODE_ALWAYS : NODE_MODE_BYPASS" in common
assert "widget.options.serialize = false" in common
assert 'from "./easy_bypass_toggle.js"' in source
assert "configureEasyBypassToggleNode" in source
+345
View File
@@ -0,0 +1,345 @@
from __future__ import annotations
from fractions import Fraction
import inspect
import json
import os
from pathlib import Path
import shutil
import subprocess
from types import SimpleNamespace
import pytest
import torch
from ComfyUI_H3_Continuum_Join import nodes as root_nodes
from ComfyUI_H3_Continuum_Join.v3 import easy_video_nodes as video_nodes
from ComfyUI_H3_Continuum_Join.v3.easy_video_nodes import (
ExecutionBlocker,
H3ContinuumLoadVideo,
NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS,
_resample_video_frames,
load_video_components,
)
ROOT = Path(__file__).resolve().parents[1]
COMMON_FRONTEND_PATH = ROOT / "web" / "easy_bypass_toggle.js"
FRONTEND_PATH = ROOT / "web" / "easy_load_video.js"
def _frames(count: int) -> torch.Tensor:
values = torch.arange(count, dtype=torch.float32).view(count, 1, 1, 1)
return values.expand(-1, 2, 2, 3).clone()
def test_schema_registration_and_minimal_core_contract():
schema = H3ContinuumLoadVideo.define_schema()
assert NODE_CLASS_MAPPINGS["H3ContinuumLoadVideo"] is H3ContinuumLoadVideo
assert root_nodes.NODE_CLASS_MAPPINGS["H3ContinuumLoadVideo"] is (
H3ContinuumLoadVideo
)
assert NODE_DISPLAY_NAME_MAPPINGS["H3ContinuumLoadVideo"] == (
"H3 Continuum Load Video"
)
assert schema.node_id == "H3ContinuumLoadVideo"
assert schema.display_name == "H3 Continuum Load Video"
assert schema.category == "MiniMax H3/Continuum"
assert [item.id for item in schema.inputs] == [
"enable_video",
"file",
"force_rate",
]
assert schema.inputs[0].default is True
assert schema.inputs[1].upload.value == "video_upload"
assert schema.inputs[2].default == 24.0
assert schema.inputs[2].min == 0.0
assert schema.inputs[2].max == 120.0
assert schema.inputs[2].step == 0.01
assert len(schema.outputs) == 2
source = inspect.getsource(video_nodes)
assert "InputImpl.VideoFromFile" in source
assert "import av" not in source
assert "subprocess" not in source
def test_24_to_24_returns_the_identical_image_batch():
images = _frames(240)
result = _resample_video_frames(images, Fraction(24, 1), 24.0)
assert result is images
def test_30_to_24_preserves_ten_second_duration():
result = _resample_video_frames(_frames(300), Fraction(30, 1), 24.0)
assert result.shape[0] == 240
assert result.shape[0] / 24.0 == 10.0
def test_24_to_30_preserves_duration_and_duplicates_frames():
result = _resample_video_frames(_frames(240), Fraction(24, 1), 30.0)
assert result.shape[0] == 300
assert result.shape[0] / 30.0 == 10.0
source_values = result[:, 0, 0, 0]
assert torch.unique(source_values).numel() == 240
def test_2997_to_24_uses_fraction_without_off_by_one():
result = _resample_video_frames(
_frames(300),
Fraction(30_000, 1_001),
24.0,
)
assert result.shape[0] == 240
def test_force_rate_zero_returns_the_identical_image_batch():
images = _frames(123)
result = _resample_video_frames(images, Fraction(30_000, 1_001), 0.0)
assert result is images
def test_audio_is_bit_exact_and_core_components_are_used(monkeypatch):
images = _frames(300)
waveform = torch.linspace(-1.0, 1.0, 64).reshape(1, 1, 64)
audio = {"waveform": waveform, "sample_rate": 32_000}
calls = []
class FakeVideo:
def get_components(self):
calls.append("get_components")
return SimpleNamespace(
images=images,
audio=audio,
frame_rate=Fraction(30, 1),
)
def fake_video_from_file(path):
calls.append(("VideoFromFile", path))
return FakeVideo()
monkeypatch.setattr(
video_nodes.folder_paths,
"get_annotated_filepath",
lambda file: f"D:/input/{file}",
)
monkeypatch.setattr(video_nodes.InputImpl, "VideoFromFile", fake_video_from_file)
output_images, output_audio = load_video_components(
file="source.mp4",
enable_video=True,
force_rate=24.0,
)
assert output_images.shape[0] == 240
assert output_audio is audio
assert output_audio["sample_rate"] == 32_000
assert output_audio["waveform"].shape == waveform.shape
assert torch.equal(output_audio["waveform"], waveform)
assert calls == [("VideoFromFile", "D:/input/source.mp4"), "get_components"]
def test_enable_video_off_never_resolves_or_decodes(monkeypatch):
def forbidden(*args, **kwargs):
raise AssertionError("disabled video must not touch Core decode or the file")
monkeypatch.setattr(video_nodes.folder_paths, "get_annotated_filepath", forbidden)
monkeypatch.setattr(video_nodes.InputImpl, "VideoFromFile", forbidden)
image, audio = load_video_components(
file="missing-old-file.mp4",
enable_video=False,
force_rate=24.0,
)
assert isinstance(image, ExecutionBlocker)
assert isinstance(audio, ExecutionBlocker)
assert image.message is None
assert audio.message is None
def test_audio_missing_blocks_only_audio_branch(monkeypatch):
images = _frames(24)
class FakeVideo:
def get_components(self):
return SimpleNamespace(
images=images,
audio=None,
frame_rate=Fraction(24, 1),
)
monkeypatch.setattr(
video_nodes.folder_paths,
"get_annotated_filepath",
lambda file: f"D:/input/{file}",
)
monkeypatch.setattr(
video_nodes.InputImpl,
"VideoFromFile",
lambda path: FakeVideo(),
)
output_images, output_audio = load_video_components(
file="silent.mp4",
enable_video=True,
force_rate=24.0,
)
assert output_images is images
assert isinstance(output_audio, ExecutionBlocker)
assert output_audio.message is None
def test_validation_and_fingerprint_skip_stale_file_when_disabled(
monkeypatch,
tmp_path: Path,
):
calls = []
def exists(file):
calls.append(("exists", file))
return file == "valid.mp4"
monkeypatch.setattr(video_nodes.folder_paths, "exists_annotated_filepath", exists)
assert H3ContinuumLoadVideo.validate_inputs(False, "missing.mp4", 24.0) is True
assert calls == []
disabled_fingerprint = H3ContinuumLoadVideo.fingerprint_inputs(
False,
"missing.mp4",
24.0,
)
assert disabled_fingerprint == (False, "missing.mp4", 24.0, None)
assert calls == []
invalid = H3ContinuumLoadVideo.validate_inputs(True, "missing.mp4", 24.0)
assert invalid == "Invalid video file: missing.mp4"
assert H3ContinuumLoadVideo.validate_inputs(True, "valid.mp4", 24.0) is True
video_path = tmp_path / "valid.mp4"
video_path.write_bytes(b"video")
monkeypatch.setattr(
video_nodes.folder_paths,
"get_annotated_filepath",
lambda file: str(video_path),
)
fingerprint = H3ContinuumLoadVideo.fingerprint_inputs(
True,
"valid.mp4",
30.0,
)
assert fingerprint[:3] == (True, "valid.mp4", 30.0)
assert fingerprint[3] == os.path.getmtime(video_path)
def test_enable_video_false_uses_native_bypass_appearance(tmp_path):
node_executable = shutil.which("node")
if node_executable is None:
pytest.skip("Node.js is required for the frontend behavior regression")
functions = COMMON_FRONTEND_PATH.read_text(encoding="utf-8").replace(
"export ", ""
)
script = f"""
{functions}
function plainWidget(name, value) {{
return {{ name, value, options: {{}}, serialize: true }};
}}
const enableWidget = plainWidget("enable_video", false);
const fileWidget = plainWidget("file", "clip.mp4");
const rateWidget = plainWidget("force_rate", 24.0);
const uploadWidget = plainWidget("upload", "video");
const node = {{
comfyClass: "H3ContinuumLoadVideo",
mode: 0,
widgets: [enableWidget, fileWidget, rateWidget, uploadWidget],
dirtyCalls: 0,
setDirtyCanvas() {{ this.dirtyCalls += 1; }},
serialize() {{
return {{
mode: this.mode,
widgets_values: this.widgets.map((widget) => widget.value),
}};
}},
configure(info) {{
this.mode = info.mode;
for (let index = 0; index < info.widgets_values.length; index++) {{
this.widgets[index].value = info.widgets_values[index];
}}
}},
}};
configureExistingEasyBypassWidgetNode(node, {{
nodeClass: "H3ContinuumLoadVideo",
widgetNames: ["enable_video", "Enable Video"],
}});
const initial = {{
mode: node.mode,
enabled: enableWidget.value,
names: node.widgets.map((widget) => widget.name),
saved: node.serialize(),
}};
enableWidget.callback(true);
const enabled = {{ mode: node.mode, enabled: enableWidget.value }};
node.mode = 4;
const externalBypass = {{ mode: node.mode, enabled: enableWidget.value }};
node.mode = 0;
const externalUnbypass = {{ mode: node.mode, enabled: enableWidget.value }};
node.configure({{
mode: 0,
widgets_values: [false, "reloaded.mp4", 30.0, "video"],
}});
configureExistingEasyBypassWidgetNode(node, {{
nodeClass: "H3ContinuumLoadVideo",
widgetNames: ["enable_video", "Enable Video"],
}});
const reloaded = {{
mode: node.mode,
enabled: enableWidget.value,
file: fileWidget.value,
rate: rateWidget.value,
names: node.widgets.map((widget) => widget.name),
saved: node.serialize(),
}};
console.log(JSON.stringify({{ initial, enabled, externalBypass, externalUnbypass, reloaded }}));
"""
script_path = tmp_path / "easy-load-video-frontend.js"
script_path.write_text(script, encoding="utf-8")
result = subprocess.run(
[node_executable, str(script_path)],
check=True,
capture_output=True,
text=True,
)
observed = json.loads(result.stdout)
assert observed == {
"initial": {
"mode": 4,
"enabled": False,
"names": ["enable_video", "file", "force_rate", "upload"],
"saved": {
"mode": 4,
"widgets_values": [False, "clip.mp4", 24, "video"],
},
},
"enabled": {"mode": 0, "enabled": True},
"externalBypass": {"mode": 4, "enabled": False},
"externalUnbypass": {"mode": 0, "enabled": True},
"reloaded": {
"mode": 4,
"enabled": False,
"file": "reloaded.mp4",
"rate": 30,
"names": ["enable_video", "file", "force_rate", "upload"],
"saved": {
"mode": 4,
"widgets_values": [False, "reloaded.mp4", 30, "video"],
},
},
}
def test_video_bypass_appearance_uses_native_mode_without_hardcoded_color():
source = FRONTEND_PATH.read_text(encoding="utf-8")
common = COMMON_FRONTEND_PATH.read_text(encoding="utf-8")
assert 'from "./easy_bypass_toggle.js"' in source
assert "configureExistingEasyBypassWidgetNode" in source
assert 'widgetNames: ["enable_video", "Enable Video"]' in source
assert "NODE_MODE_BYPASS" in common
assert "node.color" not in source
assert "node.bgcolor" not in source
assert "setInterval" not in common
assert "setTimeout" not in common
+313
View File
@@ -0,0 +1,313 @@
from __future__ import annotations
import importlib.util
from pathlib import Path
import sys
import numpy as np
import torch
TOOLS = Path(__file__).parents[1] / "tools"
def _load(name: str, filename: str):
path = TOOLS / filename
spec = importlib.util.spec_from_file_location(name, path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return module
runner = _load("h3_issue13_r25_gate_runner", "issue13_r25_gate_runner.py")
analyzer = _load("h3_issue13_r25_analyze", "issue13_r2_analyze.py")
soft_reanchor = _load(
"h3_issue13_soft_reanchor",
"gpu_diagnostic_node/soft_reanchor.py",
)
def _source_prompt() -> dict:
return {
"114": {"inputs": {"image": "old.png"}},
"119": {"inputs": {}},
"139": {"inputs": {"sampler_name": "res_multistep"}},
"150": {"inputs": {"enabled": True}},
"153": {"inputs": {"scheduler": "old", "steps": 20, "denoise": 0.5}},
"188": {"inputs": {"value": "old"}},
"191": {"inputs": {}},
"249": {"inputs": {}},
"286": {
"inputs": {
"lora_1": {"on": True, "lora": "old.safetensors", "strength": 1.0}
}
},
"297": {"inputs": {"value": 0.3}},
"305": {
"class_type": "H3ContinuumSamplerV37",
"inputs": {
"continuation_backend": "Standard",
"generation_mode": "Full Run",
"review_action": "Continue / Next",
"guide": ["900", 0],
"last_frame": ["901", 0],
},
},
"306": {"inputs": {}},
}
def test_screening_order_and_contract_are_fixed():
assert tuple(runner.CASE_SPECS)[:3] == (
"screen_3x5_turbo",
"screen_3x10_turbo",
"screen_6x5_turbo",
)
prompt, loras = runner.configure_prompt(
_source_prompt(),
case="screen_3x10_turbo",
output_prefix="video/test",
image_name="closeup.png",
seed=131325,
width=576,
height=864,
diagnostic_nonce=7,
)
inputs = prompt["305"]["inputs"]
assert inputs["chunks"] == 3
assert inputs["chunk_seconds"] == 10.0
assert inputs["width"] == 576
assert inputs["height"] == 864
assert prompt["139"]["inputs"]["sampler_name"] == "euler"
assert prompt["153"]["inputs"]["steps"] == 8
assert prompt["153"]["inputs"]["scheduler"] == "simple"
assert prompt["114"]["inputs"]["image"] == "closeup.png"
assert loras == [{"name": runner.TURBO_LORA, "strength": 1.0}]
assert prompt["188"]["inputs"]["value"].count("\n---\n") == 2
assert "dynv2" not in prompt["188"]["inputs"]["value"]
def test_six_by_five_uses_six_motion_steps():
prompt, _ = runner.configure_prompt(
_source_prompt(),
case="screen_6x5_turbo",
output_prefix="video/test",
image_name="closeup.png",
seed=1,
width=576,
height=864,
diagnostic_nonce=8,
)
assert prompt["305"]["inputs"]["chunks"] == 6
assert prompt["188"]["inputs"]["value"].count("\n---\n") == 5
def test_six_by_five_fixed_prompt_repeats_one_prompt():
prompt, loras = runner.configure_prompt(
_source_prompt(),
case="screen_6x5_turbo_fixed_prompt",
output_prefix="video/issue13_r26/fixed",
image_name="closeup.png",
seed=131325,
width=576,
height=864,
diagnostic_nonce=132600,
)
prompts = prompt["188"]["inputs"]["value"].split("\n---\n")
assert len(prompts) == 6
assert len(set(prompts)) == 1
assert prompt["305"]["inputs"]["chunks"] == 6
assert prompt["305"]["inputs"]["chunk_seconds"] == 5.0
assert prompt["153"]["inputs"]["steps"] == 8
assert loras == [{"name": runner.TURBO_LORA, "strength": 1.0}]
def test_six_by_five_fixed_prefix_changes_only_diagnostic_source_mode():
source = _source_prompt()
recursive, _ = runner.configure_prompt(
source,
case="screen_6x5_turbo_fixed_prompt",
output_prefix="video/issue13_r26/recursive",
image_name="closeup.png",
seed=131325,
width=576,
height=864,
diagnostic_nonce=132600,
)
fixed, _ = runner.configure_prompt(
source,
case="screen_6x5_turbo_fixed_prefix",
output_prefix="video/issue13_r26/fixed-prefix",
image_name="closeup.png",
seed=131325,
width=576,
height=864,
diagnostic_nonce=132601,
)
recursive_inputs = recursive["305"]["inputs"]
fixed_inputs = fixed["305"]["inputs"]
assert recursive_inputs["continuation_source_mode"] == "Recursive"
assert fixed_inputs["continuation_source_mode"] == "Fixed Group 1 Tail"
ignored = {"continuation_source_mode", "diagnostic_nonce"}
assert {
key: value for key, value in recursive_inputs.items() if key not in ignored
} == {key: value for key, value in fixed_inputs.items() if key not in ignored}
assert recursive["188"]["inputs"]["value"] == fixed["188"]["inputs"]["value"]
def test_six_by_five_soft_reanchor_changes_only_diagnostic_source_mode():
source = _source_prompt()
recursive, _ = runner.configure_prompt(
source,
case="screen_6x5_turbo_fixed_prompt",
output_prefix="video/issue13_r27/recursive",
image_name="closeup.png",
seed=131325,
width=576,
height=864,
diagnostic_nonce=132700,
)
reanchored, _ = runner.configure_prompt(
source,
case="screen_6x5_turbo_soft_reanchor",
output_prefix="video/issue13_r27/soft-reanchor",
image_name="closeup.png",
seed=131325,
width=576,
height=864,
diagnostic_nonce=132701,
)
recursive_inputs = recursive["305"]["inputs"]
reanchored_inputs = reanchored["305"]["inputs"]
assert recursive_inputs["continuation_source_mode"] == "Recursive"
assert reanchored_inputs["continuation_source_mode"] == "Soft Re-anchor Group 4"
ignored = {"continuation_source_mode", "diagnostic_nonce"}
assert {
key: value for key, value in recursive_inputs.items() if key not in ignored
} == {key: value for key, value in reanchored_inputs.items() if key not in ignored}
assert recursive["188"]["inputs"]["value"] == reanchored["188"]["inputs"]["value"]
def test_soft_reanchor_moves_global_appearance_halfway_without_geometry_change():
current = torch.zeros((1, 4, 8, 8, 3), dtype=torch.float32)
current[..., 0] = 0.8
current[..., 1] = 0.3
current[..., 2] = 0.2
reference = torch.zeros_like(current)
reference[..., 0] = 0.4
reference[..., 1] = 0.5
reference[..., 2] = 0.6
adjusted, report = soft_reanchor.soft_match_rgb_appearance(
current,
reference,
strength=0.5,
)
assert adjusted.shape == current.shape
assert torch.equal(current[..., 0], torch.full_like(current[..., 0], 0.8))
before_gap = abs(
report["before"]["luma_mean"] - report["reference"]["luma_mean"]
)
after_gap = abs(
report["after"]["luma_mean"] - report["reference"]["luma_mean"]
)
assert after_gap < before_gap
assert report["strength"] == 0.5
assert report["geometry_unchanged"] is True
def test_soft_reanchor_vae_roundtrip_preserves_shape_and_inputs():
class FakeVideoVAE:
def decode(self, latent):
value = float(latent.mean().item())
pixels = torch.full((1, 22, 32, 32, 3), value, dtype=torch.float32)
pixels[..., 0] = value + 0.1
return pixels.clamp(0.0, 1.0)
def encode(self, pixels):
value = float(pixels.mean().item())
return torch.full((1, 24, 7, 2, 2), value, dtype=torch.float32)
current = torch.full((1, 24, 7, 2, 2), 0.7, dtype=torch.float32)
reference = torch.full((1, 24, 7, 2, 2), 0.3, dtype=torch.float32)
current_before = current.clone()
reference_before = reference.clone()
encoded, report = soft_reanchor.soft_reanchor_context(
current,
reference,
video_vae=FakeVideoVAE(),
strength=0.5,
)
assert encoded.shape == current.shape
assert encoded.dtype == current.dtype
assert torch.isfinite(encoded).all()
assert torch.equal(current, current_before)
assert torch.equal(reference, reference_before)
assert report["current_context_unchanged"] is True
assert report["reference_context_unchanged"] is True
assert report["latent_shape_unchanged"] is True
def test_boundary_metrics_report_flow_and_frame_jump():
frames = []
for index in range(12):
frame = np.zeros((24, 24, 3), dtype=np.uint8)
frame[:, max(0, min(20, index)) : max(1, min(24, index + 4))] = 80
if index >= 6:
frame = np.clip(frame + 80, 0, 255).astype(np.uint8)
frames.append(frame)
rows = analyzer._boundary_metrics(frames, chunks=2)
assert len(rows) == 1
assert rows[0]["target_group"] == 2
assert rows[0]["frame_mae"] > 0.0
assert rows[0]["trajectory_flow_discontinuity"] >= 0.0
def test_motion_pair_ab_uses_normal_twenty_step_and_no_turbo():
off, off_loras = runner.configure_prompt(
_source_prompt(),
case="motion_off_3x5_normal",
output_prefix="video/test",
image_name="closeup.png",
seed=1,
width=576,
height=864,
diagnostic_nonce=9,
)
both, both_loras = runner.configure_prompt(
_source_prompt(),
case="motion_both_3x5_normal",
output_prefix="video/test",
image_name="closeup.png",
seed=1,
width=576,
height=864,
diagnostic_nonce=10,
)
assert off_loras == []
assert off["153"]["inputs"]["steps"] == 20
assert "dynv2" in off["188"]["inputs"]["value"]
assert [item["name"] for item in both_loras] == [
runner.MOTION_BOOSTER_LORA,
runner.MOTION_REPAIR_LORA,
]
assert both["153"]["inputs"]["steps"] == 20
assert all(runner.TURBO_LORA != item["name"] for item in both_loras)
def test_continuation_rgb_proxy_uses_pre_boundary_context_window():
frames = [np.full((8, 8, 3), index, dtype=np.uint8) for index in range(30)]
result = analyzer._continuation_input_rgb_proxy(
frames, chunks=3, context_frames=4
)
assert result["context_frames"] == 4
assert len(result["boundaries"]) == 2
first = result["boundaries"][0]
assert first["boundary_frame"] == 10
assert first["window_start"] == 6
assert first["window_end_exclusive"] == 10
assert first["window_frames"] == 4
assert abs(sum(first["luma_histogram"]) - 1.0) < 1e-9
+213
View File
@@ -0,0 +1,213 @@
from __future__ import annotations
import importlib.util
from pathlib import Path
import sys
import torch
TOOLS = Path(__file__).parents[1] / "tools"
def _load(name: str, filename: str):
path = TOOLS / filename
spec = importlib.util.spec_from_file_location(name, path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return module
policy_module = _load(
"h3_issue13_r28_continuation_policy",
"gpu_diagnostic_node/continuation_policy.py",
)
runner = _load("h3_issue13_r28_gate_runner", "issue13_r28_gate_runner.py")
analyzer = _load("h3_issue13_r28_analyze", "issue13_r28_analyze.py")
class FakeNested:
def __init__(self, tensors):
self.tensors = tuple(tensors)
def unbind(self):
return self.tensors
def _summary(tensor: torch.Tensor) -> dict:
return {
"shape": [int(value) for value in tensor.shape],
"mean": float(tensor.float().mean().item()),
}
def _latent():
video = torch.randn((1, 24, 42, 4, 4), generator=torch.Generator().manual_seed(1))
audio = torch.randn((1, 32, 2, 235), generator=torch.Generator().manual_seed(2))
video_mask = torch.ones((1, 1, 42, 4, 4), dtype=torch.float32)
video_mask[:, :, :7] = 0.0
audio_mask = torch.ones((1, 1, 2, 235), dtype=torch.float32)
audio_mask[..., :37] = 0.0
return {
"samples": FakeNested((video, audio)),
"noise_mask": FakeNested((video_mask, audio_mask)),
}
def _apply(mode: str):
latent = _latent()
original_samples = latent["samples"]
original_video_mask, original_audio_mask = [
value.clone() for value in latent["noise_mask"].unbind()
]
policy = policy_module.R28ContinuationPolicy(mode, tensor_summary=_summary)
result = policy.prepare_masked_latent(
latent=latent,
physical_group=2,
logical_chunks=(2,),
context_frames=22,
video_context=torch.zeros((1, 24, 7, 4, 4)),
audio_context=torch.zeros((1, 32, 2, 37)),
)
assert result["samples"] is original_samples
assert torch.equal(latent["noise_mask"].unbind()[0], original_video_mask)
assert torch.equal(latent["noise_mask"].unbind()[1], original_audio_mask)
return policy, result
def test_depth_13_uses_last_four_slots_and_preserves_audio_contract():
policy, result = _apply(policy_module.MODE_DEPTH_13)
video_mask, audio_mask = result["noise_mask"].unbind()
assert policy.active_video_slots == 4
assert policy.active_video_frames == 13
assert torch.all(video_mask[:, :, :3] == 1)
assert torch.all(video_mask[:, :, 3:7] == 0)
assert torch.all(video_mask[:, :, 7:] == 1)
assert torch.all(audio_mask[..., :37] == 0)
assert torch.all(audio_mask[..., 37:] == 1)
def test_depth_9_uses_last_three_slots_only():
policy, result = _apply(policy_module.MODE_DEPTH_9)
video_mask, _ = result["noise_mask"].unbind()
assert policy.active_video_slots == 3
assert policy.active_video_frames == 9
assert torch.all(video_mask[:, :, :4] == 1)
assert torch.all(video_mask[:, :, 4:7] == 0)
def test_strength_75_uses_core_fractional_mask_without_scaling_latent():
latent = _latent()
source_video, source_audio = latent["samples"].unbind()
source_video_before = source_video.clone()
source_audio_before = source_audio.clone()
policy = policy_module.R28ContinuationPolicy(
policy_module.MODE_STRENGTH_75, tensor_summary=_summary
)
result = policy.prepare_masked_latent(
latent=latent,
physical_group=2,
logical_chunks=(2,),
context_frames=22,
video_context=torch.zeros((1, 24, 7, 4, 4)),
audio_context=torch.zeros((1, 32, 2, 37)),
)
video_mask, audio_mask = result["noise_mask"].unbind()
assert torch.all(video_mask[:, :, :7] == 0.25)
assert torch.all(audio_mask[..., :37] == 0)
assert torch.equal(source_video, source_video_before)
assert torch.equal(source_audio, source_audio_before)
def test_baseline_returns_original_latent_and_mask_objects():
latent = _latent()
policy = policy_module.R28ContinuationPolicy(
policy_module.MODE_BASELINE_22, tensor_summary=_summary
)
result = policy.prepare_masked_latent(
latent=latent,
physical_group=2,
logical_chunks=(2,),
context_frames=22,
video_context=torch.zeros((1, 24, 7, 4, 4)),
audio_context=torch.zeros((1, 32, 2, 37)),
)
assert result is latent
assert policy.active_video_slots == 7
assert policy.active_video_frames == 22
def _source_prompt() -> dict:
return {
"114": {"inputs": {"image": "old.png"}},
"119": {"inputs": {}},
"139": {"inputs": {"sampler_name": "old"}},
"150": {"inputs": {"enabled": True}},
"153": {"inputs": {"scheduler": "old", "steps": 20}},
"188": {"inputs": {"value": "old"}},
"191": {"inputs": {}},
"249": {"inputs": {}},
"286": {"inputs": {"lora_1": {"on": False}}},
"297": {"inputs": {"value": 0.3}},
"305": {
"class_type": "H3ContinuumMaskedPrefixR1Diagnostic",
"inputs": {
"continuation_source_mode": "Recursive",
"synchronize_sampling": True,
"last_frame": ["900", 0],
},
},
"306": {"inputs": {}},
}
def test_runner_changes_only_the_approved_r28_experiment_contract():
prompt, loras = runner.configure_prompt(
_source_prompt(),
case="depth_13f",
output_prefix="video/issue13_r28/test",
image_name="closeup.png",
seed=131325,
width=576,
height=864,
diagnostic_nonce=132800,
)
inputs = prompt["305"]["inputs"]
assert prompt["305"]["class_type"] == "H3ContinuumContinuationR28Diagnostic"
assert inputs["continuation_experiment"] == "Video Depth 13f"
assert inputs["continuation_transport"] == "masked_av_prefix_22_v1"
assert inputs["continuity"] == "Balanced — 22 frames"
assert inputs["audio_continuity"] is True
assert inputs["chunks"] == 6
assert inputs["chunk_seconds"] == 5.0
assert "continuation_source_mode" not in inputs
assert "synchronize_sampling" not in inputs
assert "last_frame" not in inputs
assert prompt["188"]["inputs"]["value"].count("\n---\n") == 5
assert len(set(prompt["188"]["inputs"]["value"].split("\n---\n"))) == 1
assert loras == [{"name": runner.r25.TURBO_LORA, "strength": 1.0}]
def _analysis_case(scale: float) -> dict:
rows = []
for group in range(1, 7):
row = {key: 0.0 for key in analyzer.base.METRIC_KEYS}
for key in analyzer.DRIFT_KEYS:
row[key] = float(group - 1) * scale
rows.append(row)
return {
"end_trend": analyzer.base._trend(rows, analyzer.base.METRIC_KEYS),
"boundary_metrics": [
{"trajectory_flow_discontinuity": 0.1} for _ in range(5)
],
}
def test_comparison_marks_a_clean_half_reduction_promising():
result = analyzer._metric_comparison(_analysis_case(1.0), _analysis_case(0.5))
assert result["screening_mean_reduction_percent"] == 50.0
assert result["sharpness_not_worse"] is True
assert result["gradient_not_worse"] is True
assert result["numeric_promising"] is True
+139
View File
@@ -0,0 +1,139 @@
from __future__ import annotations
import importlib.util
from pathlib import Path
import sys
import numpy as np
import pytest
TOOLS = Path(__file__).parents[1] / "tools"
def _load(name: str, filename: str):
path = TOOLS / filename
spec = importlib.util.spec_from_file_location(name, path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return module
runner = _load("h3_issue13_r2_gate_runner", "issue13_r2_gate_runner.py")
analyzer = _load("h3_issue13_r2_analyze", "issue13_r2_analyze.py")
def _source_prompt() -> dict:
return {
"305": {
"class_type": "H3ContinuumSamplerV37",
"inputs": {
"continuation_backend": "Standard",
"generation_mode": "Full Run",
"review_action": "Continue / Next",
"guide": ["900", 0],
"last_frame": ["901", 0],
},
},
"188": {"inputs": {"value": "old"}},
"153": {"inputs": {"scheduler": "old", "steps": 20, "denoise": 0.5}},
"297": {"inputs": {"value": 0.3}},
"306": {"inputs": {}},
"191": {"inputs": {}},
"249": {"inputs": {}},
"150": {"inputs": {"enabled": True}},
"286": {
"inputs": {
"lora_1": {"on": True, "lora": "turbo.safetensors", "strength": 1.0}
}
},
}
def test_g1_configures_reported_six_by_ten_masked_av_baseline():
prompt = runner.configure_prompt(
_source_prompt(),
case="g1_standard_6x10",
output_prefix="video/test",
seed=130013,
steps=8,
size=384,
diagnostic_nonce=7,
)
sampler = prompt["305"]
inputs = sampler["inputs"]
assert sampler["class_type"] == "H3ContinuumMaskedPrefixR1Diagnostic"
assert inputs["chunks"] == 6
assert inputs["chunk_seconds"] == 10.0
assert inputs["continuation_transport"] == "masked_av_prefix_22_v1"
assert inputs["continuity"] == "Balanced — 22 frames"
assert inputs["audio_continuity"] is True
assert inputs["run_storage"] == "Off"
assert "continuation_backend" not in inputs
assert "guide" not in inputs
assert "last_frame" not in inputs
assert prompt["188"]["inputs"]["value"].count("\n---\n") == 5
assert prompt["150"]["inputs"]["enabled"] is False
assert prompt["286"]["inputs"]["lora_1"]["on"] is False
assert prompt["306"]["inputs"]["video_seam"] == "Off"
assert prompt["306"]["inputs"]["audio_seam"] == "Off"
def test_g2_keeps_old_five_by_five_comparison_shape():
prompt = runner.configure_prompt(
_source_prompt(),
case="g2_standard_5x5",
output_prefix="video/test",
seed=130013,
steps=8,
size=384,
diagnostic_nonce=8,
)
inputs = prompt["305"]["inputs"]
assert inputs["chunks"] == 5
assert inputs["chunk_seconds"] == 5.0
assert prompt["188"]["inputs"]["value"].count("\n---\n") == 4
def test_diagnostic_payload_is_extracted_from_status_suffix():
assert runner._diagnostic_from_status(
'Production status\nV3.6-R1 diagnostic: {"transport":"masked_av_prefix_22_v1"}'
) == {"transport": "masked_av_prefix_22_v1"}
def test_decoded_metrics_include_local_sharpness():
frame = np.zeros((32, 32, 3), dtype=np.uint8)
frame[:, 16:] = 255
metrics = analyzer._frame_metrics(frame)
assert metrics["contrast_p95_p05"] == 1.0
assert metrics["sharpness_laplacian_variance"] > 0.0
assert metrics["gradient_mean"] > 0.0
def test_latent_trend_requires_bit_exact_continuation_prefixes():
diagnostic = {
"sample_calls": [
{"sample_number": 1, "output_tail": {"rms": 1.0, "std": 0.5}},
{
"sample_number": 2,
"source_tail": {"rms": 1.0, "std": 0.5},
"output_tail": {"rms": 1.2, "std": 0.7},
},
],
"final_prefix_pairs": [
{
"bit_exact": True,
"audio_bit_exact": True,
"max_abs_diff": 0.0,
"audio_max_abs_diff": 0.0,
}
],
}
result = analyzer._latent_trend(diagnostic)
assert result["all_video_prefix_pairs_bit_exact"] is True
assert result["all_audio_prefix_pairs_bit_exact"] is True
trend = result["streams"]["output_tail"]["trend"]["rms"]
assert trend["last_minus_first"] == pytest.approx(0.2)
assert trend["increase_steps"] == 1
+1 -1
View File
@@ -581,5 +581,5 @@ def test_v35_assembler_is_registered_without_replacing_v34():
H3ContinuumAssembleSeamV35
)
assert NODE_DISPLAY_NAME_MAPPINGS["H3ContinuumAssembleSeamV35"] == (
"H3 Continuum Assemble + Seam V3.5"
"H3 Continuum Finalize"
)
+1 -1
View File
@@ -6,7 +6,7 @@ import tomllib
ROOT = Path(__file__).resolve().parents[1]
EXPECTED_VERSION = "3.7.0"
EXPECTED_VERSION = "3.8.0"
def test_v35_release_metadata_is_consistent():
+113
View File
@@ -0,0 +1,113 @@
"""Run Storage identity must not track Core's normal loading lifecycle."""
import copy
import json
import os
from pathlib import Path
import subprocess
import sys
from types import SimpleNamespace
import torch
from ComfyUI_H3_Continuum_Join.run_storage import (
_hash, _module_signature, _observe, _video_vae_signature,
)
def vae_fixture():
module = torch.nn.Module()
module.encoder = torch.nn.Linear(3, 4, bias=False)
module.decoder = torch.nn.Module()
module.decoder.register_parameter('scale1', torch.nn.Parameter(torch.tensor([0.123456, 0.654321, 1.234567])))
module.decoder.proj = torch.nn.Linear(4, 3, bias=False)
module.decoder.scale1_comfy_model_dtype = torch.float16
return SimpleNamespace(first_stage_model=module, patcher=None, vae_dtype=torch.float16)
def test_video_vae_identity_survives_core_lazy_cast_without_mutation():
vae = vae_fixture()
before_tensors = {n: p.detach().clone() for n, p in vae.first_stage_model.named_parameters()}
rng = torch.random.get_rng_state().clone()
cold, cold_safe = _video_vae_signature(vae, required=True)
assert cold_safe
assert torch.equal(rng, torch.random.get_rng_state())
assert all(torch.equal(before_tensors[n], p) for n, p in vae.first_stage_model.named_parameters())
assert vae.first_stage_model.decoder.scale1.dtype == torch.float32
# Same assignment as Core DynamicVRAM load, not a Continuum mutation.
vae.first_stage_model.decoder.scale1 = torch.nn.Parameter(vae.first_stage_model.decoder.scale1.detach().half())
warm, warm_safe = _video_vae_signature(vae, required=True)
assert warm_safe and cold == warm
assert not torch.cuda.is_initialized()
def test_video_vae_real_weight_change_is_still_detected():
vae = vae_fixture()
before, _ = _video_vae_signature(vae, required=True)
with torch.no_grad():
vae.first_stage_model.decoder.scale1.add_(0.25)
after, _ = _video_vae_signature(vae, required=True)
assert before != after
def test_declared_precision_change_is_not_ignored():
vae = vae_fixture()
before, _ = _video_vae_signature(vae, required=True)
vae.first_stage_model.decoder.scale1_comfy_model_dtype = torch.bfloat16
after, _ = _video_vae_signature(vae, required=True)
assert before != after
def test_no_core_dtype_metadata_preserves_original_probe_contract():
module = torch.nn.Linear(3, 2, bias=False)
before, safe = _module_signature(module)
assert safe and before['weight_probe'][0]['dtype'] == 'torch.float32'
after, safe = _module_signature(copy.deepcopy(module).half())
assert safe and before != after
def test_set_identity_is_complete_order_independent_and_typed():
keys = {f'layer.{i}.lora_A.weight' for i in range(500)}
before = copy.deepcopy(keys)
a, safe = _observe(keys)
b, other_safe = _observe(set(reversed(sorted(keys))))
assert safe and other_safe and a == b and keys == before
assert len(a['items']) == 500
changed, _ = _observe(keys | {'different.weight'})
frozen, _ = _observe(frozenset(keys))
assert a != changed and a != frozen
assert _observe([1, 2])[0] != _observe([2, 1])[0]
def test_adapter_weight_and_strength_changes_are_not_hidden_by_set_fix():
adapter = SimpleNamespace(loaded_keys={'b', 'a'}, weights=[torch.arange(8.), 8.])
before, safe = _observe([(1., adapter)])
assert safe
adapter.weights[0][0] += 1
after, safe = _observe([(1., adapter)])
assert safe and before != after
assert after != _observe([(0.5, adapter)])[0]
def test_lora_set_identity_matches_across_python_hash_seeds():
root = str(Path(__file__).resolve().parents[1])
code = f'''
import sys, types, json
p = types.ModuleType("ComfyUI_H3_Continuum_Join")
p.__path__ = [{root!r}]
sys.modules[p.__name__] = p
from ComfyUI_H3_Continuum_Join.run_storage import _observe, _hash
from types import SimpleNamespace
import torch
obj = SimpleNamespace(loaded_keys={{f"layer.{{i}}.lora_A.weight" for i in range(500)}}, weights=[torch.arange(8.), 8.])
value, safe = _observe(obj)
assert safe and not torch.cuda.is_initialized()
print("RESULT:" + json.dumps({{"sha": _hash(value), "safe": safe}}))
'''
results = []
for seed in ('1', '777'):
env = dict(os.environ, PYTHONHASHSEED=seed)
run = subprocess.run([sys.executable, '-B', '-c', code], env=env, capture_output=True, text=True, timeout=30, check=True)
records = [line[7:] for line in run.stdout.splitlines() if line.startswith('RESULT:')]
assert len(records) == 1, run.stdout
results.append(json.loads(records[0]))
assert results[0] == results[1]
+50
View File
@@ -0,0 +1,50 @@
"""Real on-disk provenance must not bypass a newly requested reroll."""
import pytest
import importlib.util
from pathlib import Path
_spec = importlib.util.spec_from_file_location(
"review_storage_fixtures", Path(__file__).with_name("test_v38_review_run_storage.py"))
_fixtures = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_fixtures)
_contract, _controller, _persist = _fixtures._contract, _fixtures._controller, _fixtures._persist
@pytest.mark.parametrize("boundary", [1, 2, 3, 4, 5, 6])
def test_new_reroll_only_reuses_chunks_before_boundary(tmp_path, boundary):
old = _persist(tmp_path, _contract(chunks=6), prefix=6, review_unit=(6, 6),
updated_utc="2026-09-07T00:00:00+00:00")
requested = _contract(chunks=6, boundary=boundary, nonce=1)
current = _controller(tmp_path, requested)
entries, records = current._valid_provenance_prefix(
old.manifest, current_contract=requested, enforce_sampling_contract=True)
assert len(entries) == len(records) == boundary - 1
assert len(old.manifest["chunks"]) == 6
def test_same_nonce_interrupted_prefix_can_resume(tmp_path):
contract = _contract(chunks=6, boundary=2, nonce=1)
old = _persist(tmp_path, contract, prefix=3, review_unit=(3, 3),
updated_utc="2026-09-07T00:00:00+00:00")
current = _controller(tmp_path, contract)
entries, records = current._valid_provenance_prefix(
old.manifest, current_contract=contract, enforce_sampling_contract=True)
assert len(entries) == len(records) == 3
def test_completed_same_contract_still_reuses_all(tmp_path):
contract = _contract(chunks=2)
old = _persist(tmp_path, contract, prefix=2, review_unit=(2, 2),
updated_utc="2026-09-07T00:00:00+00:00")
current = _controller(tmp_path, contract)
assert len(current._valid_provenance_prefix(
old.manifest, current_contract=contract, enforce_sampling_contract=True)[0]) == 2
def test_smart_retry_new_nonce_does_not_reuse_previous_take(tmp_path):
old = _persist(tmp_path, _contract(chunks=3, boundary=2, nonce=1),
prefix=2, review_unit=(2, 2), updated_utc="2026-09-07T00:00:00+00:00")
contract = _contract(chunks=3, boundary=2, nonce=2)
current = _controller(tmp_path, contract)
assert len(current._valid_provenance_prefix(
old.manifest, current_contract=contract, enforce_sampling_contract=True)[0]) == 1
+2 -6
View File
@@ -83,12 +83,8 @@ def test_v33_unifies_optional_timeline_video_and_keeps_v324_schema():
from ComfyUI_H3_Continuum_Join import nodes as root_nodes
assert root_nodes.NODE_DISPLAY_NAME_MAPPINGS["H3ContinuumSamplerTimelineVideo"] == (
"[Legacy] H3 Continuum Sampler V3.3"
)
assert root_nodes.NODE_DISPLAY_NAME_MAPPINGS["H3ContinuumSamplerProduction"] == (
"[Legacy] H3 Continuum Sampler V3.2.4"
)
assert "H3ContinuumSamplerTimelineVideo" not in root_nodes.NODE_CLASS_MAPPINGS
assert "H3ContinuumSamplerProduction" not in root_nodes.NODE_CLASS_MAPPINGS
def test_timeline_node_without_video_delegates_to_stable_engine(monkeypatch):
+1 -1
View File
@@ -145,4 +145,4 @@ def test_v217_result_pack_expands_legacy_outputs():
def test_v217_has_no_frontend_display_controller():
assert not (ROOT / "web" / "h3_continuum_v2.js").exists()
version_source = (ROOT / "version.py").read_text(encoding="utf-8")
assert 'PACKAGE_VERSION = "3.7.0"' in version_source
assert 'PACKAGE_VERSION = "3.8.0"' in version_source
+2 -7
View File
@@ -2,16 +2,11 @@ from ComfyUI_H3_Continuum_Join.constants import (
PROMPT_FORMAT_OPTIONS,
SEAM_CORRECTION_AUTO,
)
from ComfyUI_H3_Continuum_Join.nodes import NODE_CLASS_MAPPINGS
from ComfyUI_H3_Continuum_Join.v2.nodes import NODE_CLASS_MAPPINGS
def test_v2_nodes_are_registered_without_removing_v1():
def test_v2_nodes_remain_available_in_the_internal_module():
expected = {
"H3ContinuumJoin",
"H3ContinuumFinish",
"H3ContinuumAssemble",
"H3ContinuumSaveState",
"H3ContinuumLoadState",
"H3ContinuumSamplerV2",
"H3ContinuumPromptPlanPreview",
"H3ContinuumSaveSession",
+46
View File
@@ -7,9 +7,11 @@ from types import SimpleNamespace
import torch
import pytest
import ctypes
import ComfyUI_H3_Continuum_Join.run_storage as run_storage_module
from ComfyUI_H3_Continuum_Join.run_storage import (
RunStorageController,
RunStorageError,
_hash,
_resume_session_settings,
_apply_nonce_contract,
@@ -156,6 +158,50 @@ def test_fsync_file_accepts_a_completed_file_on_windows(tmp_path):
_fsync_file(target)
def test_json_manifest_replace_retries_transient_windows_access_denied(tmp_path, monkeypatch):
target = tmp_path / "manifest.json"
original_replace = run_storage_module.os.replace
calls = []
def transient_replace(source, destination):
calls.append((source, destination))
if len(calls) < 3:
raise PermissionError(5, "synthetic access denied", str(destination))
return original_replace(source, destination)
monkeypatch.setattr(run_storage_module.os, "replace", transient_replace)
sleeps = []
monkeypatch.setattr(run_storage_module.time, "sleep", sleeps.append)
run_storage_module._write_json(target, {"revision": "new"})
assert json.loads(target.read_text(encoding="utf-8")) == {"revision": "new"}
assert len(calls) == 3
assert sleeps == [0.02, 0.05]
assert not list(tmp_path.glob(".manifest.json.*.tmp"))
def test_json_manifest_replace_keeps_existing_manifest_after_permanent_access_denied(
tmp_path, monkeypatch
):
target = tmp_path / "manifest.json"
target.write_text('{"revision": "old"}\n', encoding="utf-8")
def permanent_replace(source, destination):
raise PermissionError(5, "synthetic permanent access denied", str(destination))
monkeypatch.setattr(run_storage_module.os, "replace", permanent_replace)
monkeypatch.setattr(run_storage_module.time, "sleep", lambda _: None)
with pytest.raises(RunStorageError, match="atomic manifest replace failed") as error:
run_storage_module._write_json(target, {"revision": "new"})
assert "src_exists=True" in str(error.value)
assert "dst_exists=True" in str(error.value)
assert json.loads(target.read_text(encoding="utf-8")) == {"revision": "old"}
assert not list(tmp_path.glob(".manifest.json.*.tmp"))
def test_chunk_sha256_rejects_same_size_corruption(tmp_path):
controller, _ = _controller(tmp_path)
controller.commit_chunk(_entry(0), position=0)
+2 -6
View File
@@ -151,12 +151,8 @@ def test_v34_public_schema_replaces_reference_audio_with_driving_audio():
from ComfyUI_H3_Continuum_Join import nodes as root_nodes
assert root_nodes.NODE_DISPLAY_NAME_MAPPINGS["H3ContinuumSamplerV34"] == (
"H3 Continuum Sampler V3.4"
)
assert root_nodes.NODE_DISPLAY_NAME_MAPPINGS[
"H3ContinuumSamplerTimelineVideo"
].startswith("[Legacy]")
assert "H3ContinuumSamplerV34" not in root_nodes.NODE_CLASS_MAPPINGS
assert "H3ContinuumSamplerTimelineVideo" not in root_nodes.NODE_CLASS_MAPPINGS
def test_unused_long_audio_tail_does_not_change_contract_or_output():
+2 -1
View File
@@ -92,13 +92,14 @@ def test_run_storage_off_normalizes_widgets_reload_and_queued_inputs(tmp_path):
_function_source(source, "findWidget", "setWidgetVisible"),
_function_source(source, "setWidgetVisible", "hidePersistentWidget"),
_function_source(source, "linkedInput", "attachRefresh"),
_function_source(source, "attachRefresh", "normalizeRunStorageState"),
_function_source(source, "attachRefresh", "normalizedV38View"),
_function_source(source, "normalizeRunStorageState", "configureConditionalWidgets"),
_function_source(source, "configureConditionalWidgets", "configureAssembler"),
]
)
script = f"""
const RUN_STORAGE_WIDGET = "run_storage";
const V38_NODE_CLASS = "H3ContinuumSamplerV38";
const REGENERATE_WIDGET = "reroll_from_chunk";
const REROLL_NONCE_WIDGET = "reroll_nonce";
const LEGACY_RUN_NAME_WIDGET = "run_name";
+1 -1
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
import torch
from ComfyUI_H3_Continuum_Join.nodes import (
from ComfyUI_H3_Continuum_Join.v3.conditioning_bridge_nodes import (
NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS,
)
+1 -3
View File
@@ -233,9 +233,7 @@ def test_v35_is_registered_with_v34_outputs_then_refine_context():
assert NODE_DISPLAY_NAME_MAPPINGS["H3ContinuumSamplerV35"] == (
"H3 Continuum Sampler V3.5"
)
assert root_nodes.NODE_CLASS_MAPPINGS["H3ContinuumSamplerV35"] is (
H3ContinuumSamplerV35
)
assert "H3ContinuumSamplerV35" not in root_nodes.NODE_CLASS_MAPPINGS
assert H3ContinuumSamplerV35.RETURN_TYPES[:5] == H3ContinuumSamplerV34.RETURN_TYPES
assert H3ContinuumSamplerV35.RETURN_NAMES[:5] == H3ContinuumSamplerV34.RETURN_NAMES
assert H3ContinuumSamplerV35.RETURN_TYPES[5] == "H3_CONTINUUM_REFINE_CONTEXT"
+10 -4
View File
@@ -6,10 +6,16 @@ import types
import pytest
import torch
from ComfyUI_H3_Continuum_Join.nodes import (
from ComfyUI_H3_Continuum_Join.v3.hires_fix_nodes import (
NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS,
)
from ComfyUI_H3_Continuum_Join.v3.second_pass_nodes import (
NODE_DISPLAY_NAME_MAPPINGS as SECOND_PASS_DISPLAY_NAME_MAPPINGS,
)
from ComfyUI_H3_Continuum_Join.v3.latent_resize_nodes import (
NODE_DISPLAY_NAME_MAPPINGS as LATENT_RESIZE_DISPLAY_NAME_MAPPINGS,
)
from ComfyUI_H3_Continuum_Join.v3.hires_fix_nodes import (
H3ContinuumHiResFixV35,
align_h3_manual_canvas,
@@ -511,10 +517,10 @@ def test_three_v35_nodes_are_registered_with_final_display_names():
assert NODE_DISPLAY_NAME_MAPPINGS["H3ContinuumHiResFixV35"] == (
"H3 Continuum Hi-Res Fix V3.5"
)
assert NODE_DISPLAY_NAME_MAPPINGS["H3ContinuumSecondPassV35"] == (
"H3 Continuum Second Pass V3.5"
assert SECOND_PASS_DISPLAY_NAME_MAPPINGS["H3ContinuumSecondPassV35"] == (
"H3 Continuum Second Pass"
)
assert NODE_DISPLAY_NAME_MAPPINGS["H3ContinuumLatentResizeV35"] == (
assert LATENT_RESIZE_DISPLAY_NAME_MAPPINGS["H3ContinuumLatentResizeV35"] == (
"H3 Continuum Latent Resize V3.5"
)
assert H3ContinuumHiResFixV35.INPUT_IS_LIST is True
+1 -1
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import torch
import torch.nn.functional as F
from ComfyUI_H3_Continuum_Join.nodes import NODE_CLASS_MAPPINGS
from ComfyUI_H3_Continuum_Join.v3.latent_resize_nodes import NODE_CLASS_MAPPINGS
from ComfyUI_H3_Continuum_Join.v3.latent_resize_nodes import (
H3ContinuumLatentResizeV35,
UPSCALE_METHODS,
+2 -6
View File
@@ -36,12 +36,8 @@ def test_v36_is_registered_without_replacing_v35():
assert NODE_DISPLAY_NAME_MAPPINGS["H3ContinuumSamplerV36"] == (
"H3 Continuum Sampler V3.6"
)
assert root_nodes.NODE_CLASS_MAPPINGS["H3ContinuumSamplerV36"] is (
H3ContinuumSamplerV36
)
assert root_nodes.NODE_CLASS_MAPPINGS["H3ContinuumSamplerV35"] is (
H3ContinuumSamplerV35
)
assert "H3ContinuumSamplerV36" not in root_nodes.NODE_CLASS_MAPPINGS
assert "H3ContinuumSamplerV35" not in root_nodes.NODE_CLASS_MAPPINGS
assert H3ContinuumSamplerV36.RETURN_TYPES == H3ContinuumSamplerV35.RETURN_TYPES
assert H3ContinuumSamplerV36.RETURN_NAMES == H3ContinuumSamplerV35.RETURN_NAMES
+40
View File
@@ -0,0 +1,40 @@
from __future__ import annotations
import copy
import json
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
WORKFLOW_DIR = ROOT / "examples" / "workflows"
V36_PATH = WORKFLOW_DIR / "MiniMax_H3_Continuum_V36.json"
V37_PATH = WORKFLOW_DIR / "MiniMax_H3_Continuum_V37.json"
V37_ZIP_PATH = WORKFLOW_DIR / "MiniMax_H3_Continuum_V37.zip"
def _load(path: Path) -> dict:
return json.loads(path.read_text(encoding="utf-8"))
def test_v37_template_is_the_v36_graph_with_only_the_sampler_class_replaced():
v36 = _load(V36_PATH)
v37 = _load(V37_PATH)
sampler = next(node for node in v37["nodes"] if node["id"] == 305)
assert sampler["type"] == "H3ContinuumSamplerV37"
assert sampler["properties"]["Node name for S&R"] == "H3ContinuumSamplerV37"
assert sampler["widgets_values_named"]["continuation_backend"] == "Standard"
assert all(input_["name"] != "guide" for input_ in sampler["inputs"])
normalized = copy.deepcopy(v37)
normalized_sampler = next(node for node in normalized["nodes"] if node["id"] == 305)
normalized_sampler["type"] = "H3ContinuumSamplerV36"
normalized_sampler["properties"]["Node name for S&R"] = "H3ContinuumSamplerV36"
assert normalized == v36
def test_v37_zip_contains_the_exact_public_workflow_json():
with zipfile.ZipFile(V37_ZIP_PATH) as archive:
assert archive.namelist() == [V37_PATH.name]
assert archive.read(V37_PATH.name) == V37_PATH.read_bytes()
@@ -0,0 +1,253 @@
from __future__ import annotations
from pathlib import Path
import pytest
from ComfyUI_H3_Continuum_Join.v3.adaptive_continuity import (
ADAPTIVE_CONTINUITY_OBSERVER_VERSION,
ADAPTIVE_CONTINUITY_PLANNER_HASH,
AdaptiveContinuityObservationError,
AdaptiveContinuityObserver,
EXECUTION_APPLIED,
INITIAL_TRANSPORT,
adaptive_observer_event_fail_soft,
make_adaptive_continuity_decision,
)
ROOT = Path(__file__).resolve().parents[1]
def _entry(context_frames, motion_score):
return {
"context_frames": context_frames,
"motion_score": motion_score,
"video": object(),
"audio": object(),
}
def test_planner_contract_and_decision_hash_are_deterministic():
kwargs = {
"physical_group": 2,
"logical_chunks": (2,),
"observed_motion_score": 0.075,
"current_context_frames": 22,
"resolved_transport": "masked_av_prefix_22_v1",
"terminal_atomic": False,
"boundary_index": 1,
"boundary_count": 2,
"reason": "fixed profile",
}
first = make_adaptive_continuity_decision(**kwargs)
second = make_adaptive_continuity_decision(**kwargs)
assert ADAPTIVE_CONTINUITY_OBSERVER_VERSION == 1
assert len(ADAPTIVE_CONTINUITY_PLANNER_HASH) == 64
assert first == second
assert len(first["decision_hash"]) == 64
assert first["execution_applied"] is EXECUTION_APPLIED is False
assert first["issue_13_mitigation_claim"] is False
assert first["confidence_scope"].endswith("not mitigation efficacy")
def test_initial_group_is_trace_only_and_has_no_continuation_action():
decision = make_adaptive_continuity_decision(
physical_group=1,
logical_chunks=(1,),
observed_motion_score=0.0,
current_context_frames=0,
resolved_transport=INITIAL_TRANSPORT,
terminal_atomic=False,
boundary_index=0,
boundary_count=0,
reason="initial clip",
)
assert decision["recommendation"] == "no_continuation_action_initial_group"
assert decision["execution_applied"] is False
def test_reference_context_and_masked_contracts_are_only_recommended_not_applied():
common = {
"physical_group": 2,
"logical_chunks": (2,),
"observed_motion_score": 0.1,
"current_context_frames": 22,
"terminal_atomic": False,
"boundary_index": 1,
"boundary_count": 2,
"reason": "conservative balanced fallback",
}
reference = make_adaptive_continuity_decision(
**common, resolved_transport="reference_context_v1"
)
masked = make_adaptive_continuity_decision(
**common, resolved_transport="masked_av_prefix_22_v1"
)
assert reference["recommendation"] == "keep_current_reference_context_contract"
assert masked["recommendation"] == "keep_current_masked_prefix_contract"
assert reference["execution_applied"] is masked["execution_applied"] is False
def test_terminal_recommendation_keeps_atomic_fixed_contract():
decision = make_adaptive_continuity_decision(
physical_group=2,
logical_chunks=(2, 3),
observed_motion_score=0.05,
current_context_frames=22,
resolved_transport="masked_av_prefix_22_v1",
terminal_atomic=True,
boundary_index=1,
boundary_count=2,
reason="terminal merged 10-second sample",
)
assert decision["terminal_atomic"] is True
assert decision["recommendation"] == "keep_fixed_terminal_merge_contract"
assert decision["execution_applied"] is False
@pytest.mark.parametrize(
"override",
[
{"current_context_frames": 13},
{"resolved_transport": "dynamic_transport"},
{"observed_motion_score": float("nan")},
{"boundary_index": 3},
],
)
def test_malformed_observation_is_rejected_by_pure_builder(override):
kwargs = {
"physical_group": 2,
"logical_chunks": (2,),
"observed_motion_score": 0.1,
"current_context_frames": 22,
"resolved_transport": "masked_av_prefix_22_v1",
"terminal_atomic": False,
"boundary_index": 1,
"boundary_count": 2,
"reason": "fixed profile",
}
kwargs.update(override)
with pytest.raises(AdaptiveContinuityObservationError):
make_adaptive_continuity_decision(**kwargs)
def test_fail_soft_event_records_advisory_without_raising():
observer = AdaptiveContinuityObserver()
result = adaptive_observer_event_fail_soft(
observer,
"observe",
physical_group=2,
logical_chunks=(2,),
observed_motion_score=0.1,
current_context_frames=13,
resolved_transport="masked_av_prefix_22_v1",
terminal_atomic=False,
boundary_index=1,
boundary_count=2,
reason="invalid diagnostic input",
)
assert result is None
lines = observer.report_lines()
assert "observed_groups=0" in lines[0]
assert "unavailable/advisory" not in lines[0]
assert "Adaptive Continuity advisory [A8a v1]" in lines[1]
assert "execution_applied=false" in lines[1]
def test_replayed_normal_prefix_uses_metadata_without_retaining_payloads():
entries = [_entry(0, 0.0), _entry(22, 0.07), _entry(22, 0.08)]
observer = AdaptiveContinuityObserver()
observer.replay_prefix(
entries=entries,
total_chunks=3,
terminal_merge_enabled=False,
resolved_transport="masked_av_prefix_22_v1",
)
assert [record["physical_group"] for record in observer.records] == [1, 2, 3]
assert all(record["reused"] for record in observer.records)
assert all("video" not in record and "audio" not in record for record in observer.records)
def test_replayed_terminal_pair_is_one_atomic_physical_record():
entries = [_entry(0, 0.0), _entry(22, 0.09), _entry(22, 0.09)]
observer = AdaptiveContinuityObserver()
observer.replay_prefix(
entries=entries,
total_chunks=3,
terminal_merge_enabled=True,
resolved_transport="masked_av_prefix_22_v1",
)
records = observer.records
assert len(records) == 2
assert records[1]["logical_chunks"] == [2, 3]
assert records[1]["terminal_atomic"] is True
assert records[1]["boundary_index"] == 1
assert records[1]["boundary_count"] == 2
def test_report_contains_required_contract_fields_and_no_execution_claim():
observer = AdaptiveContinuityObserver()
observer.observe(
physical_group=1,
logical_chunks=(1,),
observed_motion_score=0.0,
current_context_frames=0,
resolved_transport=INITIAL_TRANSPORT,
terminal_atomic=False,
boundary_index=0,
boundary_count=2,
reason="initial clip",
)
text = "\n".join(observer.report_lines())
for token in (
"planner_hash=",
"motion=",
"context=",
"transport=",
"terminal_atomic=",
"boundary=",
"recommendation=",
"confidence=",
"reason=",
"fallback_reason=",
"execution_applied=false",
):
assert token in text
assert "Issue #13 mitigation claim=none" in text
def test_a8a_is_detailed_only_and_has_no_public_schema_or_identity_field():
sequence = (ROOT / "v2" / "sequence.py").read_text(encoding="utf-8")
observer_creation = sequence.index(
"adaptive_continuity_observer=AdaptiveContinuityObserver()"
)
detailed_guard = sequence.rindex(
"if diagnostics_mode==DIAGNOSTICS_FULL:", 0, observer_creation
)
assert detailed_guard < observer_creation
for path in (
ROOT / "v3" / "nodes.py",
ROOT / "v3" / "driving_nodes.py",
ROOT / "v3" / "second_pass_nodes.py",
):
assert "adaptive_continuity" not in path.read_text(encoding="utf-8")
storage = (ROOT / "run_storage.py").read_text(encoding="utf-8")
assert "adaptive_continuity" not in storage
def test_a8a_source_has_no_tensor_or_execution_mutation_api():
source = (ROOT / "v3" / "adaptive_continuity.py").read_text(encoding="utf-8")
for forbidden in (
"import torch",
".clone(",
".copy_(",
"noise_mask",
"prepare_conditioning",
"sample_chunk",
"unload_all_models",
"optimized_attention_override",
"PackedLayout",
):
assert forbidden not in source
+292
View File
@@ -0,0 +1,292 @@
from __future__ import annotations
import copy
import hashlib
from types import SimpleNamespace
import pytest
import torch
from ComfyUI_H3_Continuum_Join.v3 import targeted_refine_sampling
from ComfyUI_H3_Continuum_Join.v3.refine_schedule import make_tail_schedule
from ComfyUI_H3_Continuum_Join.v3.refine_target import (
MODE_AUDIO_ONLY,
derive_target_refine_seed,
)
from ComfyUI_H3_Continuum_Join.v3.second_pass import update_second_pass_geometry
from ComfyUI_H3_Continuum_Join.v3.targeted_refine_sampling import (
_prepare_audio_only_noise_and_mask,
sample_audio_only_refine_chunk,
)
from ComfyUI_H3_Continuum_Join.v3.targeted_second_pass import (
run_targeted_second_pass_groups,
)
class _Nested:
is_nested = True
def __init__(self, tensors):
self.tensors = list(tensors)
def unbind(self):
return self.tensors
def to(self, *_args, **_kwargs):
return self
def _sha(tensor: torch.Tensor) -> str:
value = tensor.detach().to(device="cpu").contiguous()
return hashlib.sha256(value.view(torch.uint8).numpy().tobytes()).hexdigest()
def test_audio_only_noise_is_random_for_audio_zero_for_video_with_minimal_masks():
video = torch.ones((1, 24, 3, 4, 5), dtype=torch.float16)
audio = torch.zeros((1, 32, 2, 12), dtype=torch.float16)
calls = []
def prepare_noise(samples, seed, batch_inds):
calls.append((samples, seed, batch_inds))
return torch.full_like(samples, 0.625, device="cpu")
noise, mask = _prepare_audio_only_noise_and_mask(
video,
audio,
seed=321,
batch_inds=[0],
prepare_noise_fn=prepare_noise,
nested_builder=_Nested,
)
video_noise, audio_noise = noise.unbind()
video_mask, audio_mask = mask.unbind()
assert calls == [(audio, 321, [0])]
assert torch.count_nonzero(video_noise) == 0
assert video_noise.dtype == video.dtype
assert torch.equal(audio_noise, torch.full_like(audio_noise, 0.625))
assert tuple(video_mask.shape) == (1, 1, 1, 1, 1)
assert tuple(audio_mask.shape) == (1, 1, 1, 1)
assert torch.all(video_mask == 0)
assert torch.all(audio_mask == 1)
def test_audio_only_sampler_passes_target_policy_and_exact_sigmas_to_core(monkeypatch):
video = torch.randn((1, 24, 3, 4, 4))
audio = torch.randn((1, 32, 2, 12))
latent_samples = _Nested((video, audio))
sigmas = torch.tensor([0.35, 0.2, 0.0])
captured = {}
class _Guider:
def sample(self, noise, latent_image, sampler, supplied_sigmas, **kwargs):
captured.update(
noise=noise,
latent_image=latent_image,
sampler=sampler,
sigmas=supplied_sigmas,
**kwargs,
)
return _Nested((video + 500.0, audio + 2.0))
def prepare_noise(samples, seed, batch_inds):
captured["prepare_noise"] = (samples, seed, batch_inds)
return torch.full_like(samples, 0.75, device="cpu")
fake_sample = SimpleNamespace(
fix_empty_latent_channels=lambda _model, samples, _spatial, _temporal: samples,
prepare_noise=prepare_noise,
)
fake_runtime = (
SimpleNamespace(intermediate_device=lambda: torch.device("cpu")),
SimpleNamespace(NestedTensor=_Nested),
fake_sample,
SimpleNamespace(PROGRESS_BAR_ENABLED=False),
SimpleNamespace(prepare_callback=lambda *_args: None),
)
monkeypatch.setattr(
targeted_refine_sampling,
"_load_runtime_modules",
lambda: fake_runtime,
)
monkeypatch.setattr(
targeted_refine_sampling,
"_make_basic_guider",
lambda *_args: _Guider(),
)
sampler = object()
output = sample_audio_only_refine_chunk(
model=object(),
conditioning=["conditioning"],
latent={"samples": latent_samples},
sampler=sampler,
sigmas=sigmas,
seed=654,
enable_preview=False,
)
assert captured["prepare_noise"] == (audio, 654, None)
assert captured["latent_image"] is latent_samples
assert captured["sigmas"] is sigmas
assert captured["sampler"] is sampler
video_noise, audio_noise = captured["noise"].unbind()
video_mask, audio_mask = captured["denoise_mask"].unbind()
assert torch.count_nonzero(video_noise) == 0
assert torch.equal(audio_noise, torch.full_like(audio_noise, 0.75))
assert torch.all(video_mask == 0)
assert torch.all(audio_mask == 1)
sampled_video, sampled_audio = output["samples"].unbind()
assert torch.equal(sampled_video, video + 500.0)
assert torch.equal(sampled_audio, audio + 2.0)
def _group(group_id: int, *, temporal: int, audio_t: int, terminal: bool) -> dict:
return {
"group_id": group_id,
"logical_chunks": [1] if group_id == 0 else [2, 3],
"physical_prompt": f"group {group_id + 1}",
"prompt_policy": "paired_timeline_v1" if terminal else "single",
"physical_frames": 260 if terminal else 124,
"trim_prefix_frames": 22 if terminal else 0,
"terminal_merged": terminal,
"source_width": 128,
"source_height": 128,
"source_batch": 1,
"latent_channels": 24,
"source_latent_t": temporal,
"source_latent_h": 8,
"source_latent_w": 8,
"source_audio_shape": [1, 32, 2, audio_t],
}
def _fixture():
groups = [
_group(0, temporal=31, audio_t=207, terminal=False),
_group(1, temporal=65, audio_t=433, terminal=True),
]
videos = [
{
"samples": torch.arange(
24 * group["source_latent_t"] * 8 * 8,
dtype=torch.float32,
).reshape(1, 24, group["source_latent_t"], 8, 8)
}
for group in groups
]
audios = [
{
"samples": torch.arange(
32 * 2 * group["source_audio_shape"][-1],
dtype=torch.float32,
).reshape(group["source_audio_shape"])
}
for group in groups
]
plan = {
"width": 128,
"height": 128,
"existing_top_level": {"preserved": True},
"second_pass_contract": {
"version": 1,
"existing_contract_field": "preserved",
"physical_groups": groups,
},
}
return groups, videos, audios, plan
def test_audio_only_group_gate_preserves_video_and_samples_each_physical_group_once():
groups, videos, audios, plan = _fixture()
plan_before = copy.deepcopy(plan)
video_hashes = [_sha(item["samples"]) for item in videos]
source_sigmas = torch.tensor([0.6, 0.3, 0.0], dtype=torch.float32)
schedule = make_tail_schedule(source_sigmas, evaluation_count=1)
schedule_before = copy.deepcopy(dict(schedule.contract))
calls = []
def sample(**kwargs):
calls.append(kwargs)
return {
"video": kwargs["latent"]["video"] + 1000.0,
"audio": kwargs["latent"]["audio"] + float(len(calls)),
}
result = run_targeted_second_pass_groups(
model="model",
clip="clip",
sampler="sampler",
sigmas=source_sigmas,
video_latents=videos,
audio_latents=audios,
assembly_plan=plan,
refine_seed=91,
refine_target=MODE_AUDIO_ONLY,
encode_prompt_fn=lambda _clip, prompt, **_kwargs: [prompt],
latent_builder=lambda video, audio: {"video": video, "audio": audio},
sample_fn=sample,
stream_extractor=lambda value: (value["video"], value["audio"]),
clone_model_fn=lambda source, **kwargs: (source, kwargs),
refine_schedule=schedule,
enable_preview=False,
)
output_videos, output_audios, updated_plan, status = result
assert plan == plan_before
assert dict(schedule.contract) == schedule_before
assert all(
output is source
for output, source in zip(output_videos, videos, strict=True)
)
assert [_sha(item["samples"]) for item in output_videos] == video_hashes
assert [tuple(item["samples"].shape) for item in output_audios] == [
tuple(item["samples"].shape) for item in audios
]
assert all(
output is not source
for output, source in zip(output_audios, audios, strict=True)
)
assert [call["seed"] for call in calls] == [
derive_target_refine_seed(91, 0, MODE_AUDIO_ONLY),
derive_target_refine_seed(91, 1, MODE_AUDIO_ONLY),
]
assert all(call["sigmas"] is schedule.sigmas for call in calls)
assert [call["conditioning"] for call in calls] == [["group 1"], ["group 2"]]
assert len(calls) == len(groups) == 2
assert groups[1]["logical_chunks"] == [2, 3]
assert groups[1]["terminal_merged"] is True
assert "Production HOLD" in status
contract = updated_plan["second_pass_contract"]
assert contract["version"] == 1
assert contract["refine_target_contract"]["mode"] == MODE_AUDIO_ONLY
assert contract["video_output"] == "bit_exact_first_pass_passthrough"
assert contract["video_sampling"] == "zero_noise_mask_locked"
assert contract["audio_output"] == "sampled"
assert contract["audio_sampling"] == "seeded_random_mask_1"
assert contract["refine_group_seeds"] == [call["seed"] for call in calls]
assert contract["refine_schedule"]["schedule_hash"] == schedule.contract["schedule_hash"]
assert contract["refine_execution_contract"]["sigma_range"]["sigma_hash"] == (
schedule.contract["sigma_hash"]
)
expected_plan = update_second_pass_geometry(plan, videos)
normalized = copy.deepcopy(updated_plan)
normalized_contract = normalized["second_pass_contract"]
for key in (
"execution",
"conditioning_sources",
"refine_seed_base",
"refine_group_seeds",
"video_output",
"video_sampling",
"audio_output",
"audio_sampling",
"refine_schedule",
"refine_schedule_identity",
"refine_target_contract",
"refine_execution_contract",
):
normalized_contract.pop(key)
assert normalized == expected_plan
+114
View File
@@ -0,0 +1,114 @@
from __future__ import annotations
import pytest
from ComfyUI_H3_Continuum_Join.branch_provenance import (
BranchProvenanceError,
PhysicalGroup,
active_revision_map,
make_group_revision,
physical_groups,
resolve_chain,
validate_group_revision,
)
def _record(position: int, source: str, seed: int):
return {
"sequence_index": position,
"storage_revision_id": source,
"filename": f"chunk_{position + 1:04d}.safetensors",
"file_size": 100 + position,
"file_sha256": f"sha-{source}-{position}",
"entry": {"seed": seed, "prompt_hash": f"prompt-{position}"},
}
def _revision(group, *, parent=None, source="a", nonce=0, branch_cut=None):
return make_group_revision(
parent_revision_id=parent,
group=group,
variation_nonce=nonce,
created_utc="2026-09-03T00:00:00+00:00",
storage_revision_id=source,
generation_contract_sha256=f"contract-{source}",
lineage_sha256="lineage",
records=[
_record(position, source, 1000 + position + nonce)
for position in range(group.start - 1, group.end)
],
branch_cut=branch_cut,
)
def test_normal_and_terminal_physical_groups_are_atomic():
assert [(g.start, g.end) for g in physical_groups(chunks=3, terminal_merge_enabled=False)] == [
(1, 1),
(2, 2),
(3, 3),
]
assert [(g.start, g.end) for g in physical_groups(chunks=3, terminal_merge_enabled=True)] == [
(1, 1),
(2, 3),
]
def test_group_revision_identity_is_immutable_and_display_name_free():
group = PhysicalGroup(3, 3, 3)
first = _revision(group, source="take-b", nonce=2)
second = _revision(group, source="take-b", nonce=2)
assert first["revision_id"] == second["revision_id"]
assert "take" not in first
assert validate_group_revision(first)["revision_id"] == first["revision_id"]
changed = dict(first)
changed["variation_nonce"] = 3
with pytest.raises(BranchProvenanceError, match="identity"):
validate_group_revision(changed)
def test_branch_chain_keeps_both_takes_and_resolves_selected_parent():
r1 = _revision(PhysicalGroup(1, 1, 1), source="root")
r2 = _revision(PhysicalGroup(2, 2, 2), parent=r1["revision_id"], source="root")
r3a = _revision(PhysicalGroup(3, 3, 3), parent=r2["revision_id"], source="a", nonce=1)
r3b = _revision(PhysicalGroup(3, 3, 3), parent=r2["revision_id"], source="b", nonce=2)
r4b = _revision(
PhysicalGroup(4, 4, 4),
parent=r3b["revision_id"],
source="b2",
nonce=3,
branch_cut={
"selected_revision_id": r3b["revision_id"],
"after_physical_group": 3,
},
)
catalog = {item["revision_id"]: item for item in (r1, r2, r3a, r3b, r4b)}
chain = resolve_chain(catalog, r4b["revision_id"])
assert [item["revision_id"] for item in chain] == [
r1["revision_id"],
r2["revision_id"],
r3b["revision_id"],
r4b["revision_id"],
]
assert r3a["revision_id"] in catalog
assert active_revision_map(chain)["3"] == r3b["revision_id"]
def test_wrong_parent_and_terminal_half_are_rejected():
r1 = _revision(PhysicalGroup(1, 1, 1), source="root")
orphan = _revision(PhysicalGroup(3, 3, 3), parent=r1["revision_id"], source="bad")
with pytest.raises(BranchProvenanceError, match="contiguous"):
resolve_chain(
{r1["revision_id"]: r1, orphan["revision_id"]: orphan},
orphan["revision_id"],
)
with pytest.raises(BranchProvenanceError, match="non-atomic"):
make_group_revision(
parent_revision_id=r1["revision_id"],
group=PhysicalGroup(2, 3, 2),
variation_nonce=1,
created_utc="2026-09-03T00:00:00+00:00",
storage_revision_id="terminal",
generation_contract_sha256="contract",
lineage_sha256="lineage",
records=[_record(1, "terminal", 1)],
)
@@ -0,0 +1,334 @@
from __future__ import annotations
import inspect
import pytest
from ComfyUI_H3_Continuum_Join.temporal import audio_latent_t, context_slots
from ComfyUI_H3_Continuum_Join.v3.reliability_v38 import (
build_chunk_boundary_diagnostics,
)
def _chunk(index: int, *, context: int = 22, start: int | None = None):
if index == 1:
total = net = 124
trim = 0
else:
trim = context
total = context + 119
net = 119
if start is None:
start = 0 if index == 1 else 124 + (index - 2) * 119
return {
"sequence_index": index,
"chunk_index": index,
"total_frames": total,
"trim_frames": trim,
"net_frames": net,
"context_frames": trim,
"frame_start": start,
"frame_stop": start + net,
}
def _decode_group(chunk, *, logical=None, terminal=False):
group = dict(chunk)
group["logical_chunk_indices"] = list(logical or [chunk["chunk_index"]])
group["terminal_merged"] = bool(terminal)
return group
def _second_pass_group(group_id: int, group):
return {
"group_id": group_id,
"logical_chunks": list(group["logical_chunk_indices"]),
"physical_frames": group["total_frames"],
"trim_prefix_frames": group["trim_frames"],
"terminal_merged": bool(group.get("terminal_merged", False)),
}
def _plan(*chunks, groups=None, second_pass=True):
active_groups = (
list(groups)
if groups is not None
else [_decode_group(chunk) for chunk in chunks]
)
plan = {"chunks": list(chunks), "decode_groups": active_groups}
if second_pass:
plan["second_pass_contract"] = {
"version": 1,
"physical_groups": [
_second_pass_group(index, group)
for index, group in enumerate(active_groups)
],
}
return plan
def _diagnose(plan, *, video_count=None, audio_count=None):
groups = plan.get("decode_groups", plan.get("chunks", []))
return build_chunk_boundary_diagnostics(
video_latents=[object()] * (len(groups) if video_count is None else video_count),
audio_latents=[object()] * (len(groups) if audio_count is None else audio_count),
assembly_plan=plan,
)
def test_single_chunk_has_zero_boundaries_and_silent_basic():
result = _diagnose(_plan(_chunk(1)))
assert result.basic == ()
assert result.detailed == (
"Chunk boundary contract: structural diagnostic only; "
"no image/audio similarity measurement.",
"Second Pass contract: groups=1 PASS.",
)
@pytest.mark.parametrize(
("context", "expected_video", "expected_audio"),
(
(5, 2, 8),
(22, 7, 37),
(39, 12, 65),
),
)
def test_fast_balanced_strong_context_uses_shared_temporal_helpers(
context, expected_video, expected_audio
):
first = _chunk(1)
second = _chunk(2, context=context)
result = _diagnose(_plan(first, second))
assert context_slots(context) == expected_video
assert audio_latent_t(context) == expected_audio
assert result.basic == ()
assert len([line for line in result.detailed if line.startswith("Boundary ")]) == 1
assert (
f"context={context}f video={expected_video}T audio={expected_audio}T"
in result.detailed[-1]
)
assert result.detailed[-1].endswith("PASS.")
def test_three_chunks_have_two_boundaries_and_silent_basic():
result = _diagnose(_plan(_chunk(1), _chunk(2), _chunk(3)))
assert result.basic == ()
boundaries = [line for line in result.detailed if line.startswith("Boundary ")]
assert len(boundaries) == 2
assert boundaries[0].startswith("Boundary 1→2: physical;")
assert boundaries[1].startswith("Boundary 2→3: physical;")
@pytest.mark.parametrize(
("field", "value", "message"),
(
("trim_frames", 200, "trim_frames exceeds total_frames"),
("net_frames", 118, "total_frames - trim_frames differs from net_frames"),
),
)
def test_invalid_right_geometry_is_advisory(field, value, message):
right = _chunk(2)
right[field] = value
result = _diagnose(_plan(_chunk(1), right))
assert any(message in line for line in result.basic)
assert result.detailed[-1].endswith(").")
assert "ADVISORY" in result.detailed[-1]
@pytest.mark.parametrize(("right_start", "gap"), ((125, 1), (123, -1)))
def test_artificial_gap_or_overlap_is_advisory(right_start, gap):
result = _diagnose(_plan(_chunk(1), _chunk(2, start=right_start)))
assert any("non-contiguous visible range" in line for line in result.basic)
boundary = result.detailed[-1]
assert f"gap={gap}" in boundary
assert "ADVISORY" in boundary
def test_missing_geometry_is_unavailable_without_hard_failure():
right = _chunk(2)
del right["total_frames"]
result = _diagnose(_plan(_chunk(1), right, second_pass=False))
assert result.basic
assert "required geometry is unavailable" in "\n".join(result.basic)
assert "ADVISORY" in result.detailed[-1]
def test_non_contiguous_logical_order_is_advisory():
right = _chunk(2)
right["chunk_index"] = 3
groups = [_decode_group(_chunk(1)), _decode_group(right, logical=[2])]
result = _diagnose(_plan(_chunk(1), right, groups=groups, second_pass=False))
assert any("logical order" in line for line in result.basic)
def test_physical_mapping_missing_logical_chunk():
chunks = (_chunk(1), _chunk(2), _chunk(3))
groups = [_decode_group(chunks[0]), _decode_group(chunks[2])]
result = _diagnose(_plan(*chunks, groups=groups, second_pass=False))
assert any("does not cover all logical chunks" in line for line in result.basic)
assert any("UNAVAILABLE" in line for line in result.detailed)
def test_physical_mapping_duplicate_logical_chunk():
chunks = (_chunk(1), _chunk(2))
groups = [_decode_group(chunks[0]), _decode_group(chunks[1], logical=[1])]
result = _diagnose(_plan(*chunks, groups=groups, second_pass=False))
assert any("mapped more than once" in line for line in result.basic)
def test_physical_mapping_reversed_order():
chunks = (_chunk(1), _chunk(2))
group = _decode_group(chunks[0], logical=[2, 1], terminal=True)
result = _diagnose(_plan(*chunks, groups=[group], second_pass=False))
joined = "\n".join(result.basic)
assert "logical order is reversed" in joined
assert "Terminal Merge mapping is invalid" in joined
def test_physical_output_group_count_mismatch_is_summarized():
plan = _plan(_chunk(1), _chunk(2), second_pass=False)
result = _diagnose(plan, video_count=1, audio_count=2)
assert any("physical output/group counts differ" in line for line in result.basic)
def _terminal_plan(*, terminal_flag=True, second_pass=True):
chunks = [_chunk(1), _chunk(2), _chunk(3)]
terminal = dict(chunks[1])
terminal.update(
{
"total_frames": 260,
"trim_frames": 22,
"net_frames": 238,
"frame_start": 124,
"frame_stop": 362,
"logical_chunk_indices": [2, 3],
"terminal_merged": terminal_flag,
}
)
groups = [_decode_group(chunks[0]), terminal]
return _plan(*chunks, groups=groups, second_pass=second_pass)
def test_terminal_merge_is_shared_physical_boundary_not_external_seam():
result = _diagnose(_terminal_plan())
assert result.basic == ()
terminal = [line for line in result.detailed if line.startswith("Boundary 2→3")][0]
assert "shared physical group=2" in terminal
assert "terminal_merged=yes" in terminal
assert "no external decode boundary" in terminal
assert terminal.endswith("PASS.")
def test_terminal_flag_mismatch_is_advisory():
result = _diagnose(_terminal_plan(terminal_flag=False, second_pass=False))
assert any("without Terminal Merge" in line for line in result.basic)
terminal = [line for line in result.detailed if line.startswith("Boundary 2→3")][0]
assert "terminal_merged=no" in terminal
assert "ADVISORY" in terminal
@pytest.mark.parametrize(
("field", "value", "message"),
(
("logical_chunks", [1, 2], "logical_chunks differs"),
("physical_frames", 999, "physical_frames differs"),
("trim_prefix_frames", 5, "trim_prefix_frames differs"),
),
)
def test_second_pass_contract_mismatch_is_advisory(field, value, message):
plan = _terminal_plan()
plan["second_pass_contract"]["physical_groups"][1][field] = value
result = _diagnose(plan)
assert any(message in line for line in result.basic)
assert "Second Pass contract: groups=2 ADVISORY." in result.detailed
class _ReadOnlyTensorProbe:
shape = (1, 24, 37, 4, 4)
dtype = "probe-dtype"
device = "probe-device"
def data_ptr(self):
return 12345
def clone(self):
raise AssertionError("clone must not be called")
def cpu(self):
raise AssertionError("cpu must not be called")
def float(self):
raise AssertionError("float must not be called")
def numpy(self):
raise AssertionError("numpy must not be called")
def __hash__(self):
raise AssertionError("hash must not be called")
def test_diagnostic_is_read_only_and_preserves_all_objects():
video_tensor = _ReadOnlyTensorProbe()
audio_tensor = _ReadOnlyTensorProbe()
video_latents = [{"samples": video_tensor}]
audio_latents = [{"samples": audio_tensor}]
plan = _plan(_chunk(1))
before = (
id(video_latents),
id(audio_latents),
id(plan),
id(video_tensor),
id(audio_tensor),
video_tensor.data_ptr(),
video_tensor.dtype,
video_tensor.device,
video_tensor.shape,
)
build_chunk_boundary_diagnostics(
video_latents=video_latents,
audio_latents=audio_latents,
assembly_plan=plan,
)
after = (
id(video_latents),
id(audio_latents),
id(plan),
id(video_tensor),
id(audio_tensor),
video_tensor.data_ptr(),
video_tensor.dtype,
video_tensor.device,
video_tensor.shape,
)
assert after == before
def test_boundary_implementation_has_no_tensor_content_operations():
source = inspect.getsource(build_chunk_boundary_diagnostics)
for forbidden in (
".clone(",
".cpu(",
".float(",
".numpy(",
"ContextDiagnosticsTracker",
"torch.equal",
):
assert forbidden not in source
+437
View File
@@ -0,0 +1,437 @@
from __future__ import annotations
import copy
import pytest
import torch
from ComfyUI_H3_Continuum_Join.v3 import second_pass, second_pass_nodes
from ComfyUI_H3_Continuum_Join.v3 import targeted_second_pass
from ComfyUI_H3_Continuum_Join.v3.refine_scope import (
MAGIC,
MODE_ALL,
MODE_LOGICAL_CHUNK,
MODE_PHYSICAL_GROUP,
RefineScopeError,
resolve_refine_scope,
serializable_scope_contract,
)
from ComfyUI_H3_Continuum_Join.v3.refine_target import (
MODE_AUDIO_ONLY,
MODE_VIDEO_AUDIO,
MODE_VIDEO_ONLY,
derive_target_refine_seed,
)
from ComfyUI_H3_Continuum_Join.v3.second_pass_nodes import (
H3ContinuumSelectiveSecondPassExperimental,
REFINE_SCOPE_ALL,
REFINE_SCOPE_LOGICAL_CHUNK,
REFINE_SCOPE_PHYSICAL_GROUP,
REFINE_TARGET_VIDEO_ONLY,
)
from ComfyUI_H3_Continuum_Join.v3.targeted_second_pass import (
run_targeted_second_pass_groups,
)
def _group(
group_id: int,
logical_chunks: list[int],
*,
temporal: int,
audio_t: int,
terminal: bool = False,
) -> dict:
return {
"group_id": group_id,
"logical_chunks": logical_chunks,
"physical_prompt": f"group {group_id + 1}",
"prompt_policy": "paired_timeline_v1" if terminal else "single",
"physical_frames": 260 if terminal else 124,
"trim_prefix_frames": 22 if group_id else 0,
"terminal_merged": terminal,
"source_width": 128,
"source_height": 128,
"source_batch": 1,
"latent_channels": 24,
"source_latent_t": temporal,
"source_latent_h": 8,
"source_latent_w": 8,
"source_audio_shape": [1, 32, 2, audio_t],
}
def _fixture(*, terminal: bool = False):
if terminal:
groups = [
_group(0, [1], temporal=31, audio_t=207),
_group(1, [2, 3], temporal=65, audio_t=433, terminal=True),
]
else:
groups = [
_group(0, [1], temporal=31, audio_t=207),
_group(1, [2], temporal=36, audio_t=235),
_group(2, [3], temporal=36, audio_t=235),
]
videos = [
{
"samples": torch.full(
(1, 24, group["source_latent_t"], 8, 8),
float(index + 1),
)
}
for index, group in enumerate(groups)
]
audios = [
{
"samples": torch.full(
tuple(group["source_audio_shape"]),
float(index + 11),
)
}
for index, group in enumerate(groups)
]
plan = {
"width": 128,
"height": 128,
"existing_top_level": {"preserved": True},
"second_pass_contract": {
"version": 1,
"existing_contract_field": "preserved",
"physical_groups": groups,
},
}
return groups, videos, audios, plan
def _run(
target: str,
*,
scope: str = MODE_ALL,
scope_index: int = 1,
terminal: bool = False,
observers: dict | None = None,
):
groups, videos, audios, plan = _fixture(terminal=terminal)
calls = observers if observers is not None else {}
calls.setdefault("encode", [])
calls.setdefault("clone", [])
calls.setdefault("sample", [])
sigmas = torch.tensor([0.6, 0.3, 0.0], dtype=torch.float32)
def encode(_clip, prompt, **_kwargs):
calls["encode"].append(prompt)
return [prompt]
def clone(model, **kwargs):
calls["clone"].append(kwargs)
return model
def sample(**kwargs):
calls["sample"].append(kwargs)
return {
"video": kwargs["latent"]["video"] + 100.0,
"audio": kwargs["latent"]["audio"] + 200.0,
}
result = run_targeted_second_pass_groups(
model="model",
clip="clip",
sampler="sampler",
sigmas=sigmas,
video_latents=videos,
audio_latents=audios,
assembly_plan=plan,
refine_seed=91,
refine_target=target,
refine_scope=scope,
refine_scope_index=scope_index,
encode_prompt_fn=encode,
latent_builder=lambda video, audio: {"video": video, "audio": audio},
sample_fn=sample,
stream_extractor=lambda value: (value["video"], value["audio"]),
clone_model_fn=clone,
enable_preview=False,
)
return groups, videos, audios, plan, sigmas, calls, result
def test_scope_resolver_is_pure_and_terminal_logical_selection_is_atomic():
groups, _videos, _audios, plan = _fixture(terminal=True)
plan_before = copy.deepcopy(plan)
all_scope = resolve_refine_scope(MODE_ALL, 99, plan)
physical = resolve_refine_scope(MODE_PHYSICAL_GROUP, 2, plan)
logical = resolve_refine_scope(MODE_LOGICAL_CHUNK, 3, plan)
assert plan == plan_before
assert all_scope.selected_group_indices == (0, 1)
assert all_scope.contract["requested_index"] is None
assert physical.selected_group_indices == (1,)
assert physical.contract["selected_logical_chunks"] == (2, 3)
assert physical.contract["terminal_expanded"] is False
assert logical.selected_group_indices == (1,)
assert logical.contract["selected_logical_chunks"] == (2, 3)
assert logical.contract["terminal_expanded"] is True
assert logical.contract["magic"] == MAGIC
serialized = serializable_scope_contract(logical)
serialized["selected_logical_chunks"].append(99)
assert logical.contract["selected_logical_chunks"] == (2, 3)
assert groups[1]["logical_chunks"] == [2, 3]
@pytest.mark.parametrize(
("mode", "index", "match"),
(
("unknown", 1, "unsupported refine scope"),
(1, 1, "unsupported refine scope"),
(MODE_PHYSICAL_GROUP, 0, "positive integer"),
(MODE_PHYSICAL_GROUP, 1.5, "positive integer"),
(MODE_PHYSICAL_GROUP, 3, "outside"),
(MODE_LOGICAL_CHUNK, 4, "not present"),
),
)
def test_invalid_scope_fails_before_any_execution(mode, index, match):
_groups, _videos, _audios, plan = _fixture(terminal=True)
with pytest.raises(RefineScopeError, match=match):
resolve_refine_scope(mode, index, plan)
@pytest.mark.parametrize(
("target", "video_changed", "audio_changed"),
(
(MODE_VIDEO_ONLY, True, False),
(MODE_AUDIO_ONLY, False, True),
(MODE_VIDEO_AUDIO, True, True),
),
)
def test_physical_group_scope_does_no_work_for_unselected_groups(
monkeypatch,
target,
video_changed,
audio_changed,
):
derived_indices = []
if target == MODE_VIDEO_ONLY:
original = second_pass.derive_refine_seed
def derive(seed, index):
derived_indices.append(index)
return original(seed, index)
monkeypatch.setattr(second_pass, "derive_refine_seed", derive)
else:
original = targeted_second_pass.derive_target_refine_seed
def derive(seed, index, resolved_target):
derived_indices.append(index)
return original(seed, index, resolved_target)
monkeypatch.setattr(targeted_second_pass, "derive_target_refine_seed", derive)
groups, videos, audios, plan, sigmas, calls, result = _run(
target,
scope=MODE_PHYSICAL_GROUP,
scope_index=2,
)
output_videos, output_audios, updated_plan, status = result
assert len(groups) == 3
assert calls["encode"] == ["group 2"]
assert len(calls["clone"]) == len(calls["sample"]) == 1
assert derived_indices == [1]
assert calls["sample"][0]["sigmas"] is sigmas
assert calls["sample"][0]["seed"] == derive_target_refine_seed(91, 1, target)
for index in (0, 2):
assert output_videos[index] is videos[index]
assert output_audios[index] is audios[index]
assert (output_videos[1] is not videos[1]) is video_changed
assert (output_audios[1] is not audios[1]) is audio_changed
assert plan["existing_top_level"] == {"preserved": True}
assert plan["second_pass_contract"]["existing_contract_field"] == "preserved"
contract = updated_plan["second_pass_contract"]
assert contract["version"] == 1
assert contract["existing_contract_field"] == "preserved"
assert contract["physical_groups"][:3] != []
assert contract["refine_group_seeds"] == [calls["sample"][0]["seed"]]
assert "refine_scope_contract" not in contract
assert "no conditioning, MODEL clone, Sampling, or seed derivation" in status
def test_non_selected_refine_context_conditioning_is_not_adapted_or_cloned():
groups, videos, _audios, plan = _fixture()
calls = {"adapt": [], "clone": [], "consume": []}
def validate(_context, *, assembly_plan):
assert assembly_plan is plan
return {"complete": True, "groups": groups}
def adapt(group, **_kwargs):
calls["adapt"].append(group["group_id"])
return [[f"conditioning-{group['group_id']}", {}]], None
def clone(model, **kwargs):
calls["clone"].append(kwargs["chunk_index"])
return model
prepared = second_pass.prepare_physical_refine_groups(
model="model",
clip="clip",
video_latents=videos,
assembly_plan=plan,
refine_context=object(),
validate_refine_context_fn=validate,
adapt_group_conditioning_fn=adapt,
clone_model_fn=clone,
group_consumer_fn=lambda group_index, *_args: calls["consume"].append(
group_index
),
retain_group_outputs=False,
selected_group_indices=(1,),
)
assert calls == {"adapt": [1], "clone": [2], "consume": [1]}
assert prepared["selected_group_indices"] == [1]
assert prepared["selected_group_count"] == 1
def test_selected_group_seed_matches_all_mode_and_all_mode_has_a3c_plan_contract():
*_prefix, all_calls, all_result = _run(MODE_VIDEO_AUDIO)
*_scoped_prefix, scoped_calls, scoped_result = _run(
MODE_VIDEO_AUDIO,
scope=MODE_PHYSICAL_GROUP,
scope_index=2,
)
all_plan = all_result[2]
scoped_plan = scoped_result[2]
assert scoped_calls["sample"][0]["seed"] == all_calls["sample"][1]["seed"]
assert "refine_scope_contract" not in all_plan["second_pass_contract"]
assert set(scoped_plan["second_pass_contract"]) == set(
all_plan["second_pass_contract"]
)
assert "Refine Scope:" not in all_result[3]
assert scoped_plan["second_pass_contract"]["version"] == 1
@pytest.mark.parametrize("logical_chunk", (2, 3))
def test_terminal_logical_chunk_scope_expands_to_one_atomic_physical_pair(
logical_chunk,
):
groups, videos, audios, _plan, _sigmas, calls, result = _run(
MODE_VIDEO_AUDIO,
scope=MODE_LOGICAL_CHUNK,
scope_index=logical_chunk,
terminal=True,
)
output_videos, output_audios, updated_plan, status = result
assert groups[1]["logical_chunks"] == [2, 3]
assert groups[1]["terminal_merged"] is True
assert len(calls["encode"]) == len(calls["clone"]) == len(calls["sample"]) == 1
assert output_videos[0] is videos[0]
assert output_audios[0] is audios[0]
assert output_videos[1] is not videos[1]
assert output_audios[1] is not audios[1]
assert "refine_scope_contract" not in updated_plan["second_pass_contract"]
assert "selected_physical_groups=[2]" in status
assert "selected_logical_chunks=[2, 3]" in status
assert "terminal_expanded=true" in status
def test_public_scope_labels_forward_without_frontend_or_silent_fallback(monkeypatch):
calls = []
def fake_run(**kwargs):
calls.append(kwargs)
return kwargs["video_latents"], kwargs["audio_latents"], kwargs[
"assembly_plan"
], "ok"
monkeypatch.setattr(second_pass_nodes, "run_targeted_second_pass_groups", fake_run)
node = H3ContinuumSelectiveSecondPassExperimental()
common = {
"model": [object()],
"clip": [object()],
"sampler": [object()],
"sigmas": [object()],
"video_latents": [{"samples": object()}],
"audio_latents": [{"samples": object()}],
"assembly_plan": [{"second_pass_contract": {"version": 1}}],
"refine_seed": [7],
"refine_target": [REFINE_TARGET_VIDEO_ONLY],
}
node.refine(
**common,
refine_scope=[REFINE_SCOPE_PHYSICAL_GROUP],
refine_scope_index=[2],
)
node.refine(
**common,
refine_scope=[REFINE_SCOPE_LOGICAL_CHUNK],
refine_scope_index=[3],
)
node.refine(**common)
assert [(call["refine_scope"], call["refine_scope_index"]) for call in calls] == [
(MODE_PHYSICAL_GROUP, 2),
(MODE_LOGICAL_CHUNK, 3),
(MODE_ALL, 1),
]
with pytest.raises(ValueError, match="unsupported selective refine scope"):
node.refine(
**common,
refine_scope=["unknown"],
refine_scope_index=[1],
)
assert len(calls) == 3
def test_invalid_public_scope_fails_before_any_execution():
calls = {"encode": [], "clone": [], "sample": []}
with pytest.raises(RefineScopeError, match="not present"):
_run(
MODE_VIDEO_AUDIO,
scope=MODE_LOGICAL_CHUNK,
scope_index=99,
observers=calls,
)
assert calls == {"encode": [], "clone": [], "sample": []}
def test_terminal_logical_halves_resolve_to_the_same_group_seed():
*_, chunk_2_calls, _chunk_2_result = _run(
MODE_VIDEO_AUDIO,
scope=MODE_LOGICAL_CHUNK,
scope_index=2,
terminal=True,
)
*_, chunk_3_calls, _chunk_3_result = _run(
MODE_VIDEO_AUDIO,
scope=MODE_LOGICAL_CHUNK,
scope_index=3,
terminal=True,
)
assert len(chunk_2_calls["sample"]) == len(chunk_3_calls["sample"]) == 1
assert chunk_2_calls["sample"][0]["seed"] == chunk_3_calls["sample"][0][
"seed"
]
def test_scope_does_not_extend_assembly_plan_or_run_storage_contract():
*_all_prefix, all_result = _run(MODE_VIDEO_AUDIO)
*_scope_prefix, scoped_result = _run(
MODE_VIDEO_AUDIO,
scope=MODE_LOGICAL_CHUNK,
scope_index=2,
)
all_contract = all_result[2]["second_pass_contract"]
scoped_contract = scoped_result[2]["second_pass_contract"]
assert all_result[2].keys() == scoped_result[2].keys()
assert all_contract.keys() == scoped_contract.keys()
assert "refine_scope_contract" not in scoped_contract
assert "run_storage" not in targeted_second_pass.__dict__
+141
View File
@@ -0,0 +1,141 @@
"""Exercise the real frontend (not a copied visibility predicate) across its lifecycle."""
import shutil
import subprocess
from pathlib import Path
import pytest
def test_completed_review_lifecycle_with_real_frontend(tmp_path):
node = shutil.which("node")
assert node, "Node.js is required for this frontend gate"
source = (Path(__file__).resolve().parents[1] / "web/project_id.js").read_text(encoding="utf-8")
source = source.replace('import { app } from "../../scripts/app.js";',
'const app = globalThis.__app;').replace(
'import { normalizeReferenceAudioLabels } from "./reference_audio_ui.js";',
'function normalizeReferenceAudioLabels() {}')
harness = r'''
const assert = require("node:assert/strict");
let project = null;
let fetchMode = "ok";
globalThis.fetch = async () => {
if (fetchMode === "error") throw new Error("offline fixture");
return project ? {ok:true, status:200, json:async()=>structuredClone(project)} : {ok:false,status:404};
};
globalThis.__app = {
graph: {_nodes: [], links:{}, getNodeById:()=>null},
ui:{settings:{getSettingValue:(_id,fallback)=>fallback,addSetting(){}}},
registerExtension(extension){this.extension=extension;}
};
'''
cases = r'''
function makeNode() {
const values = {
prompt_mode:"Auto",chunks:2,chunk_seconds:5,aspect:"Auto from First Image",
preset:"Draft — 0.30 MP",custom_mp:0.3,continuity:"Balanced — 22 frames",
base_seed:123,control_after_generate:"fixed",audio_continuity:true,
continuation_backend:"Standard",run_storage:"Save + Auto Resume",
reroll_from_chunk:"Auto",reroll_nonce:0,run_name:"fixture",project_id:"fixture",
reference_size:"Match Output",video_reference_size:"Efficient - 0.4 MP",
diagnostics:"Detailed Report",strict_compatibility:false,debug:false,show_preview:true,
generation_mode:"Review Each Chunk",review_action:"Continue / Next",
take_group:0,take_revision_id:"",take_action:"Automatic",
size_source:"First Image",width:544,height:544
};
const n={comfyClass:"H3ContinuumSamplerV38",properties:{},inputs:[],
widgets:Object.entries(values).map(([name,value])=>({name,value,type:"combo",options:{values:[]},computeSize:()=>[120,20]})),
addWidget(type,name,value,callback,options){const w={type,name,value,callback,options:options||{},computeSize:()=>[120,20]};this.widgets.push(w);return w;},
addCustomWidget(w){this.widgets.push(w);return w;},
serialize(){return {widgets_values:this.widgets.map(w=>w.value)};},
configure(info){info.widgets_values.forEach((v,i)=>{this.widgets[i].value=v;});},
setDirtyCanvas(){}
};
app.extension.nodeCreated(n);
return n;
}
const w=(n,name)=>n.widgets.find(w=>w.name===name);
const visible=(n,name)=>!w(n,name).hidden;
const buttons=["Use it and continue","Try this chunk again","Use it and finish the rest"];
function state(status,unit,id="revision-1") {
return {branch_provenance_version:1,canonical_storage_revision_id:id,
revisions:[{revision_id:id,status,...(unit?{review_unit:unit}:{})}],
canonical_head_revision_id:"take-1",active_revisions:{"1":"take-1"},
group_revisions:[{revision_id:"take-1",revision_order:"1",take_number:1,group:{start:1,end:1,physical_group:1}}]};
}
async function load(n,p) {project=p;await loadTakeHistory(n);n.__h3ContinuumIntuitiveUxRefresh?.();n.__h3ContinuumProductionUxRefresh();}
(async()=>{
const n=makeNode();await load(n,null);
assert(buttons.every(name=>!visible(n,name)),"initial is not review-ready");
for(const status of ["running","interrupted","unknown"]){
await load(n,state(status,{start:1,end:1,physical_group:1}));
assert(buttons.every(name=>!visible(n,name)),status);
}
await load(n,state("review_ready",{start:1,end:1,physical_group:1}));
assert(buttons.every(name=>visible(n,name)),"partial review has all actions");
for(const action of ["Use it and continue","Use it and finish the rest"]){
w(n,action).callback();const inputs={};prepareReviewQueueIntent(n,inputs);
assert.equal(inputs.review_action,action==="Use it and continue"?"Continue / Next":"Finish Remaining");
w(n,"review_action").afterQueued({isPartialExecution:false});
assert.equal(w(n,"review_action").value,"Continue / Next");
}
for(const count of [1,2,3,4,5,6]){
w(n,"chunks").value=count;
const p=state("complete",{start:count,end:count,physical_group:count},`done-${count}`);
await load(n,p);
assert(visible(n,"Try this chunk again"),`retry complete ${count}`);
assert(!visible(n,"Use it and continue")&&!visible(n,"Use it and finish the rest"),"no no-op continuation buttons");
assert(visible(n,"Render History"));
assert.match(w(n,"Review Ready").value,/Saved sequence is complete/);
const saved=n.serialize();
w(n,"Back to Settings").callback();
assert(visible(n,"Chunks")&&visible(n,"Return to Review"));
assert(!visible(n,"Try this chunk again"));
w(n,"Return to Review").callback();
assert(visible(n,"Try this chunk again")&&!visible(n,"Chunks"));
assert.deepEqual(n.serialize(),saved,"settings/review are presentation only");
w(n,"Render History").callback();assert(visible(n,"Render History / Takes"));
const drawn=[];
const ctx={save(){},restore(){},beginPath(){},rect(){},clip(){},fillText(text){drawn.push(text);}};
w(n,"Render History / Takes").draw(ctx,n,400,0,300);
assert(drawn.some(text=>text.startsWith("Selected:")),"selected Take is actually drawn, not an empty text widget");
w(n,"Render History").callback();assert(!visible(n,"Render History / Takes"));
w(n,"Try this chunk again").callback();
const inputs={};prepareReviewQueueIntent(n,inputs);
assert.equal(inputs.review_action,"Regenerate Current");
assert.equal(w(n,"base_seed").value,123);
assert.equal(w(n,"control_after_generate").value,"fixed");
assert.match(w(n,"Review Ready").value,new RegExp(`Chunk ${count}`));
w(n,"review_action").afterQueued({isPartialExecution:false});
assert.equal(inputs.review_action,"Regenerate Current","queued payload remains immutable");
assert.equal(w(n,"review_action").value,"Continue / Next","one-shot consumed once");
assert.deepEqual(project,p,"backend evidence not rewritten");
await load(n,state("complete",{start:count,end:count,physical_group:count},`retry-${count}`));
assert(visible(n,"Try this chunk again"),"retry completion still accessible");
}
await load(n,state("complete",{start:2,end:3,physical_group:2},"terminal"));
w(n,"Try this chunk again").callback();
assert.match(w(n,"Review Ready").value,/Chunks 2-3/);
await load(n,state("complete",null,"finish-without-unit"));
assert(!visible(n,"Try this chunk again"),"do not invent a retry unit for full-run completion");
assert(visible(n,"Render History")&&visible(n,"Back to Settings"));
await load(n,state("review_ready",{physical_group:1}));
assert(!visible(n,"Try this chunk again"),"incomplete metadata not actionable");
await load(n,state("complete",{start:1,end:1,physical_group:1}));
fetchMode="error";await loadTakeHistory(n);
assert(!visible(n,"Try this chunk again"),"failed fetch cannot retain stale retry controls");
fetchMode="ok";await loadTakeHistory(n);assert(visible(n,"Try this chunk again"));
const reloaded=makeNode();await load(reloaded,project);
assert(visible(reloaded,"Try this chunk again"),"reload restores completed review from backend");
w(reloaded,"generation_mode").value="Full Run";reloaded.__h3ContinuumProductionUxRefresh();
assert(buttons.every(name=>!visible(reloaded,name)),"full run does not expose review actions");
w(reloaded,"generation_mode").value="Review Each Chunk";
w(reloaded,"run_storage").value="Off";reloaded.__h3ContinuumProductionUxRefresh();
assert(buttons.every(name=>!visible(reloaded,name)),"storage off does not expose review actions");
console.log("PASS: real frontend completed-review lifecycle");
})().catch(e=>{console.error(e);process.exitCode=1;});
'''
script = tmp_path / "completed_review.cjs"
script.write_text(harness + source + cases, encoding="utf-8")
result = subprocess.run([node, str(script)], capture_output=True, text=True, timeout=30)
assert result.returncode == 0, result.stdout + result.stderr
assert "PASS: real frontend" in result.stdout
+592
View File
@@ -0,0 +1,592 @@
from __future__ import annotations
import json
from pathlib import Path
import shutil
import subprocess
import sys
from types import ModuleType
import pytest
import torch
from ComfyUI_H3_Continuum_Join import nodes as root_nodes
from ComfyUI_H3_Continuum_Join.reference import (
REFERENCE_SIZE_MATCH_OUTPUT,
prepare_reference_assets,
validate_reference_prompts,
)
from ComfyUI_H3_Continuum_Join.v2.sequence import _terminal_flf_merge_enabled
from ComfyUI_H3_Continuum_Join.v3.driving_nodes import H3ContinuumSamplerV37
from ComfyUI_H3_Continuum_Join.v3.easy_nodes import (
EASY_ASPECT_AUTO,
EASY_ASPECT_LANDSCAPE,
EASY_ASPECT_PORTRAIT,
EASY_ASPECT_SQUARE,
EASY_PRESET_BALANCED,
EASY_PRESET_CUSTOM,
EASY_PRESET_DRAFT,
EASY_PRESET_NATIVE,
EASY_REFERENCES_TYPE,
EASY_SEED_MODE_RANDOMIZE,
H3ContinuumEasyReferences,
H3ContinuumEasyV38,
NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS,
make_easy_references,
resolve_easy_duration,
resolve_easy_references,
resolve_easy_resolution,
)
ROOT = Path(__file__).resolve().parents[1]
EASY_JS = ROOT / "web" / "easy_v38.js"
class _Image:
def __init__(self, height: int, width: int):
self.shape = (1, height, width, 3)
@pytest.mark.parametrize(
("duration", "chunks", "chunk_seconds"),
(
(4, 1, 4.0),
(10, 1, 10.0),
(15, 2, 7.5),
(20, 2, 10.0),
(30, 3, 10.0),
(160, 16, 10.0),
(480, 16, 30.0),
),
)
def test_duration_resolver_uses_approved_ten_second_policy(
duration,
chunks,
chunk_seconds,
):
plan = resolve_easy_duration(duration)
assert plan.duration_seconds == duration
assert plan.chunks == chunks
assert plan.chunk_seconds == chunk_seconds
assert plan.chunks * plan.chunk_seconds == duration
@pytest.mark.parametrize("duration", (3, 481, True, 10.5))
def test_duration_resolver_rejects_values_outside_integer_production_contract(duration):
with pytest.raises((TypeError, ValueError)):
resolve_easy_duration(duration)
def test_decimal_mp_presets_follow_first_image_aspect_and_32_pixel_grid():
first = _Image(1200, 900)
draft = resolve_easy_resolution(
aspect=EASY_ASPECT_AUTO,
preset=EASY_PRESET_DRAFT,
first_frame=first,
)
balanced = resolve_easy_resolution(
aspect=EASY_ASPECT_AUTO,
preset=EASY_PRESET_BALANCED,
first_frame=first,
)
assert (draft.width, draft.height) == (480, 640)
assert (balanced.width, balanced.height) == (672, 896)
assert draft.aspect_source == "First Image"
assert draft.width % 32 == draft.height % 32 == 0
assert balanced.width % 32 == balanced.height % 32 == 0
@pytest.mark.parametrize(
("aspect", "expected"),
(
(EASY_ASPECT_SQUARE, (768, 768)),
(EASY_ASPECT_LANDSCAPE, (1344, 768)),
(EASY_ASPECT_PORTRAIT, (768, 1344)),
),
)
def test_native_768_representative_dimensions(aspect, expected):
plan = resolve_easy_resolution(aspect=aspect, preset=EASY_PRESET_NATIVE)
assert (plan.width, plan.height) == expected
def test_native_768_preserves_extreme_aspect_by_prioritizing_long_edge_cap():
landscape = resolve_easy_resolution(
aspect=EASY_ASPECT_AUTO,
preset=EASY_PRESET_NATIVE,
first_frame=_Image(900, 2100),
)
portrait = resolve_easy_resolution(
aspect=EASY_ASPECT_AUTO,
preset=EASY_PRESET_NATIVE,
first_frame=_Image(2100, 900),
)
assert (landscape.width, landscape.height) == (1344, 576)
assert (portrait.width, portrait.height) == (576, 1344)
def test_auto_without_first_image_falls_back_to_landscape():
auto = resolve_easy_resolution(
aspect=EASY_ASPECT_AUTO,
preset=EASY_PRESET_DRAFT,
)
explicit = resolve_easy_resolution(
aspect=EASY_ASPECT_LANDSCAPE,
preset=EASY_PRESET_DRAFT,
)
assert (auto.width, auto.height) == (explicit.width, explicit.height)
assert auto.aspect_source == "Landscape 16:9 fallback"
def test_custom_mp_is_not_clamped_to_native_and_reports_diagnostics():
plan = resolve_easy_resolution(
aspect=EASY_ASPECT_SQUARE,
preset=EASY_PRESET_CUSTOM,
custom_mp=3.0,
)
assert plan.width > 768
assert plan.height > 768
assert len(plan.warnings) == 2
assert "Above Native 768" in plan.warnings[0]
assert "High Custom MP" in plan.warnings[1]
def test_easy_schema_keeps_driving_audio_optional_and_scheduler_out():
schema = H3ContinuumEasyV38.INPUT_TYPES()
required = schema["required"]
optional = schema["optional"]
assert tuple(required)[:5] == ("model", "clip", "video_vae", "sampler", "sigmas")
assert "scheduler" not in required
assert "audio_vae" not in required
assert optional["driving_audio"][0] == "AUDIO"
assert optional["driving_audio"][1]["display_name"] == "Driving Audio"
assert optional["audio_vae"][0] == "VAE"
assert optional["audio_vae"][1]["display_name"] == "Driving Audio VAE"
assert "first_frame" in optional
assert "last_frame" in optional
assert optional["references"][0] == EASY_REFERENCES_TYPE
assert not {
"driving_audio_vae",
"reference_audio_1",
"reference_audio_vae",
"reference_video_1",
"still_image_guide",
"timeline_video",
} & set(optional)
assert required["duration"][1]["default"] == 10
assert required["seed_mode"][1]["default"] == EASY_SEED_MODE_RANDOMIZE
assert required["run_storage"][1]["default"] == "Off"
assert required["prompt_text"][1]["multiline"] is True
def test_easy_node_is_registered_without_replacing_v37():
assert NODE_CLASS_MAPPINGS["H3ContinuumEasyReferences"] is (
H3ContinuumEasyReferences
)
assert NODE_DISPLAY_NAME_MAPPINGS["H3ContinuumEasyReferences"] == (
"H3 Continuum Easy References"
)
assert NODE_CLASS_MAPPINGS["H3ContinuumEasyV38"] is H3ContinuumEasyV38
assert NODE_DISPLAY_NAME_MAPPINGS["H3ContinuumEasyV38"] == (
"H3 Continuum Easy V3.8"
)
assert "H3ContinuumEasyV38" not in root_nodes.NODE_CLASS_MAPPINGS
assert "H3ContinuumSamplerV37" not in root_nodes.NODE_CLASS_MAPPINGS
assert "H3ContinuumEasyReferences" not in root_nodes.NODE_CLASS_MAPPINGS
assert H3ContinuumEasyReferences.DEPRECATED is False
assert H3ContinuumEasyV38.DEPRECATED is False
def test_easy_references_schema_has_three_fixed_optional_image_sockets_only():
schema = H3ContinuumEasyReferences.INPUT_TYPES()
assert "required" not in schema
assert tuple(schema["optional"]) == (
"reference_image_1",
"reference_image_2",
"reference_image_3",
)
assert all(value[0] == "IMAGE" for value in schema["optional"].values())
assert H3ContinuumEasyReferences.RETURN_TYPES == (EASY_REFERENCES_TYPE,)
@pytest.mark.parametrize(
"active_slots",
((), (1,), (1, 2), (1, 2, 3), (2,)),
)
def test_easy_references_preserve_fixed_slots_for_v37_mapping(active_slots):
images = {index: object() for index in range(1, 4)}
kwargs = {
f"reference_image_{index}": images[index]
for index in active_slots
}
bundle = H3ContinuumEasyReferences().pack(**kwargs)[0]
resolved = resolve_easy_references(bundle)
assert resolved == tuple(
images[index] if index in active_slots else None
for index in range(1, 4)
)
def test_easy_references_none_and_invalid_payload_contract():
assert resolve_easy_references(None) == (None, None, None)
with pytest.raises(TypeError, match="H3 Continuum Easy References"):
resolve_easy_references("not-a-reference-bundle")
with pytest.raises(ValueError, match="schema version"):
resolve_easy_references({"schema_version": 999})
@pytest.mark.parametrize(
("duration", "expected_chunks", "expected_seconds"),
((10, 1, 10.0), (15, 2, 7.5), (20, 2, 10.0), (30, 3, 10.0)),
)
def test_easy_facade_maps_to_v37_without_copying_sampling(
monkeypatch,
duration,
expected_chunks,
expected_seconds,
):
captured = {}
def fake_v37_run(_self, **kwargs):
captured.update(kwargs)
return "video", "audio", {"plan": True}, "V3.7 status", None, "refine"
monkeypatch.setattr(H3ContinuumSamplerV37, "run", fake_v37_run)
outputs = H3ContinuumEasyV38().run(
model="model",
clip="clip",
video_vae="video-vae",
sampler="sampler",
sigmas="sigmas",
prompt_text="<|caption|> literal embedding:example",
duration=duration,
seed=42,
aspect=EASY_ASPECT_AUTO,
preset=EASY_PRESET_DRAFT,
first_frame=_Image(1200, 900),
last_frame=_Image(1200, 900),
)
assert captured["chunks"] == expected_chunks
assert captured["chunk_seconds"] == expected_seconds
assert captured["sequence_prompt"] == "<|caption|> literal embedding:example"
assert captured["prompt_mode"] == "Auto"
assert (captured["width"], captured["height"]) == (480, 640)
assert captured["first_frame"] is not None
assert captured["last_frame"] is not None
assert captured["base_seed"] == 42
assert captured["run_storage"] == "Off"
assert captured["driving_audio"] is None
assert captured["audio_vae"] is None
assert len(outputs) == 5
assert "FL2VA + Continuation" in outputs[3]
assert "V3.7 status" in outputs[3]
def test_easy_driving_audio_and_vae_map_directly_to_v37(monkeypatch):
captured = {}
driving_audio = {"waveform": object(), "sample_rate": 32000}
audio_vae = object()
def fake_v37_run(_self, **kwargs):
captured.update(kwargs)
return "video", "audio", {"plan": True}, "V3.7 status", driving_audio
monkeypatch.setattr(H3ContinuumSamplerV37, "run", fake_v37_run)
outputs = H3ContinuumEasyV38().run(
model="model",
clip="clip",
video_vae="video-vae",
sampler="sampler",
sigmas="sigmas",
prompt_text="prompt",
duration=10,
seed=42,
driving_audio=driving_audio,
audio_vae=audio_vae,
)
assert captured["driving_audio"] is driving_audio
assert captured["audio_vae"] is audio_vae
assert outputs[4] is driving_audio
def test_easy_audio_vae_only_remains_normal_generation(monkeypatch):
captured = {}
audio_vae = object()
def fake_v37_run(_self, **kwargs):
captured.update(kwargs)
return "video", "generated-audio", {"plan": True}, "V3.7 status", None
monkeypatch.setattr(H3ContinuumSamplerV37, "run", fake_v37_run)
outputs = H3ContinuumEasyV38().run(
model="model",
clip="clip",
video_vae="video-vae",
sampler="sampler",
sigmas="sigmas",
prompt_text="prompt",
duration=10,
seed=42,
audio_vae=audio_vae,
)
assert captured["driving_audio"] is None
assert captured["audio_vae"] is audio_vae
assert outputs[1] == "generated-audio"
assert outputs[4] is None
def test_easy_audio_without_vae_keeps_v37_validation(monkeypatch):
def fake_v37_run(_self, **kwargs):
if kwargs["driving_audio"] is not None and kwargs["audio_vae"] is None:
raise ValueError("anchoring guide audio needs the audio_vae input")
raise AssertionError("expected the existing V3.7 validation path")
monkeypatch.setattr(H3ContinuumSamplerV37, "run", fake_v37_run)
with pytest.raises(ValueError, match="audio_vae input"):
H3ContinuumEasyV38().run(
model="model",
clip="clip",
video_vae="video-vae",
sampler="sampler",
sigmas="sigmas",
prompt_text="prompt",
duration=10,
seed=42,
driving_audio={"waveform": object(), "sample_rate": 32000},
)
def test_easy_reference_mapping_matches_direct_v37_slots_and_output_geometry(
monkeypatch,
):
captured = {}
first_ref, second_ref, third_ref = object(), object(), object()
def fake_v37_run(_self, **kwargs):
captured.update(kwargs)
return "video", "audio", {"plan": True}, "V3.7 status", None, "refine"
monkeypatch.setattr(H3ContinuumSamplerV37, "run", fake_v37_run)
references = make_easy_references(first_ref, second_ref, third_ref)
H3ContinuumEasyV38().run(
model="model",
clip="clip",
video_vae="video-vae",
sampler="sampler",
sigmas="sigmas",
prompt_text="Use <Picture 1>, <Picture 2>, and <Picture 3>.",
duration=10,
seed=42,
aspect=EASY_ASPECT_PORTRAIT,
preset=EASY_PRESET_DRAFT,
references=references,
)
direct_v37_reference_kwargs = {
"reference_image_1": first_ref,
"reference_image_2": second_ref,
"reference_image_3": third_ref,
}
assert {
key: captured[key] for key in direct_v37_reference_kwargs
} == direct_v37_reference_kwargs
assert captured["reference_size"] == REFERENCE_SIZE_MATCH_OUTPUT
assert (captured["width"], captured["height"]) == (416, 736)
@pytest.mark.parametrize(
("first_frame", "last_frame", "expected_mode"),
(
(_Image(640, 480), None, "Hybrid I2VA + Reference + Continuation"),
(
_Image(640, 480),
_Image(640, 480),
"Hybrid FL2VA + Reference + Continuation",
),
),
)
def test_easy_status_reports_first_last_with_reference(
monkeypatch,
first_frame,
last_frame,
expected_mode,
):
def fake_v37_run(_self, **_kwargs):
return "video", "audio", {"plan": True}, "V3.7 status", None, "refine"
monkeypatch.setattr(H3ContinuumSamplerV37, "run", fake_v37_run)
outputs = H3ContinuumEasyV38().run(
model="model",
clip="clip",
video_vae="video-vae",
sampler="sampler",
sigmas="sigmas",
prompt_text="Use <Picture 1>.",
duration=10,
seed=42,
first_frame=first_frame,
last_frame=last_frame,
references=make_easy_references(object()),
)
assert expected_mode in outputs[3]
def test_easy_reference_gap_compacts_to_picture_one_in_existing_v37_preprocessing():
second = torch.ones((1, 32, 32, 3))
refs = resolve_easy_references(
make_easy_references(reference_image_2=second)
)
assets = prepare_reference_assets(
reference_image_1=refs[0],
reference_image_2=refs[1],
reference_image_3=refs[2],
output_width=480,
output_height=640,
size_mode=REFERENCE_SIZE_MATCH_OUTPUT,
)
assert assets is not None
assert assets.count == 1
assert torch.equal(assets.images[0], second)
assert validate_reference_prompts(["Use <Picture 1>."], assets.count) == ""
assert "unavailable <Picture 2>" in validate_reference_prompts(
["Use <Picture 2>."], assets.count
)
def test_easy_reference_size_uses_existing_v37_output_geometry_policy(monkeypatch):
comfy_module = ModuleType("comfy")
comfy_utils_module = ModuleType("comfy.utils")
def common_upscale(image, width, height, _method, _crop):
return torch.nn.functional.interpolate(
image,
size=(height, width),
mode="bilinear",
align_corners=False,
)
comfy_utils_module.common_upscale = common_upscale
comfy_module.utils = comfy_utils_module
monkeypatch.setitem(sys.modules, "comfy", comfy_module)
monkeypatch.setitem(sys.modules, "comfy.utils", comfy_utils_module)
source = torch.zeros((1, 512, 1024, 3))
refs = resolve_easy_references(make_easy_references(source))
assets = prepare_reference_assets(
reference_image_1=refs[0],
reference_image_2=refs[1],
reference_image_3=refs[2],
output_width=320,
output_height=320,
size_mode=REFERENCE_SIZE_MATCH_OUTPUT,
)
assert assets is not None
height, width = assets.images[0].shape[1:3]
assert width * height <= 320 * 320
assert width % 32 == height % 32 == 0
assert width == 2 * height
@pytest.mark.parametrize("duration", (10, 15, 20, 30))
def test_approved_easy_fl2va_durations_do_not_enter_five_second_terminal_merge(
duration,
):
plan = resolve_easy_duration(duration)
enabled = _terminal_flf_merge_enabled(
multi_chunk_flf=plan.chunks >= 2,
chunks=plan.chunks,
chunk_seconds=plan.chunk_seconds,
prompt_hashes=["p"] * plan.chunks,
timeline_video_source=None,
)
assert enabled is False
def _function_source(source: str, name: str, next_name: str) -> str:
start = source.index(f"function {name}")
end = source.index(f"function {next_name}", start)
return source[start:end]
def test_easy_frontend_maps_only_randomize_fixed_and_hides_conditional_widgets(tmp_path):
node_executable = shutil.which("node")
if node_executable is None:
pytest.skip("Node.js is required for the frontend behavior regression")
source = EASY_JS.read_text(encoding="utf-8")
functions = "\n".join(
(
_function_source(source, "findWidget", "setWidgetVisible"),
_function_source(source, "setWidgetVisible", "attachRefresh"),
_function_source(source, "attachRefresh", "createProjectId"),
_function_source(source, "createProjectId", "seedControlWidget"),
_function_source(source, "seedControlWidget", "configureEasyNode"),
_function_source(source, "configureEasyNode", "configureEasyNodeAfterSetup"),
)
)
script = f"""
const EASY_NODE_CLASS = "H3ContinuumEasyV38";
const CUSTOM_PRESET = "Custom";
const STORAGE_ENABLED = "Save + Auto Resume";
{functions}
function widget(name, value) {{
return {{ name, value, type: "combo", options: {{}}, computeSize: () => [120, 20] }};
}}
const node = {{
comfyClass: EASY_NODE_CLASS,
widgets: [
widget("preset", "Draft — 0.30 MP"),
widget("custom_mp", 0.3),
widget("run_storage", "Off"),
widget("run_name", ""),
widget("seed_mode", "Randomize"),
widget("control_after_generate", "fixed"),
widget("project_id", "test-project"),
],
setDirtyCanvas() {{}},
}};
configureEasyNode(node);
const observed = {{
initialControl: findWidget(node, "control_after_generate").value,
controlHidden: findWidget(node, "control_after_generate").hidden,
customHidden: findWidget(node, "custom_mp").hidden,
runNameHidden: findWidget(node, "run_name").hidden,
projectHidden: findWidget(node, "project_id").hidden,
}};
findWidget(node, "seed_mode").value = "Fixed";
findWidget(node, "seed_mode").callback("Fixed");
findWidget(node, "preset").value = "Custom";
findWidget(node, "preset").callback("Custom");
findWidget(node, "run_storage").value = "Save + Auto Resume";
findWidget(node, "run_storage").callback("Save + Auto Resume");
observed.fixedControl = findWidget(node, "control_after_generate").value;
observed.customVisible = !findWidget(node, "custom_mp").hidden;
observed.runNameVisible = !findWidget(node, "run_name").hidden;
console.log(JSON.stringify(observed));
"""
script_path = tmp_path / "easy-v38-frontend.js"
script_path.write_text(script, encoding="utf-8")
result = subprocess.run(
[node_executable, str(script_path)],
check=True,
capture_output=True,
text=True,
)
observed = json.loads(result.stdout)
assert observed == {
"initialControl": "randomize",
"controlHidden": True,
"customHidden": True,
"runNameHidden": True,
"projectHidden": True,
"fixedControl": "fixed",
"customVisible": True,
"runNameVisible": True,
}
+214
View File
@@ -0,0 +1,214 @@
from __future__ import annotations
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
WORKFLOW_PATH = (
ROOT / "examples" / "workflows" / "MiniMax_H3_Continuum_Easy_V38.json"
)
def _workflow() -> dict:
return json.loads(WORKFLOW_PATH.read_text(encoding="utf-8"))
def _one_node(workflow: dict, node_type: str) -> dict:
values = [node for node in workflow["nodes"] if node["type"] == node_type]
assert len(values) == 1
return values[0]
def _link_map(workflow: dict) -> dict[int, list]:
return {int(link[0]): link for link in workflow["links"]}
FORBIDDEN_MINIMAL_MARKERS = (
"power lora loader",
"rgthree",
"easy cleangpuused",
"spectrum",
"hires",
"hi-res",
"second pass",
"secondpass",
"upscale",
"minimaxchunkfeedforward",
"sageattention",
)
def test_v38_easy_public_workflow_uses_the_approved_default_contract():
workflow = _workflow()
easy = _one_node(workflow, "H3ContinuumEasyV38")
helper = _one_node(workflow, "H3ContinuumEasyReferences")
assert easy["widgets_values"][:10] == [
"",
10,
0,
"randomize",
"Randomize",
"Auto from First Image",
"Draft — 0.30 MP",
0.3,
"Off",
"",
]
easy_widget_names = [
"prompt_text",
"duration",
"seed",
"control_after_generate",
"seed_mode",
"aspect",
"preset",
"custom_mp",
"run_storage",
"run_name",
"project_id",
]
assert easy["widgets_values"] == [
easy["widgets_values_named"][name] for name in easy_widget_names
]
assert [item["name"] for item in easy["inputs"]] == [
"model",
"clip",
"video_vae",
"sampler",
"sigmas",
"first_frame",
"last_frame",
"references",
"driving_audio",
"audio_vae",
"prompt_text",
]
assert helper["outputs"][0]["type"] == "H3_CONTINUUM_EASY_REFERENCES"
assert [item["name"] for item in helper["inputs"]] == [
"reference_image_1",
"reference_image_2",
"reference_image_3",
]
assert not {
"reference_audio_1",
"reference_video_1",
"timeline_video",
"guide",
} & {item["name"] for item in easy["inputs"]}
assert len(workflow["nodes"]) == 20
assert len([node for node in workflow["nodes"] if node["type"] == "H3EasyLoadImage"]) == 5
audio_loader = _one_node(workflow, "H3EasyLoadAudio")
assert int(audio_loader["mode"]) == 4
assert audio_loader.get("title", "") == ""
assert [output["type"] for output in audio_loader["outputs"]] == ["AUDIO"]
assert not [node for node in workflow["nodes"] if node["type"] == "LoadImage"]
assert workflow["extra"] == {
"frontendVersion": "1.49.6",
"ds": workflow["extra"]["ds"],
}
def test_v38_easy_public_workflow_is_strict_minimal():
workflow = _workflow()
node_types = [str(node["type"]) for node in workflow["nodes"]]
searchable = "\n".join(node_types).lower()
assert not [marker for marker in FORBIDDEN_MINIMAL_MARKERS if marker in searchable]
assert not [
node
for node in workflow["nodes"]
if node.get("properties", {}).get("cnr_id")
not in {None, "", "comfy-core"}
]
assert "PreviewAny" not in node_types
assert "MarkdownNote" not in node_types
scheduler = _one_node(workflow, "BasicScheduler")
assert scheduler["widgets_values_named"] == {
"scheduler": "simple",
"steps": 20,
"denoise": 1,
}
def test_v38_easy_public_workflow_defaults_to_t2va_with_optional_hybrids():
workflow = _workflow()
nodes = {int(node["id"]): node for node in workflow["nodes"]}
links = _link_map(workflow)
easy = _one_node(workflow, "H3ContinuumEasyV38")
helper = _one_node(workflow, "H3ContinuumEasyReferences")
helper_inputs = {item["name"]: item for item in helper["inputs"]}
source_modes = {}
for name, input_ in helper_inputs.items():
link = links[int(input_["link"])]
source_modes[name] = int(nodes[int(link[1])]["mode"])
assert source_modes == {
"reference_image_1": 4,
"reference_image_2": 4,
"reference_image_3": 4,
}
easy_inputs = {item["name"]: item for item in easy["inputs"]}
first_source = nodes[int(links[int(easy_inputs["first_frame"]["link"])][1])]
last_source = nodes[int(links[int(easy_inputs["last_frame"]["link"])][1])]
assert int(first_source["mode"]) == 4
assert int(last_source["mode"]) == 4
assert links[int(easy_inputs["references"]["link"])][1] == helper["id"]
prompt_link = links[int(easy_inputs["prompt_text"]["link"])]
prompt_node = nodes[int(prompt_link[1])]
assert "<Picture" not in prompt_node["widgets_values"][0]
def test_v38_easy_public_workflow_keeps_core_display_titles_standard():
workflow = _workflow()
core_nodes = [
node
for node in workflow["nodes"]
if node.get("properties", {}).get("cnr_id") == "comfy-core"
]
assert core_nodes
assert all(not node.get("title") for node in core_nodes)
def test_v38_easy_public_workflow_links_are_closed_and_unique():
workflow = _workflow()
nodes = {int(node["id"]) for node in workflow["nodes"]}
links = _link_map(workflow)
assert len(links) == len(workflow["links"])
for link_id, link in links.items():
assert int(link[0]) == link_id
assert int(link[1]) in nodes
assert int(link[3]) in nodes
for node in workflow["nodes"]:
for input_ in node.get("inputs", []):
if input_.get("link") is not None:
assert int(input_["link"]) in links
for output in node.get("outputs", []):
for link_id in output.get("links") or []:
assert int(link_id) in links
assert json.loads(json.dumps(workflow, ensure_ascii=False)) == workflow
assert len({int(node["id"]) for node in workflow["nodes"]}) == len(
workflow["nodes"]
)
def test_easy_image_loaders_use_native_modes_without_custom_titles():
workflow = _workflow()
loaders = {
int(node["id"]): node
for node in workflow["nodes"]
if node["type"] == "H3EasyLoadImage"
}
assert {node_id: int(node["mode"]) for node_id, node in loaders.items()} == {
114: 4,
290: 4,
258: 4,
257: 4,
264: 4,
}
for node in loaders.values():
assert node.get("title", "") == ""
assert node["properties"] == {"Node name for S&R": "H3EasyLoadImage"}
assert [output["type"] for output in node["outputs"]] == ["IMAGE", "MASK"]
+181
View File
@@ -0,0 +1,181 @@
import json
from pathlib import Path
import shutil
import subprocess
import pytest
from ComfyUI_H3_Continuum_Join.v3.driving_nodes import H3ContinuumSamplerV38
ROOT = Path(__file__).resolve().parents[1]
PROJECT_ID_JS = ROOT / "web" / "project_id.js"
def _function_source(source: str, name: str, next_name: str) -> str:
start = source.index(f"function {name}")
end = source.index(f"function {next_name}", start)
return source[start:end]
def test_v38_public_sampler_inputs_all_have_hover_help():
schema = H3ContinuumSamplerV38.INPUT_TYPES()
missing = []
for group in ("required", "optional"):
for name, definition in schema[group].items():
metadata = definition[1] if len(definition) > 1 else {}
if not str(metadata.get("tooltip", "")).strip():
missing.append(f"{group}.{name}")
assert missing == []
def test_v38_main_facade_help_covers_every_visible_control():
source = PROJECT_ID_JS.read_text(encoding="utf-8")
facade_names = (
"FACADE_PROMPT_FORMAT_WIDGET",
"FACADE_CONTINUITY_WIDGET",
"FACADE_BASE_SEED_WIDGET",
"FACADE_CONTROL_AFTER_WIDGET",
"FACADE_AUDIO_CONTINUITY_WIDGET",
"FACADE_CHUNKS_WIDGET",
"FACADE_SECONDS_WIDGET",
"FACADE_TOTAL_LENGTH_WIDGET",
"FACADE_GENERATE_WIDGET",
"FACADE_SIZE_SOURCE_WIDGET",
"FACADE_RESOLUTION_WIDGET",
"FACADE_CUSTOM_MP_WIDGET",
"FACADE_WIDTH_WIDGET",
"FACADE_HEIGHT_WIDGET",
"FACADE_SAVE_WIDGET",
"FACADE_READY_WIDGET",
"FACADE_REFERENCE_SIZE_WIDGET",
"FACADE_VIDEO_SIZE_WIDGET",
"FACADE_ADVANCED_WIDGET",
)
for name in facade_names:
assert f"[{name}]" in source
assert "function setWidgetTooltip(widget, tooltip)" in source
assert "widget.tooltip = tooltip;" in source
assert "widget.options.tooltip = tooltip;" in source
assert "function facadeWidgetTooltip(node, name)" in source
assert "function applyV38WidgetHelp(node)" in source
assert "applyV38WidgetHelp(node);" in source
def test_v38_size_help_explains_t2va_i2va_and_resolution_choices():
source = PROJECT_ID_JS.read_text(encoding="utf-8")
for marker in (
"Use this for T2VA",
"Use this for I2VA or FL2VA",
"Draft — 0.30 MP",
"Balanced — 0.60 MP",
"Native 768",
"Efficient - 0.4 MP",
"Match Output",
"Review Each Chunk",
"Render History",
):
assert marker in source
def test_v38_hover_help_is_attached_and_updates_with_current_selection(tmp_path):
node_executable = shutil.which("node")
if node_executable is None:
pytest.skip("Node.js is required for the frontend tooltip regression")
source = PROJECT_ID_JS.read_text(encoding="utf-8")
constants = source[
source.index("const PROJECT_WIDGET") : source.index("const V38_VIEW_PROPERTY")
]
functions = "\n".join(
(
_function_source(source, "findWidget", "setWidgetVisible"),
_function_source(source, "linkedInput", "attachRefresh"),
_function_source(
source, "facadeProductionWidgets", "addFacadeWidget"
),
_function_source(source, "setWidgetTooltip", "facadeWidgetTooltip"),
_function_source(source, "facadeWidgetTooltip", "applyV38WidgetHelp"),
_function_source(
source, "applyV38WidgetHelp", "installCompactNumberDisplay"
),
)
)
script = f"""
{constants}
{functions}
const facadeNames = [
FACADE_PROMPT_FORMAT_WIDGET, FACADE_CONTINUITY_WIDGET, FACADE_BASE_SEED_WIDGET,
FACADE_CONTROL_AFTER_WIDGET, FACADE_AUDIO_CONTINUITY_WIDGET,
FACADE_CHUNKS_WIDGET, FACADE_SECONDS_WIDGET, FACADE_TOTAL_LENGTH_WIDGET,
FACADE_SIZE_SOURCE_WIDGET, FACADE_RESOLUTION_WIDGET, FACADE_CUSTOM_MP_WIDGET,
FACADE_WIDTH_WIDGET, FACADE_HEIGHT_WIDGET, FACADE_SAVE_WIDGET,
FACADE_GENERATE_WIDGET, FACADE_READY_WIDGET, FACADE_REFERENCE_SIZE_WIDGET,
FACADE_VIDEO_SIZE_WIDGET, FACADE_ADVANCED_WIDGET,
];
const sourceValues = {{
[GENERATION_MODE_WIDGET]: GENERATION_MODE_REVIEW,
[SIZE_SOURCE_WIDGET]: SIZE_SOURCE_FIRST_IMAGE,
[RESOLUTION_PRESET_WIDGET]: RESOLUTION_PRESET_DRAFT,
[RUN_STORAGE_WIDGET]: "Save + Auto Resume",
[REFERENCE_SIZE_WIDGET]: "Match Output",
[VIDEO_REFERENCE_SIZE_WIDGET]: "Efficient - 0.4 MP",
}};
const node = {{
widgets: [],
inputs: [{{ name: "first_frame", link: 1 }}],
}};
for (const [name, value] of Object.entries(sourceValues)) {{
node.widgets.push({{ name, value, options: {{}} }});
}}
for (const name of Object.keys(ADVANCED_WIDGET_HELP)) {{
if (!node.widgets.some((widget) => widget.name === name)) {{
node.widgets.push({{ name, value: null, options: {{}} }});
}}
}}
for (const name of facadeNames) {{
node.widgets.push({{ name, value: null, options: {{}}, [FACADE_TRANSIENT_WIDGET]: true }});
}}
applyV38WidgetHelp(node);
const firstImageHelp = findWidget(node, FACADE_SIZE_SOURCE_WIDGET).tooltip;
const firstPass = {{
missingFacade: facadeProductionWidgets(node).filter((widget) => !widget.tooltip).map((widget) => widget.name),
missingFacadeOptions: facadeProductionWidgets(node).filter((widget) => !widget.options.tooltip).map((widget) => widget.name),
missingAdvanced: Object.keys(ADVANCED_WIDGET_HELP).filter((name) => !findWidget(node, name)?.tooltip),
firstImageHelp,
reviewHelp: findWidget(node, FACADE_GENERATE_WIDGET).tooltip,
}};
findWidget(node, SIZE_SOURCE_WIDGET).value = SIZE_SOURCE_MANUAL;
findWidget(node, RESOLUTION_PRESET_WIDGET).value = RESOLUTION_PRESET_NATIVE;
findWidget(node, RUN_STORAGE_WIDGET).value = "Off";
applyV38WidgetHelp(node);
console.log(JSON.stringify({{
firstPass,
manualHelp: findWidget(node, FACADE_SIZE_SOURCE_WIDGET).tooltip,
nativeHelp: findWidget(node, FACADE_RESOLUTION_WIDGET).tooltip,
storageOffHelp: findWidget(node, FACADE_SAVE_WIDGET).tooltip,
}}));
"""
script_path = tmp_path / "v38-hover-help.mjs"
script_path.write_text(script, encoding="utf-8")
result = subprocess.run(
[node_executable, str(script_path)],
check=True,
capture_output=True,
text=True,
)
observed = json.loads(result.stdout)
assert observed["firstPass"]["missingFacade"] == []
assert observed["firstPass"]["missingFacadeOptions"] == []
assert observed["firstPass"]["missingAdvanced"] == []
assert "I2VA or FL2VA" in observed["firstPass"]["firstImageHelp"]
assert "Review Each Chunk" in observed["firstPass"]["reviewHelp"]
assert "Set Chunks to 2 or more" in observed["firstPass"]["reviewHelp"]
assert "T2VA" in observed["manualHelp"]
assert "Native 768" in observed["nativeHelp"]
assert "does not keep resumable chunk history" in observed["storageOffHelp"]
+261
View File
@@ -0,0 +1,261 @@
from __future__ import annotations
import ast
from pathlib import Path
import torch
from ComfyUI_H3_Continuum_Join import nodes as root_nodes
from ComfyUI_H3_Continuum_Join.reference import (
REFERENCE_SIZE_MATCH_OUTPUT,
REFERENCE_SIZE_MAX_IDENTITY,
combine_hybrid_visual_identity,
prepare_reference_assets,
)
from ComfyUI_H3_Continuum_Join.reference_video import (
REFERENCE_VIDEO_SIZE_BALANCED,
REFERENCE_VIDEO_SIZE_EFFICIENT,
REFERENCE_VIDEO_SIZE_MATCH_OUTPUT,
)
from ComfyUI_H3_Continuum_Join.v3.driving_nodes import (
H3ContinuumMemoryActionPolicyExperimental,
H3ContinuumSamplerV38,
H3ContinuumSamplerV38MemoryPolicyExperimental,
NODE_CLASS_MAPPINGS,
NODE_DISPLAY_NAME_MAPPINGS,
)
from ComfyUI_H3_Continuum_Join.v3.memory_action_policy import (
ACTION_DISABLED,
ACTION_REDUCE_REFERENCES_ONE_STEP,
MEMORY_ACTION_POLICY_VERSION,
format_memory_action_status,
make_memory_action_policy,
resolve_memory_action_policy,
)
ROOT = Path(__file__).resolve().parents[1]
def _resolve(policy, *, image=True, video=True, image_mode=None, video_mode=None):
return resolve_memory_action_policy(
policy,
image_mode=image_mode or REFERENCE_SIZE_MAX_IDENTITY,
video_mode=video_mode or REFERENCE_VIDEO_SIZE_MATCH_OUTPUT,
has_reference_images=image,
has_video_guide=video,
)
def test_policy_contract_is_versioned_deterministic_and_tamper_evident():
first = make_memory_action_policy(ACTION_REDUCE_REFERENCES_ONE_STEP)
second = make_memory_action_policy(ACTION_REDUCE_REFERENCES_ONE_STEP)
assert first == second
assert first["memory_action_policy_version"] == MEMORY_ACTION_POLICY_VERSION
assert len(first["contract_hash"]) == 64
assert first["auto_unload"] == "advisory_only"
assert first["backend_switch"] == "advisory_only"
assert first["same_run_actual_row_trigger"] is False
modified = dict(first, action="unsupported")
decision = _resolve(modified)
assert decision.enabled is False
assert decision.warning is not None
assert decision.effective_image_mode == REFERENCE_SIZE_MAX_IDENTITY
assert decision.effective_video_mode == REFERENCE_VIDEO_SIZE_MATCH_OUTPUT
def test_disabled_and_disconnected_are_complete_resolver_noops():
disconnected = _resolve(None)
disabled = _resolve(make_memory_action_policy(ACTION_DISABLED))
for decision in (disconnected, disabled):
assert decision.enabled is False
assert decision.applied is False
assert decision.effective_image_mode == REFERENCE_SIZE_MAX_IDENTITY
assert decision.effective_video_mode == REFERENCE_VIDEO_SIZE_MATCH_OUTPUT
assert format_memory_action_status(decision) is None
def test_one_step_reference_resolver_uses_only_existing_presets():
policy = make_memory_action_policy(ACTION_REDUCE_REFERENCES_ONE_STEP)
first = _resolve(policy)
assert first.effective_image_mode == REFERENCE_SIZE_MATCH_OUTPUT
assert first.effective_video_mode == REFERENCE_VIDEO_SIZE_BALANCED
assert first.image_applied is True
assert first.video_applied is True
second = _resolve(
policy,
image_mode=REFERENCE_SIZE_MATCH_OUTPUT,
video_mode=REFERENCE_VIDEO_SIZE_BALANCED,
)
assert second.effective_image_mode == REFERENCE_SIZE_MATCH_OUTPUT
assert second.effective_video_mode == REFERENCE_VIDEO_SIZE_EFFICIENT
assert second.image_applied is False
assert second.video_applied is True
minimum = _resolve(
policy,
image_mode=REFERENCE_SIZE_MATCH_OUTPUT,
video_mode=REFERENCE_VIDEO_SIZE_EFFICIENT,
)
assert minimum.applied is False
def test_one_step_policy_changes_only_connected_reference_kinds():
policy = make_memory_action_policy(ACTION_REDUCE_REFERENCES_ONE_STEP)
image_only = _resolve(policy, video=False)
assert image_only.image_applied is True
assert image_only.video_applied is False
assert image_only.effective_video_mode == REFERENCE_VIDEO_SIZE_MATCH_OUTPUT
video_only = _resolve(policy, image=False)
assert video_only.image_applied is False
assert video_only.video_applied is True
assert video_only.effective_image_mode == REFERENCE_SIZE_MAX_IDENTITY
def test_effective_reference_contract_changes_existing_run_storage_identity():
image = torch.zeros((1, 32, 32, 3), dtype=torch.float32)
original = prepare_reference_assets(
reference_image_1=image,
reference_image_2=None,
output_width=32,
output_height=32,
size_mode=REFERENCE_SIZE_MAX_IDENTITY,
)
downgraded = prepare_reference_assets(
reference_image_1=image,
reference_image_2=None,
output_width=32,
output_height=32,
size_mode=REFERENCE_SIZE_MATCH_OUTPUT,
)
assert original is not None and downgraded is not None
assert original.contract["size_mode"] == REFERENCE_SIZE_MAX_IDENTITY
assert downgraded.contract["size_mode"] == REFERENCE_SIZE_MATCH_OUTPUT
assert original.combined_hash != downgraded.combined_hash
base = "a" * 64
assert combine_hybrid_visual_identity(
keyframe_identity_hash=base,
reference_assets=original,
has_first=False,
has_last=False,
) != combine_hybrid_visual_identity(
keyframe_identity_hash=base,
reference_assets=downgraded,
has_first=False,
has_last=False,
)
def test_existing_v38_schema_is_unchanged_and_experimental_input_is_additive():
production = H3ContinuumSamplerV38.INPUT_TYPES()
experimental = H3ContinuumSamplerV38MemoryPolicyExperimental.INPUT_TYPES()
assert "memory_action_policy" not in production.get("required", {})
assert "memory_action_policy" not in production.get("optional", {})
assert production["required"] == experimental["required"]
expected_optional = dict(production.get("optional", {}))
actual_optional = dict(experimental.get("optional", {}))
policy_input = actual_optional.pop("memory_action_policy")
assert actual_optional == expected_optional
assert policy_input[0] == "H3_CONTINUUM_MEMORY_ACTION_POLICY"
def test_nodes_are_additively_registered_under_advanced_category():
policy_id = "H3ContinuumMemoryActionPolicyExperimental"
sampler_id = "H3ContinuumSamplerV38MemoryPolicyExperimental"
assert NODE_CLASS_MAPPINGS[policy_id] is H3ContinuumMemoryActionPolicyExperimental
assert NODE_CLASS_MAPPINGS[sampler_id] is (
H3ContinuumSamplerV38MemoryPolicyExperimental
)
assert policy_id not in root_nodes.NODE_CLASS_MAPPINGS
assert sampler_id not in root_nodes.NODE_CLASS_MAPPINGS
assert NODE_DISPLAY_NAME_MAPPINGS[policy_id].endswith("(Experimental)")
assert NODE_DISPLAY_NAME_MAPPINGS[sampler_id].endswith("(Experimental)")
assert H3ContinuumMemoryActionPolicyExperimental.CATEGORY.endswith("/Advanced")
assert H3ContinuumSamplerV38MemoryPolicyExperimental.CATEGORY.endswith(
"/Advanced"
)
def test_experimental_disabled_delegates_exact_kwargs_and_output(monkeypatch):
captured = []
sentinel = object()
def fake_run(self, **kwargs):
captured.append(kwargs)
return sentinel
monkeypatch.setattr(H3ContinuumSamplerV38, "run", fake_run)
node = H3ContinuumSamplerV38MemoryPolicyExperimental()
kwargs = {
"reference_size": REFERENCE_SIZE_MAX_IDENTITY,
"video_reference_size": REFERENCE_VIDEO_SIZE_MATCH_OUTPUT,
"reference_image_1": object(),
"reference_video_1": object(),
"base_seed": 123,
"sigmas": object(),
}
assert node.run(**kwargs) is sentinel
assert captured[-1] == kwargs
assert node.run(
memory_action_policy=make_memory_action_policy(ACTION_DISABLED),
**kwargs,
) is sentinel
assert captured[-1] == kwargs
def test_experimental_active_changes_only_effective_reference_modes(monkeypatch):
captured = {}
video = object()
audio = object()
plan = {"groups": [[1]]}
def fake_run(self, **kwargs):
captured.update(kwargs)
return (video, audio, plan, "Production status", "driving")
monkeypatch.setattr(H3ContinuumSamplerV38, "run", fake_run)
seed = 42
sigmas = object()
result = H3ContinuumSamplerV38MemoryPolicyExperimental().run(
memory_action_policy=make_memory_action_policy(
ACTION_REDUCE_REFERENCES_ONE_STEP
),
reference_size=REFERENCE_SIZE_MAX_IDENTITY,
video_reference_size=REFERENCE_VIDEO_SIZE_BALANCED,
reference_image_1=object(),
reference_video_1=object(),
base_seed=seed,
sigmas=sigmas,
)
assert captured["reference_size"] == REFERENCE_SIZE_MATCH_OUTPUT
assert captured["video_reference_size"] == REFERENCE_VIDEO_SIZE_EFFICIENT
assert captured["base_seed"] == seed
assert captured["sigmas"] is sigmas
assert result[:3] == (video, audio, plan)
assert result[4] == "driving"
assert "automatic MODEL unload was not executed" in result[3]
assert "external MODEL wrapper was preserved" in result[3]
def test_policy_code_has_no_runtime_unload_or_backend_switch_calls():
called_names = set()
for path in (ROOT / "v3" / "memory_action_policy.py", ROOT / "v3" / "driving_nodes.py"):
tree = ast.parse(path.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
if isinstance(node.func, ast.Name):
called_names.add(node.func.id)
elif isinstance(node.func, ast.Attribute):
called_names.add(node.func.attr)
assert called_names.isdisjoint(
{
"unload_all_models",
"unload_model_and_clones",
"soft_empty_cache",
"optimized_attention_override",
}
)
+312
View File
@@ -0,0 +1,312 @@
from __future__ import annotations
from types import SimpleNamespace
import pytest
import torch
from ComfyUI_H3_Continuum_Join import nodes as root_nodes
from ComfyUI_H3_Continuum_Join.graph_contract import build_upstream_graph_contract
from ComfyUI_H3_Continuum_Join.reference import ReferenceAssets, encode_reference_prompt
from ComfyUI_H3_Continuum_Join.reference_audio import (
H3ContinuumReferenceAudios,
REFERENCE_AUDIOS_TYPE,
ReferenceAudioError,
combine_reference_audio_identity,
encode_reference_audio_input,
prepare_reference_audio_bundle,
prepare_reference_audio_source,
resolve_reference_audio_input,
validate_reference_audio_prompts,
)
from ComfyUI_H3_Continuum_Join.v2.h3_builder import encode_prompt_conditioning
from ComfyUI_H3_Continuum_Join.v3.driving_nodes import (
H3ContinuumSamplerV37,
H3ContinuumSamplerV38,
)
def _audio(value: float) -> dict:
return {
"waveform": torch.full((1, 2, 320), value, dtype=torch.float32),
"sample_rate": 32000,
}
class _AudioVAE:
audio_sample_rate = 32000
def __init__(self):
self.inputs = []
def encode(self, waveform):
self.inputs.append(waveform.clone())
value = float(waveform.mean().item())
return torch.full((1, 32, 2, len(self.inputs)), value, dtype=torch.float32)
class _Clip:
def __init__(self):
self.options = None
def tokenize(self, prompt, **kwargs):
self.options = kwargs
return prompt
def encode_from_tokens_scheduled(self, tokens):
return [[torch.zeros((1, 1, 2)), {}]]
def test_public_helper_and_v38_socket_are_the_only_surface_additions():
helper_id = "H3ContinuumReferenceAudios"
helper_schema = H3ContinuumReferenceAudios.INPUT_TYPES()
v37 = H3ContinuumSamplerV37.INPUT_TYPES()
v38 = H3ContinuumSamplerV38.INPUT_TYPES()
assert root_nodes.NODE_CLASS_MAPPINGS[helper_id] is H3ContinuumReferenceAudios
assert root_nodes.NODE_DISPLAY_NAME_MAPPINGS[helper_id] == (
"H3 Continuum Reference Audios"
)
assert tuple(helper_schema) == ("optional",)
assert tuple(helper_schema["optional"]) == (
"reference_audio_1",
"reference_audio_2",
"reference_audio_3",
"reference_audio_vae",
)
assert H3ContinuumReferenceAudios.RETURN_TYPES == (REFERENCE_AUDIOS_TYPE,)
assert "audio_references" not in v37["optional"]
assert list(v38["optional"])[:-1] == list(v37["optional"])
assert v38["optional"]["audio_references"][0] == REFERENCE_AUDIOS_TYPE
def test_helper_preserves_order_and_requires_contiguous_core_numbering():
vae = _AudioVAE()
bundle = H3ContinuumReferenceAudios().pack(
_audio(0.1), _audio(0.2), _audio(0.3), vae
)[0]
assert bundle.count == 3
assert bundle.reference_audio_vae is vae
assert [item.source_sha256 for item in bundle.sources] == [
item["reference_audio"]["source_sha256"]
for item in bundle.contract["items"]
]
assert [item["audio_index"] for item in bundle.contract["items"]] == [1, 2, 3]
with pytest.raises(ReferenceAudioError, match="without gaps"):
prepare_reference_audio_bundle(_audio(0.1), None, _audio(0.3), vae)
assert prepare_reference_audio_bundle(None, None, None, vae) is None
def test_bundle_order_changes_run_identity_and_legacy_identity_stays_v1():
vae = _AudioVAE()
first = prepare_reference_audio_bundle(_audio(0.1), _audio(0.2), None, vae)
swapped = prepare_reference_audio_bundle(_audio(0.2), _audio(0.1), None, vae)
assert first is not None and swapped is not None
first_identity = combine_reference_audio_identity("visual", first)
swapped_identity = combine_reference_audio_identity("visual", swapped)
assert first_identity != swapped_identity
assert first.contract != swapped.contract
legacy = SimpleNamespace(combined_hash="audio")
assert combine_reference_audio_identity("visual", legacy) == (
"59fa60ba2a9a19525222c867aa2c2b8350dbf6af1e24ad34056317bcd40c81cb"
)
def test_legacy_and_bundle_inputs_cannot_be_mixed():
vae = _AudioVAE()
bundle = prepare_reference_audio_bundle(_audio(0.1), _audio(0.2), None, vae)
with pytest.raises(ReferenceAudioError, match="not both"):
resolve_reference_audio_input(_audio(0.1), vae, bundle)
resolved, resolved_vae = resolve_reference_audio_input(None, object(), bundle)
assert resolved is bundle
assert resolved_vae is vae
def test_each_reference_is_encoded_independently_in_order():
vae = _AudioVAE()
bundle = prepare_reference_audio_bundle(_audio(0.1), _audio(0.2), _audio(0.3), vae)
assert bundle is not None
assets = encode_reference_audio_input(vae, bundle, cache_enabled=False)
assert isinstance(assets, tuple)
assert len(assets) == 3
assert len(vae.inputs) == 3
assert [round(float(item.audio_latent.mean().item()), 3) for item in assets] == [
0.1,
0.2,
0.3,
]
def test_three_assets_follow_core_tokenizer_and_packed_ref_order():
latents = tuple(
SimpleNamespace(audio_latent=torch.full((1, 32, 2, index), float(index)))
for index in (1, 2, 3)
)
clip = _Clip()
conditioning = encode_prompt_conditioning(
clip,
"<Audio 1> woman; <Audio 2> man; <Audio 3> ambience.",
first_image=None,
last_image=None,
reference_audio_assets=latents,
)
assert [item["type"] for item in clip.options["minimax_ref_items"]] == [
"audio",
"audio",
"audio",
]
refs = conditioning[0][1]["minimax_refs"]
assert [item["kind"] for item in refs] == ["audio", "audio", "audio"]
assert [item["ref_audio_t"] for item in refs] == [1, 2, 3]
assert [float(item["audio_latent"].mean().item()) for item in refs] == [1.0, 2.0, 3.0]
def test_reference_images_and_three_audio_assets_share_ordered_core_payloads():
image = torch.full((1, 32, 32, 3), 0.5, dtype=torch.float32)
image_assets = ReferenceAssets(
images=(image,),
latents=(torch.zeros((1, 24, 2, 2, 2)),),
image_hashes=("reference-image",),
combined_hash="reference-images",
size_mode="Match Output",
)
audio_assets = tuple(
SimpleNamespace(audio_latent=torch.full((1, 32, 2, index), float(index)))
for index in (1, 2, 3)
)
clip = _Clip()
conditioning = encode_reference_prompt(
clip,
"<Picture 1> with <Audio 1>, <Audio 2>, and <Audio 3>.",
image_assets,
reference_audio_assets=audio_assets,
)
assert [item["type"] for item in clip.options["minimax_ref_items"]] == [
"image",
"audio",
"audio",
"audio",
]
refs = conditioning[0][1]["minimax_refs"]
assert [item["kind"] for item in refs] == ["image", "audio", "audio", "audio"]
assert [item["ref_audio_t"] for item in refs[1:]] == [1, 2, 3]
def test_one_item_helper_conditioning_matches_legacy_single_item():
latent = torch.arange(64, dtype=torch.float32).reshape(1, 32, 2, 1)
asset = SimpleNamespace(audio_latent=latent)
legacy_clip = _Clip()
helper_clip = _Clip()
legacy = encode_prompt_conditioning(
legacy_clip,
"Use <Audio 1>.",
first_image=None,
last_image=None,
reference_audio_assets=asset,
)
helper = encode_prompt_conditioning(
helper_clip,
"Use <Audio 1>.",
first_image=None,
last_image=None,
reference_audio_assets=(asset,),
)
assert legacy_clip.options == helper_clip.options
assert legacy[0][1].keys() == helper[0][1].keys()
assert legacy[0][1]["minimax_refs"][0]["ref_audio_t"] == 1
assert torch.equal(
legacy[0][1]["minimax_refs"][0]["audio_latent"],
helper[0][1]["minimax_refs"][0]["audio_latent"],
)
def test_prompt_warnings_follow_connected_audio_count():
vae = _AudioVAE()
bundle = prepare_reference_audio_bundle(_audio(0.1), _audio(0.2), None, vae)
assert bundle is not None
warning = validate_reference_audio_prompts(
["<Audio 1> speaks while <Audio 3> answers."], bundle
)
assert "unavailable <Audio 3>" in warning
assert "no <Audio 2> tag" in warning
assert "no <Audio 1> tag" not in warning
def test_run_storage_graph_contract_fingerprints_helper_vae_and_sources():
prompt = {
"sampler": {
"class_type": "H3ContinuumSamplerV38",
"inputs": {
"model": ["model", 0],
"clip": ["clip", 0],
"audio_references": ["refs", 0],
},
},
"model": {"class_type": "UNETLoader", "inputs": {"name": "model.safetensors"}},
"clip": {"class_type": "CLIPLoader", "inputs": {"name": "text.safetensors"}},
"refs": {
"class_type": "H3ContinuumReferenceAudios",
"inputs": {
"reference_audio_1": ["audio1", 0],
"reference_audio_2": ["audio2", 0],
"reference_audio_vae": ["vae", 0],
},
},
"audio1": {"class_type": "LoadAudio", "inputs": {"audio": "one.wav"}},
"audio2": {"class_type": "LoadAudio", "inputs": {"audio": "two.wav"}},
"vae": {"class_type": "VAELoader", "inputs": {"vae_name": "audio.safetensors"}},
}
contract, safe, reasons = build_upstream_graph_contract(
prompt,
"sampler",
require_video_vae=False,
require_reference_audio_vae=True,
)
assert safe, reasons
route = contract["routes"]["reference_audio_vae"]
assert route["node"]["class_type"] == "H3ContinuumReferenceAudios"
assert route["node"]["inputs"]["reference_audio_vae"]["node"]["class_type"] == (
"VAELoader"
)
assert route["node"]["inputs"]["reference_audio_2"]["node"]["inputs"]["audio"] == (
"two.wav"
)
def test_v38_facade_forwards_bundle_socket_without_touching_v37(monkeypatch):
captured = {}
def fake_v37_run(_self, **kwargs):
captured.update(kwargs)
return "ok"
monkeypatch.setattr(H3ContinuumSamplerV37, "run", fake_v37_run)
marker = object()
result = H3ContinuumSamplerV38().run(audio_references=marker)
assert result == "ok"
assert captured["audio_references"] is marker
def test_legacy_source_preparation_remains_available_unchanged():
vae = _AudioVAE()
source = prepare_reference_audio_source(_audio(0.25), vae)
assert source is not None
assert source.contract["reference_audio_contract_version"] == 1
assert "reference_audio_bundle_contract_version" not in source.contract
+248
View File
@@ -0,0 +1,248 @@
from __future__ import annotations
import ast
import copy
from pathlib import Path
import pytest
import torch
from ComfyUI_H3_Continuum_Join.v3.driving_nodes import (
H3ContinuumAssembleSeamV35,
)
from ComfyUI_H3_Continuum_Join.v3.plan import _attach_second_pass_contract
from ComfyUI_H3_Continuum_Join.v3.second_pass import (
SecondPassContractError,
passthrough_audio_latents,
update_second_pass_geometry,
validate_second_pass_inputs,
)
from ComfyUI_H3_Continuum_Join.v3.second_pass_nodes import (
H3ContinuumSecondPassV35,
)
def _entry(t: int, audio_t: int, *, prompt: str) -> dict:
return {
"video": torch.zeros((1, 24, t, 40, 40)),
"audio": torch.zeros((1, 8, audio_t)),
"prompt": prompt,
}
def _terminal_fixture():
logical = [
_entry(31, 100, prompt="first"),
_entry(35, 110, prompt="middle"),
_entry(35, 110, prompt="last"),
]
physical = [logical[0], _entry(65, 220, prompt="terminal")]
plan = {
"width": 640,
"height": 640,
"chunks": [
{"total_frames": 124, "trim_frames": 0},
{"total_frames": 141, "trim_frames": 22},
{"total_frames": 141, "trim_frames": 22},
],
"decode_groups": [
{
"logical_chunk_indices": [1],
"terminal_merged": False,
"total_frames": 124,
"trim_frames": 0,
},
{
"logical_chunk_indices": [2, 3],
"terminal_merged": True,
"total_frames": 260,
"trim_frames": 22,
},
],
}
_attach_second_pass_contract(
plan,
logical_entries=logical,
physical_entries=physical,
chunk_seconds=5.0,
)
videos = [{"samples": entry["video"]} for entry in physical]
audios = [{"samples": entry["audio"]} for entry in physical]
return plan, videos, audios
def _external_spatial_processor(video_latents, *, target_h: int, target_w: int):
return [
{
**latent,
"samples": latent["samples"].new_zeros(
(*latent["samples"].shape[:3], target_h, target_w)
),
}
for latent in video_latents
]
def _without_target_geometry(plan: dict) -> dict:
normalized = copy.deepcopy(plan)
normalized.pop("width", None)
normalized.pop("height", None)
contract = normalized["second_pass_contract"]
contract.pop("target_width", None)
contract.pop("target_height", None)
for group in contract["physical_groups"]:
for key in (
"target_latent_h",
"target_latent_w",
"target_width",
"target_height",
):
group.pop(key, None)
return normalized
def test_external_processor_may_change_only_common_spatial_video_geometry():
plan, videos, audios = _terminal_fixture()
processed = _external_spatial_processor(videos, target_h=60, target_w=64)
result = validate_second_pass_inputs(processed, audios, plan)
assert result == {
"physical_group_count": 2,
"target_latent_h": 60,
"target_latent_w": 64,
"audio_passthrough": True,
}
terminal = plan["second_pass_contract"]["physical_groups"][1]
assert terminal["logical_chunks"] == [2, 3]
assert terminal["terminal_merged"] is True
@pytest.mark.parametrize(
("mutation", "message"),
(
(lambda values: values[:1], "group count"),
(
lambda values: [
{"samples": torch.zeros((24, 31, 40, 40))},
values[1],
],
r"shape \[B,C,T,H,W\]",
),
(
lambda values: [
values[0],
{"samples": torch.zeros((1, 24, 64, 40, 40))},
],
"temporal length",
),
(
lambda values: [
values[0],
{"samples": torch.zeros((1, 24, 65, 39, 40))},
],
"preserved or enlarged",
),
),
)
def test_external_processor_rejects_group_temporal_or_downscale_changes(
mutation,
message,
):
plan, videos, audios = _terminal_fixture()
with pytest.raises(SecondPassContractError, match=message):
validate_second_pass_inputs(mutation(videos), audios, plan)
@pytest.mark.parametrize(
("stream", "bad_value"),
(("video", float("nan")), ("audio", float("inf"))),
)
def test_external_processor_rejects_nonfinite_latents_before_sampling(
stream,
bad_value,
):
plan, videos, audios = _terminal_fixture()
target = videos if stream == "video" else audios
target[0]["samples"].view(-1)[0] = bad_value
with pytest.raises(SecondPassContractError, match="contains NaN or Inf"):
validate_second_pass_inputs(videos, audios, plan)
def test_external_processor_rejects_changed_audio_shape():
plan, videos, audios = _terminal_fixture()
audios[1] = {"samples": torch.zeros((1, 8, 219))}
with pytest.raises(SecondPassContractError, match="audio latent shape"):
validate_second_pass_inputs(videos, audios, plan)
def test_first_pass_audio_objects_and_input_plan_are_not_mutated():
plan, videos, audios = _terminal_fixture()
before = copy.deepcopy(plan)
processed = _external_spatial_processor(videos, target_h=60, target_w=60)
output_audio = passthrough_audio_latents(audios)
updated = update_second_pass_geometry(plan, processed)
assert plan == before
assert updated is not plan
assert all(left is right for left, right in zip(audios, output_audio, strict=True))
assert _without_target_geometry(updated) == _without_target_geometry(plan)
def test_public_second_pass_and_finalize_keep_existing_comfy_type_boundary():
second_pass = H3ContinuumSecondPassV35.INPUT_TYPES()
finalize = H3ContinuumAssembleSeamV35.INPUT_TYPES()
assert tuple(second_pass["required"]) == (
"model",
"clip",
"sampler",
"sigmas",
"video_latents",
"audio_latents",
"assembly_plan",
"refine_seed",
)
assert second_pass["required"]["video_latents"] == ("LATENT",)
assert second_pass["required"]["audio_latents"] == ("LATENT",)
assert tuple(second_pass["optional"]) == ("refine_context", "video_vae")
assert finalize["required"]["images"] == ("IMAGE",)
assert finalize["required"]["audio"] == ("AUDIO",)
assert "video_vae" not in finalize["required"]
assert "audio_vae" not in finalize["required"]
def test_integration_modules_do_not_import_optional_accelerators_or_run_storage():
root = Path(__file__).resolve().parents[1]
forbidden_accelerators = {"sageattention", "sol_attn", "spectrum", "tensorrt"}
modules = (
root / "compatibility.py",
root / "model_patch.py",
root / "v3" / "second_pass.py",
)
for path in modules:
tree = ast.parse(path.read_text(encoding="utf-8"))
imports = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
imports.update(
alias.name.split(".", 1)[0].lower() for alias in node.names
)
elif isinstance(node, ast.ImportFrom) and node.module:
imports.add(node.module.split(".", 1)[0].lower())
assert imports.isdisjoint(forbidden_accelerators)
second_pass_tree = ast.parse(
(root / "v3" / "second_pass.py").read_text(encoding="utf-8")
)
imported_names = set()
for node in ast.walk(second_pass_tree):
if isinstance(node, ast.Import):
imported_names.update(alias.name.lower() for alias in node.names)
elif isinstance(node, ast.ImportFrom) and node.module:
imported_names.add(node.module.lower())
assert not any("run_storage" in name for name in imported_names)
+206
View File
@@ -0,0 +1,206 @@
from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
import pytest
from ComfyUI_H3_Continuum_Join.model_patch import _wrapper_factory
from ComfyUI_H3_Continuum_Join.v3.packed_row_planner import (
MAX_CONCURRENT_PHYSICAL_GROUPS,
MemoryObservation,
PackedRowPlanner,
PackedRowPlanningError,
analyze_packed_layout,
planner_event_fail_soft,
)
ROOT = Path(__file__).resolve().parents[1]
def _layout(*segments):
return SimpleNamespace(seq_len=segments[-1][1], segments=list(segments))
def _baseline_layout(*, reference_rows=0, target_video_rows=20):
cursor = 0
segments = [(cursor, cursor + 4, "text")]
cursor += 4
if reference_rows:
segments.append((cursor, cursor + reference_rows, "ref_img"))
cursor += reference_rows
segments.append((cursor, cursor + 6, "audio"))
cursor += 6
segments.append((cursor, cursor + target_video_rows, "video"))
return _layout(*segments)
def _memory(value):
return MemoryObservation(
system_available_bytes=value,
cuda_allocated_bytes=value + 1,
cuda_reserved_bytes=value + 2,
core_visible_free_bytes=value + 3,
)
def test_actual_segment_accounting_uses_core_layout_partition():
layout = _layout(
(0, 5, "text"),
(5, 9, "cond"),
(9, 12, "ref_img"),
(12, 14, "cond_audio"),
(14, 18, "ref_audio"),
(18, 26, "audio"),
(26, 56, "video"),
)
result = analyze_packed_layout(layout)
assert result.seq_len == 56
assert result.text_rows == 5
assert result.condition_video_rows == 7
assert result.condition_audio_rows == 6
assert result.target_audio_rows == 8
assert result.target_video_rows == 30
assert result.condition_rows == 13
assert result.target_rows == 38
assert result.condition_to_target_ratio == pytest.approx(13 / 38)
assert sum(stop - start for start, stop, _ in result.segment_signature) == 56
@pytest.mark.parametrize(
"layout",
[
SimpleNamespace(seq_len=10, segments=[]),
_layout((0, 3, "text"), (4, 6, "audio"), (6, 10, "video")),
SimpleNamespace(
seq_len=11,
segments=[(0, 3, "text"), (3, 6, "audio"), (6, 10, "video")],
),
_layout((0, 3, "text"), (3, 6, "audio"), (6, 8, "video"), (8, 10, "video")),
],
)
def test_invalid_layout_accounting_is_diagnostic_error(layout):
with pytest.raises(PackedRowPlanningError):
analyze_packed_layout(layout)
def test_unknown_segment_is_counted_without_changing_core_layout():
layout = _layout(
(0, 2, "text"),
(2, 5, "future_core_segment"),
(5, 9, "audio"),
(9, 15, "video"),
)
before = tuple(layout.segments)
result = analyze_packed_layout(layout)
assert result.unknown_rows == 3
assert tuple(layout.segments) == before
def test_planner_keeps_fixed_order_terminal_atomicity_and_earliest_peak_tie():
planner = PackedRowPlanner(memory_reader=lambda: _memory(1024))
for group, logical, terminal, layout in (
(1, (1,), False, _baseline_layout(target_video_rows=20)),
(2, (2,), False, _baseline_layout(reference_rows=4, target_video_rows=24)),
(3, (3, 4), True, _baseline_layout(reference_rows=4, target_video_rows=24)),
):
planner.begin_group(
physical_group=group,
logical_chunks=logical,
terminal_atomic=terminal,
)
planner.observe_layout(layout)
planner.observe_layout(layout)
planner.finish_group()
lines = planner.report_lines()
assert MAX_CONCURRENT_PHYSICAL_GROUPS == 1
assert "execution_order=[1, 2, 3]" in lines[0]
assert "peak_candidate=2" in lines[0]
assert "VRAM/time prediction=not provided" in lines[0]
assert "physical_group=3" in lines[3]
assert "logical_chunks=[3, 4]" in lines[3]
assert "terminal_atomic=true" in lines[3]
def test_topology_change_within_group_becomes_unavailable_advisory():
planner = PackedRowPlanner(memory_reader=lambda: MemoryObservation())
planner.begin_group(physical_group=1, logical_chunks=(1,), terminal_atomic=False)
planner.observe_layout(_baseline_layout())
planner.observe_layout(_baseline_layout(reference_rows=2))
planner.finish_group()
lines = planner.report_lines()
assert "observed_groups=0/1" in lines[0]
assert "unavailable/advisory=PackedLayout topology changed" in lines[1]
def test_missing_layout_and_memory_counter_failure_are_fail_soft():
def unavailable_memory():
raise RuntimeError("counter unavailable")
planner = PackedRowPlanner(memory_reader=unavailable_memory)
planner.begin_group(physical_group=1, logical_chunks=(1,), terminal_atomic=False)
planner.observe_layout(None)
planner.finish_group()
lines = planner.report_lines()
assert "peak_candidate=unavailable" in lines[0]
assert "Core PackedLayout is unavailable" in lines[1]
def test_model_wrapper_observes_target_only_layout_before_normal_passthrough():
class Executor:
def __call__(self, *args, **kwargs):
return kwargs["minimax_payload"]
planner = PackedRowPlanner(memory_reader=lambda: MemoryObservation())
planner.begin_group(physical_group=1, logical_chunks=(1,), terminal_atomic=False)
payload = {"layout": _baseline_layout(), "seed": 7}
wrapper = _wrapper_factory(
strict=True,
debug=False,
packed_row_planner=planner,
)
result = wrapper(Executor(), object(), minimax_payload=payload)
planner.finish_group()
assert result is payload
assert result == {"layout": payload["layout"], "seed": 7}
assert planner.records[0]["breakdown"].seq_len == payload["layout"].seq_len
def test_lifecycle_helper_never_propagates_diagnostic_failure():
class BrokenPlanner:
def explode(self):
raise RuntimeError("diagnostic failure")
def note_observation_failure(self, exc):
raise RuntimeError("secondary diagnostic failure")
assert planner_event_fail_soft(BrokenPlanner(), "explode") is None
def test_a7a_source_has_no_execution_or_allocator_mutation_calls():
source = (ROOT / "v3" / "packed_row_planner.py").read_text(encoding="utf-8")
for forbidden in (
".synchronize(",
".empty_cache(",
".reset_peak_memory_stats(",
"unload_all_models(",
"pynvml",
):
assert forbidden not in source
def test_a7a_is_detailed_only_and_has_no_public_widget():
sequence = (ROOT / "v2" / "sequence.py").read_text(encoding="utf-8")
planner_creation = sequence.index("packed_row_planner=PackedRowPlanner()")
detailed_guard = sequence.rindex(
"if diagnostics_mode==DIAGNOSTICS_FULL:", 0, planner_creation
)
assert detailed_guard < planner_creation
public_nodes = (ROOT / "v3" / "nodes.py").read_text(encoding="utf-8")
selective_node = (ROOT / "v3" / "second_pass_nodes.py").read_text(
encoding="utf-8"
)
assert "Packed-row" not in public_nodes
assert "Packed-row" not in selective_node
+637
View File
@@ -0,0 +1,637 @@
from __future__ import annotations
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import pytest
from ComfyUI_H3_Continuum_Join import nodes as root_nodes
from ComfyUI_H3_Continuum_Join.v3 import driving_nodes
from ComfyUI_H3_Continuum_Join.v3 import easy_nodes
from ComfyUI_H3_Continuum_Join.v3 import second_pass_nodes
ROOT = Path(__file__).resolve().parents[1]
PUBLIC_DISPLAY_NAMES = {
"H3ContinuumSamplerV38": "H3 Continuum Sampler V3.8",
"H3ContinuumReferenceAudios": "H3 Continuum Reference Audios",
"H3ContinuumAssembleSeamV35": "H3 Continuum Finalize",
"H3EasyLoadImage": "H3 Continuum Load Image",
"H3EasyLoadAudio": "H3 Continuum Load Audio",
"H3ContinuumLoadVideo": "H3 Continuum Load Video",
"H3ContinuumSecondPassV35": "H3 Continuum Second Pass",
}
def test_public_export_is_exactly_the_seven_node_v38_allowlist():
assert set(root_nodes.NODE_CLASS_MAPPINGS) == set(PUBLIC_DISPLAY_NAMES)
assert root_nodes.NODE_DISPLAY_NAME_MAPPINGS == PUBLIC_DISPLAY_NAMES
def test_labs_and_unreleased_easy_implementations_remain_internal():
assert "H3ContinuumMemoryActionPolicyExperimental" in (
driving_nodes.NODE_CLASS_MAPPINGS
)
assert "H3ContinuumSamplerV38MemoryPolicyExperimental" in (
driving_nodes.NODE_CLASS_MAPPINGS
)
assert "H3ContinuumSelectiveSecondPassExperimental" in (
second_pass_nodes.NODE_CLASS_MAPPINGS
)
assert "H3ContinuumEasyReferences" in easy_nodes.NODE_CLASS_MAPPINGS
assert "H3ContinuumEasyV38" in easy_nodes.NODE_CLASS_MAPPINGS
assert not set(
(
"H3ContinuumMemoryActionPolicyExperimental",
"H3ContinuumSamplerV38MemoryPolicyExperimental",
"H3ContinuumSelectiveSecondPassExperimental",
"H3ContinuumEasyReferences",
"H3ContinuumEasyV38",
)
) & set(root_nodes.NODE_CLASS_MAPPINGS)
def test_v38_schema_and_serialized_widget_order_are_unchanged():
schema = driving_nodes.H3ContinuumSamplerV38.INPUT_TYPES()
assert list(schema["required"]) == [
"model",
"clip",
"video_vae",
"sampler",
"sigmas",
"sequence_prompt",
"prompt_mode",
"chunks",
"chunk_seconds",
"aspect",
"preset",
"custom_mp",
"continuity",
"base_seed",
"audio_continuity",
"diagnostics",
"reroll_from_chunk",
"reroll_nonce",
"strict_compatibility",
"debug",
"show_preview",
"run_storage",
"run_name",
"reference_size",
"project_id",
"video_reference_size",
"continuation_backend",
"generation_mode",
"review_action",
"take_group",
"take_revision_id",
"take_action",
"size_source",
"width",
"height",
]
assert list(schema["optional"]) == [
"first_frame",
"last_frame",
"reference_image_1",
"reference_image_2",
"reference_image_3",
"reference_video_1",
"driving_audio",
"audio_vae",
"reference_audio_1",
"reference_audio_vae",
"guide",
"audio_references",
]
def test_registry_package_keeps_one_workflow_and_excludes_development_assets():
rules = (ROOT / ".comfyignore").read_text(encoding="utf-8").splitlines()
assert "tests/" in rules
assert "tools/*" in rules
assert "!tools/__init__.py" in rules
assert "!tools/p20_file_backed_tensor_poc.py" in rules
assert "tools/" not in rules
assert "AGENTS.md" in rules
assert "PROJECT_STATE.md" in rules
assert "WORKLOG.md" in rules
assert "MANIFEST.sha256" in rules
assert "examples/*" in rules
assert "!examples/workflows/" in rules
assert "examples/workflows/*" in rules
assert "!examples/workflows/MiniMax_H3_Continuum_V38.json" in rules
assert "!examples/workflows/MiniMax_H3_Continuum_V38.zip" in rules
assert "*.zip" in rules
workflow = json.loads(
(ROOT / "examples/workflows/MiniMax_H3_Continuum_V38.json").read_text(
encoding="utf-8"
)
)
custom_types = {
node["type"] for node in workflow["nodes"] if node["type"].startswith("H3")
}
assert custom_types <= set(PUBLIC_DISPLAY_NAMES)
sampler = next(
node for node in workflow["nodes"] if node["type"] == "H3ContinuumSamplerV38"
)
assert sampler["properties"]["H3 Continuum View"] == "Basic"
# The user-approved Spectrum distribution preserves its saved Core titles.
# Exact bytes, dependencies and graph topology are tested in the workflow suite.
assert any(node["type"] == "SpectrumApplyMiniMaxH3" for node in workflow["nodes"])
def test_registry_manifest_matches_every_declared_source_file():
manifest = ROOT / "REGISTRY_MANIFEST.sha256"
entries = {}
for line in manifest.read_text(encoding="utf-8").splitlines():
digest, relative_path = line.split(" ", 1)
entries[relative_path] = digest
assert "REGISTRY_MANIFEST.sha256" not in entries
assert "MANIFEST.sha256" not in entries
assert "AGENTS.md" not in entries
assert "PROJECT_STATE.md" not in entries
assert "WORKLOG.md" not in entries
assert "tools/__init__.py" in entries
assert "tools/p20_file_backed_tensor_poc.py" in entries
assert "tools/verify_runtime.py" in entries
assert not {
path for path in entries if path.startswith("tools/")
} - {
"tools/__init__.py",
"tools/p20_file_backed_tensor_poc.py",
"tools/verify_runtime.py",
}
assert {
path for path in entries if path.startswith("examples/")
} == {
"examples/workflows/MiniMax_H3_Continuum_V38.json",
"examples/workflows/MiniMax_H3_Continuum_V38.zip",
}
for relative_path, expected_digest in entries.items():
payload = (ROOT / relative_path).read_bytes()
assert hashlib.sha256(payload).hexdigest() == expected_digest
def test_intuitive_facade_is_discoverable_and_presentation_only(tmp_path):
node_executable = shutil.which("node")
if node_executable is None:
pytest.skip("Node.js is required for the frontend behavior regression")
source = (ROOT / "web/project_id.js").read_text(encoding="utf-8")
source = source.replace(
'import { app } from "../../scripts/app.js";',
"const app = globalThis.__app;",
).replace(
'import { normalizeReferenceAudioLabels } from "./reference_audio_ui.js";',
"function normalizeReferenceAudioLabels() {}",
)
script = f"""
globalThis.__extension = null;
const sourceNodes = {{
101: {{ id: 101, mode: 0, widgets: [{{ name: "Enable Image", value: true }}] }},
102: {{ id: 102, mode: 0, widgets: [{{ name: "Enable Video", value: true }}] }},
103: {{ id: 103, mode: 4, widgets: [{{ name: "Enable Audio", value: true }}] }},
104: {{ id: 104, mode: 0, widgets: [{{ name: "Enable Audio", value: true }}] }},
}};
globalThis.__app = {{
graph: {{
_nodes: [],
links: {{
2: {{ origin_id: 102 }}, 3: {{ origin_id: 101 }},
4: {{ origin_id: 103 }}, 5: {{ origin_id: 104 }},
}},
getNodeById(id) {{ return sourceNodes[id] || null; }},
}},
ui: {{ settings: {{ getSettingValue: (_id, fallback) => fallback, addSetting() {{}} }} }},
registerExtension(extension) {{ globalThis.__extension = extension; }},
}};
globalThis.fetch = async () => ({{ status: 404, ok: false }});
{source}
function widget(name, value) {{
return {{
name, value, type: "combo",
options: {{ values: [] }},
computeSize: () => [120, 20],
}};
}}
const node = {{
comfyClass: "H3ContinuumSamplerV38",
properties: {{ "H3 Continuum View": "Basic" }},
widgets: [
widget("prompt_mode", "Auto"),
widget("chunks", 3), widget("chunk_seconds", 5),
widget("aspect", "Auto from First Image"),
widget("preset", "Draft — 0.30 MP"), widget("custom_mp", 0.3),
widget("continuity", "Balanced — 22 frames"),
widget("base_seed", 0), widget("control_after_generate", "randomize"),
widget("audio_continuity", true),
widget("continuation_backend", "Standard"),
widget("run_storage", "Save + Auto Resume"),
widget("reroll_from_chunk", "Chunk 2"), widget("reroll_nonce", 7),
widget("run_name", "keep-me"), widget("reference_size", "Match Output"),
widget("video_reference_size", "Efficient - 0.4 MP"),
widget("diagnostics", "Detailed Report"), widget("strict_compatibility", false),
widget("debug", true), widget("show_preview", false),
widget("project_id", "stable-project"),
widget("generation_mode", "Full Run"), widget("review_action", "Continue / Next"),
widget("take_group", 0), widget("take_revision_id", ""),
widget("take_action", "Automatic"),
widget("size_source", "First Image"), widget("width", 480), widget("height", 640),
],
inputs: [
{{ name: "model", link: 10 }},
{{ name: "clip", link: 11 }},
{{ name: "video_vae", link: 12 }},
{{ name: "sampler", link: 13 }},
{{ name: "sigmas", link: 14 }},
{{ name: "prompt_overrides", link: null }},
{{ name: "first_frame", link: 3 }},
{{ name: "last_frame", link: null }},
{{ name: "reference_image_1", link: 1 }},
{{ name: "reference_video_1", link: 2 }},
{{ name: "driving_audio", link: null }},
{{ name: "audio_references", link: null }},
{{ name: "guide", link: null }},
],
addWidget(type, name, value, callback, options) {{
const item = {{ name, value, callback, type, options: options || {{}}, computeSize: () => [120, 20] }};
this.widgets.push(item);
return item;
}},
addCustomWidget(item) {{
this.widgets.push(item);
return item;
}},
serialize() {{ return {{ widgets_values: this.widgets.map((item) => item.value) }}; }},
configure(info) {{
info.widgets_values.forEach((value, index) => {{ this.widgets[index].value = value; }});
}},
setDirtyCanvas() {{}},
}};
globalThis.__app.graph._nodes.push(node);
globalThis.__extension.nodeCreated(node);
setTimeout(() => {{
const savedBefore = node.serialize().widgets_values;
const facade = Object.fromEntries([
"Prompt Format", "Continuity", "Base Seed", "Control After Generate", "Audio Continuity",
"Chunks", "Seconds per Chunk", "Total Length",
"Size Source", "Resolution", "Custom MP", "Width", "Height",
"Run", "Progress", "Ready to Queue", "Advanced Settings",
"Reference Image Size", "Video Guide Size",
].map((name) => [name, node.widgets.find((item) => item.name === name)]));
const normalVisibleBeforeReview = [
"Prompt Format", "Continuity", "Base Seed", "Control After Generate", "Audio Continuity",
"Chunks", "Seconds per Chunk", "Total Length", "Size Source", "Resolution",
"Run", "Progress", "Ready to Queue", "Advanced Settings",
].every((name) => facade[name] && !facade[name].hidden);
const coreMainOrder = node.widgets.slice(0, 5).map((item) => item.name);
const corePersistentHidden = [
"prompt_mode", "continuity", "base_seed", "control_after_generate", "audio_continuity",
].every((name) => node.widgets.find((item) => item.name === name).hidden);
const dimensionsInitiallyHidden = facade.Width.hidden && facade.Height.hidden;
const drawMetrics = (widget) => {{
let rect = null;
const textYs = [];
const ctx = {{
save() {{}}, restore() {{}}, beginPath() {{}}, closePath() {{}},
fill() {{}}, stroke() {{}}, moveTo() {{}}, lineTo() {{}}, quadraticCurveTo() {{}},
roundRect(x, y, width, height, radius) {{ rect = {{ x, y, width, height, radius }}; }},
fillText(_text, _x, y) {{ textYs.push(y); }},
}};
widget.draw(ctx, node, 400, 100, 20);
return {{ rectHeight: rect.height, firstTextY: textYs[0], secondTextY: textYs[1] }};
}};
const readyCardMetrics = drawMetrics(facade["Ready to Queue"]);
const reviewActionHidden = node.widgets.find((item) => item.name === "review_action").hidden;
const advancedSource = node.widgets.find((item) => item.name === "continuation_backend");
const advancedInitiallyHidden = advancedSource.hidden;
const advancedClosedLabel = facade["Advanced Settings"].label;
facade["Advanced Settings"].callback();
const advancedVisible = !advancedSource.hidden;
const conditionalSizesVisibleInAdvanced = (
!facade["Reference Image Size"].hidden && !facade["Video Guide Size"].hidden
);
const advancedOpenLabel = facade["Advanced Settings"].label;
facade["Advanced Settings"].callback();
facade["Seconds per Chunk"].value = 10;
facade["Seconds per Chunk"].callback(10);
const chunksAfterSecondsChange = node.widgets.find((item) => item.name === "chunks").value;
const secondsAfterSecondsChange = node.widgets.find((item) => item.name === "chunk_seconds").value;
const totalAfterSecondsChange = facade["Total Length"].value;
facade.Chunks.value = 2;
facade.Chunks.callback(2);
const secondsAfterChunksChange = node.widgets.find((item) => item.name === "chunk_seconds").value;
const totalAfterChunksChange = facade["Total Length"].value;
facade["Size Source"].value = "Manual";
facade["Size Source"].callback("Manual");
const manualSizeSource = node.widgets.find((item) => item.name === "size_source").value;
const manualResolutionHidden = facade.Resolution.hidden;
const manualDimensionsVisible = !facade.Width.hidden && !facade.Height.hidden;
facade["Size Source"].value = "First Image";
facade["Size Source"].callback("First Image");
sourceNodes[101].mode = 4;
node.__h3ContinuumIntuitiveUxRefresh();
const bypassedSizeSource = facade["Size Source"].value;
const bypassedReady = facade["Ready to Queue"].value;
const bypassedResolutionVisible = !facade.Resolution.hidden;
const bypassedDimensionsHidden = facade.Width.hidden && facade.Height.hidden;
sourceNodes[101].mode = 0;
node.__h3ContinuumIntuitiveUxRefresh();
facade.Run.value = "Review Each Chunk";
facade.Run.callback("Review Each Chunk");
const reviewMapped = node.widgets.find((item) => item.name === "generation_mode").value;
const saveMapped = node.widgets.find((item) => item.name === "run_storage").value;
facade.Chunks.value = 1;
facade.Chunks.callback(1);
const singleChunkReviewGuidance = facade["Ready to Queue"].value;
const singleChunkReviewHelp = facade.Chunks.tooltip;
facade.Chunks.value = 2;
facade.Chunks.callback(2);
const autoFixedReviewGuidance = facade["Ready to Queue"].value;
facade["Control After Generate"].value = "fixed";
facade["Control After Generate"].callback("fixed");
const fixedReviewReady = facade["Ready to Queue"].value;
const reviewButtonsHiddenBeforeReady = [
"Use it and continue", "Try this chunk again", "Use it and finish the rest",
].every((name) => node.widgets.find((item) => item.name === name).hidden);
const historyHiddenBeforeTake = node.widgets.find(
(item) => item.name === "Render History",
).hidden;
node.__h3ContinuumTakeProject = {{
branch_provenance_version: 1,
canonical_storage_revision_id: "storage-ready",
revisions: [{{
revision_id: "storage-ready", status: "review_ready",
review_unit: {{ start: 1, end: 1, physical_group: 1 }},
}}],
canonical_head_revision_id: "take-1",
active_revisions: {{ "1": "take-1" }},
group_revisions: [{{
revision_id: "take-1", revision_order: "1",
group: {{ start: 1, end: 1, physical_group: 1 }},
}}],
}};
node.__h3ContinuumProductionUxRefresh();
const reviewButtonsVisibleWhenReady = [
"Use it and continue", "Try this chunk again", "Use it and finish the rest",
].every((name) => !node.widgets.find((item) => item.name === name).hidden);
const setupHiddenWhenReady = [
"Prompt Format", "Continuity", "Base Seed", "Control After Generate", "Audio Continuity",
"Chunks", "Seconds per Chunk", "Total Length", "Size Source", "Resolution",
"Run", "Progress", "Ready to Queue",
].every((name) => node.widgets.find((item) => item.name === name).hidden);
const reviewStatus = node.widgets.find((item) => item.name === "Review Ready");
const reviewCardMetrics = drawMetrics(reviewStatus);
const reviewStatusBeforeSelection = reviewStatus.value;
const backToSettings = node.widgets.find((item) => item.name === "Back to Settings");
const returnToReview = node.widgets.find((item) => item.name === "Return to Review");
const backToSettingsVisibleWhenReady = !backToSettings.hidden;
const returnToReviewHiddenWhenReady = returnToReview.hidden;
backToSettings.callback();
const setupVisibleAfterBack = [
"Prompt Format", "Continuity", "Base Seed", "Control After Generate", "Audio Continuity",
"Chunks", "Seconds per Chunk", "Total Length", "Size Source", "Resolution",
"Run", "Progress", "Ready to Queue",
].every((name) => !node.widgets.find((item) => item.name === name).hidden);
const reviewButtonsHiddenAfterBack = [
"Use it and continue", "Try this chunk again", "Use it and finish the rest",
].every((name) => node.widgets.find((item) => item.name === name).hidden);
const returnToReviewVisibleAfterBack = !returnToReview.hidden;
const backToSettingsHiddenAfterBack = backToSettings.hidden;
const settingsReviewCard = node.widgets.find((item) => item.name === "Ready to Queue");
const settingsReviewStatusAfterBack = settingsReviewCard.value;
const settingsReviewVariantAfterBack = settingsReviewCard.__h3ContinuumInfoVariant;
returnToReview.callback();
const setupHiddenAfterReturn = [
"Prompt Format", "Continuity", "Base Seed", "Control After Generate", "Audio Continuity",
"Chunks", "Seconds per Chunk", "Total Length", "Size Source", "Resolution",
"Run", "Progress", "Ready to Queue",
].every((name) => node.widgets.find((item) => item.name === name).hidden);
const reviewButtonsVisibleAfterReturn = [
"Use it and continue", "Try this chunk again", "Use it and finish the rest",
].every((name) => !node.widgets.find((item) => item.name === name).hidden);
const continueButton = node.widgets.find((item) => item.name === "Use it and continue");
continueButton.callback();
const selectedContinueLabel = continueButton.label;
const reviewStatusAfterSelection = reviewStatus.value;
const historyVisibleWithTake = !node.widgets.find(
(item) => item.name === "Render History",
).hidden;
const savedAfter = node.serialize().widgets_values;
console.log(JSON.stringify({{
facadeNames: Object.keys(facade),
normalVisible: normalVisibleBeforeReview,
coreMainOrder,
corePersistentHidden,
promptFormat: facade["Prompt Format"].value,
continuity: facade.Continuity.value,
baseSeed: facade["Base Seed"].value,
controlAfter: facade["Control After Generate"].value,
audioContinuity: facade["Audio Continuity"].value,
readyCardMetrics,
reviewCardMetrics,
dimensionsInitiallyHidden,
chunks: facade.Chunks.value,
secondsPerChunk: facade["Seconds per Chunk"].value,
totalLength: facade["Total Length"].value,
sizeSource: facade["Size Source"].value,
resolution: facade.Resolution.value,
progress: facade.Progress.value,
ready: facade["Ready to Queue"].value,
reviewActionHidden,
advancedInitiallyHidden,
advancedVisible,
conditionalSizesVisibleInAdvanced,
advancedClosedLabel,
advancedOpenLabel,
legacyPropertyRemoved: !("H3 Continuum View" in node.properties),
reviewMapped,
saveMapped,
singleChunkReviewGuidance,
singleChunkReviewHelp,
autoFixedReviewGuidance,
fixedReviewReady,
chunksAfterSecondsChange,
secondsAfterSecondsChange,
totalAfterSecondsChange,
secondsAfterChunksChange,
totalAfterChunksChange,
manualSizeSource,
manualResolutionHidden,
manualDimensionsVisible,
bypassedSizeSource,
bypassedReady,
bypassedResolutionVisible,
bypassedDimensionsHidden,
reviewButtonsHiddenBeforeReady,
reviewButtonsVisibleWhenReady,
setupHiddenWhenReady,
backToSettingsVisibleWhenReady,
returnToReviewHiddenWhenReady,
setupVisibleAfterBack,
reviewButtonsHiddenAfterBack,
returnToReviewVisibleAfterBack,
backToSettingsHiddenAfterBack,
settingsReviewStatusAfterBack,
settingsReviewVariantAfterBack,
setupHiddenAfterReturn,
reviewButtonsVisibleAfterReturn,
reviewStatusBeforeSelection,
selectedContinueLabel,
reviewStatusAfterSelection,
historyHiddenBeforeTake,
historyVisibleWithTake,
serializedCountStable: savedBefore.length === savedAfter.length,
inputs: node.inputs.map((item) => item.name),
}}));
}}, 150);
"""
script_path = tmp_path / "v38-public-surface-ui.js"
script_path.write_text(script, encoding="utf-8")
result = subprocess.run(
[node_executable, str(script_path)],
check=True,
capture_output=True,
text=True,
)
observed = json.loads(result.stdout)
assert observed == {
"facadeNames": [
"Prompt Format",
"Continuity",
"Base Seed",
"Control After Generate",
"Audio Continuity",
"Chunks",
"Seconds per Chunk",
"Total Length",
"Size Source",
"Resolution",
"Custom MP",
"Width",
"Height",
"Run",
"Progress",
"Ready to Queue",
"Advanced Settings",
"Reference Image Size",
"Video Guide Size",
],
"normalVisible": True,
"coreMainOrder": [
"Prompt Format",
"Continuity",
"Base Seed",
"Control After Generate",
"Audio Continuity",
],
"corePersistentHidden": True,
"promptFormat": "Auto",
"continuity": "Balanced — 22 frames",
"baseSeed": 0,
"controlAfter": "fixed",
"audioContinuity": True,
"readyCardMetrics": {
"rectHeight": 56,
"firstTextY": 122,
"secondTextY": 145,
},
"reviewCardMetrics": {
"rectHeight": 62,
"firstTextY": 122,
"secondTextY": 145,
},
"dimensionsInitiallyHidden": True,
"chunks": 2,
"secondsPerChunk": 10,
"totalLength": "20 seconds",
"sizeSource": "First Image",
"resolution": "Draft — 0.30 MP",
"progress": "On — Resume and Takes available",
"ready": "Ready to Queue\n2 × 10s = 20 seconds • First Image • Review each chunk",
"reviewActionHidden": True,
"advancedInitiallyHidden": True,
"advancedVisible": True,
"conditionalSizesVisibleInAdvanced": True,
"advancedClosedLabel": "Show Advanced Settings",
"advancedOpenLabel": "Hide Advanced Settings",
"legacyPropertyRemoved": True,
"reviewMapped": "Review Each Chunk",
"saveMapped": "Save + Auto Resume",
"singleChunkReviewGuidance": (
"Set Chunks to 2 or more\nChunks is 1, so the first 10s chunk is also the last. "
"Set Chunks to 2 or more before Queue to use Review and Continue."
),
"singleChunkReviewHelp": (
"Chunks is 1, so there is no next chunk to continue. Set Chunks to 2 or more "
"before Queue when using Review Each Chunk."
),
"autoFixedReviewGuidance": (
"Ready to Queue\n2 × 10s = 20 seconds • First Image • Review each chunk"
),
"fixedReviewReady": (
"Ready to Queue\n2 × 10s = 20 seconds • First Image • Review each chunk"
),
"chunksAfterSecondsChange": 3,
"secondsAfterSecondsChange": 10,
"totalAfterSecondsChange": "30 seconds",
"secondsAfterChunksChange": 10,
"totalAfterChunksChange": "20 seconds",
"manualSizeSource": "Manual",
"manualResolutionHidden": True,
"manualDimensionsVisible": True,
"bypassedSizeSource": "First Image",
"bypassedReady": (
"Check First Image\nSize Source is First Image, but no active image is "
"connected. Queue fallback: 480 × 640."
),
"bypassedResolutionVisible": True,
"bypassedDimensionsHidden": True,
"reviewButtonsHiddenBeforeReady": True,
"reviewButtonsVisibleWhenReady": True,
"setupHiddenWhenReady": True,
"backToSettingsVisibleWhenReady": True,
"returnToReviewHiddenWhenReady": True,
"setupVisibleAfterBack": True,
"reviewButtonsHiddenAfterBack": True,
"returnToReviewVisibleAfterBack": True,
"backToSettingsHiddenAfterBack": True,
"settingsReviewStatusAfterBack": (
"Chunk 1 is ready for review\nChoose what happens next, then press Queue."
),
"settingsReviewVariantAfterBack": "review",
"setupHiddenAfterReturn": True,
"reviewButtonsVisibleAfterReturn": True,
"reviewStatusBeforeSelection": (
"Chunk 1 is ready for review\nChoose what happens next, then press Queue."
),
"selectedContinueLabel": "✓ Use it and continue",
"reviewStatusAfterSelection": (
"Chunk 1 is ready for review\nSelected: Use it and continue. Press Queue to run this action."
),
"historyHiddenBeforeTake": True,
"historyVisibleWithTake": True,
"serializedCountStable": True,
"inputs": [
"model",
"clip",
"video_vae",
"sampler",
"sigmas",
"prompt_overrides",
"first_frame",
"last_frame",
"reference_image_1",
"reference_video_1",
"driving_audio",
"audio_references",
"guide",
],
}
+223
View File
@@ -0,0 +1,223 @@
from __future__ import annotations
import hashlib
import json
from pathlib import Path
from zipfile import ZipFile
ROOT = Path(__file__).resolve().parents[1]
WORKFLOW_PATH = ROOT / "examples" / "workflows" / "MiniMax_H3_Continuum_V38.json"
# User-approved final distribution. Do not sanitize or reserialize this graph.
WORKFLOW_SHA256 = "e490c87e4995930f95c8fffc4c678111d7897e74003e1962b9b4a247ba43f4ac"
ZIP_SHA256 = "83d28cc0cd549066962dc21ceae05d2b189fe22391b556887eab2cc1800e1e80"
EXTERNAL_PACKAGES = {
"comfyui-spectrum-minimax-h3",
"rgthree-comfy",
"comfyui-kjnodes",
"comfyui-easy-use",
}
def _workflow() -> dict:
return json.loads(WORKFLOW_PATH.read_text(encoding="utf-8"))
def _one_node(workflow: dict, node_type: str) -> dict:
values = [node for node in workflow["nodes"] if node["type"] == node_type]
assert len(values) == 1
return values[0]
def _graph(workflow: dict) -> tuple[dict[int, dict], dict[int, list]]:
nodes = {int(node["id"]): node for node in workflow["nodes"]}
links = {int(link[0]): link for link in workflow["links"]}
assert len(nodes) == len(workflow["nodes"])
assert len(links) == len(workflow["links"])
for link_id, link in links.items():
assert int(link[0]) == link_id
source = nodes[int(link[1])]
target = nodes[int(link[3])]
assert link_id in (source["outputs"][int(link[2])].get("links") or [])
assert int(target["inputs"][int(link[4])]["link"]) == link_id
for node_id, node in nodes.items():
for slot, item in enumerate(node.get("inputs", [])):
if item.get("link") is not None:
assert links[int(item["link"])][3:5] == [node_id, slot]
for slot, item in enumerate(node.get("outputs", [])):
for link_id in item.get("links") or []:
assert links[int(link_id)][1:3] == [node_id, slot]
return nodes, links
def test_v38_public_workflow_declares_external_dependencies_and_is_reloadable():
workflow = _workflow()
assert len(workflow["nodes"]) == 32
assert len(workflow["links"]) == 38
packages = {
node.get("properties", {}).get("cnr_id") for node in workflow["nodes"]
} - {None, "", "comfy-core"}
assert packages == EXTERNAL_PACKAGES
node_types = {node["type"] for node in workflow["nodes"]}
assert {
"SpectrumApplyMiniMaxH3", "Power Lora Loader (rgthree)",
"Fast Groups Bypasser (rgthree)", "easy cleanGpuUsed",
"MiniMaxH3MemoryEfficientSageAttentionPatch",
} <= node_types
assert not any("hires" in name.lower() for name in node_types)
_graph(workflow)
assert json.loads(json.dumps(workflow, ensure_ascii=False)) == workflow
assert int(workflow["last_node_id"]) >= max(int(node["id"]) for node in workflow["nodes"])
assert int(workflow["last_link_id"]) >= max(int(link[0]) for link in workflow["links"])
def test_v38_public_workflow_and_zip_preserve_supplied_bytes():
payload = WORKFLOW_PATH.read_bytes()
archive_path = WORKFLOW_PATH.with_suffix(".zip")
assert hashlib.sha256(payload).hexdigest() == WORKFLOW_SHA256
assert hashlib.sha256(archive_path.read_bytes()).hexdigest() == ZIP_SHA256
with ZipFile(archive_path) as archive:
assert archive.namelist() == [WORKFLOW_PATH.name]
assert archive.testzip() is None
assert archive.read(WORKFLOW_PATH.name) == payload
def test_v38_public_workflow_preserves_sampler_widget_positions():
workflow = _workflow()
sampler = _one_node(workflow, "H3ContinuumSamplerV38")
names = [
"prompt_mode",
"chunks",
"chunk_seconds",
"aspect",
"preset",
"custom_mp",
"continuity",
"base_seed",
"control_after_generate",
"audio_continuity",
"diagnostics",
"reroll_from_chunk",
"reroll_nonce",
"strict_compatibility",
"debug",
"show_preview",
"run_storage",
"run_name",
"reference_size",
"project_id",
"video_reference_size",
"continuation_backend",
"generation_mode",
"review_action",
"take_group",
"take_revision_id",
"take_action",
"size_source",
"width",
"height",
]
assert len(sampler["widgets_values"]) == len(names) == 30
assert sampler["widgets_values"] == [
sampler["widgets_values_named"][name] for name in names
]
assert sampler["widgets_values_named"]["generation_mode"] == "Full Run"
assert sampler["widgets_values_named"]["review_action"] == "Continue / Next"
assert sampler["widgets_values_named"]["run_storage"] == "Off"
assert sampler["widgets_values_named"]["aspect"] == "Auto from First Image"
assert sampler["widgets_values_named"]["preset"] == "Draft — 0.30 MP"
assert sampler["widgets_values_named"]["size_source"] == "First Image"
assert sampler["widgets_values_named"]["width"] == 640
assert sampler["widgets_values_named"]["height"] == 640
assert sampler["widgets_values_named"]["chunks"] == 2
assert sampler["widgets_values_named"]["chunk_seconds"] == 5
assert sampler["widgets_values_named"]["control_after_generate"] == "fixed"
assert sampler["widgets_values_named"]["continuation_backend"] == "Standard"
def test_v38_public_workflow_keeps_required_and_optional_connections():
workflow = _workflow()
nodes, links = _graph(workflow)
sampler = _one_node(workflow, "H3ContinuumSamplerV38")
inputs = {item["name"]: item for item in sampler["inputs"]}
required = {"model", "clip", "video_vae", "sampler", "sigmas", "sequence_prompt"}
optional = {
"first_frame",
"last_frame",
"reference_image_1",
"reference_image_2",
"reference_image_3",
"driving_audio",
"audio_vae",
"reference_video_1",
"audio_references",
}
assert required | optional <= set(inputs)
assert all(inputs[name]["link"] is not None for name in required | optional)
source_types = {}
source_modes = {}
for name in required | optional:
link = links[int(inputs[name]["link"])]
source = nodes[int(link[1])]
source_types[name] = source["type"]
source_modes[name] = int(source["mode"])
assert source_types["model"] == "SpectrumApplyMiniMaxH3"
assert source_types["sampler"] == "KSamplerSelect"
assert source_types["sigmas"] == "BasicScheduler"
assert source_types["sequence_prompt"] == "PrimitiveStringMultiline"
assert source_types["first_frame"] == "easy cleanGpuUsed"
assert source_modes["first_frame"] == 0
assert source_modes["last_frame"] == 4
assert source_modes["reference_image_1"] == 0
assert source_modes["reference_image_2"] == 0
assert source_modes["reference_image_3"] == 0
assert source_modes["driving_audio"] == 4
assert source_modes["reference_video_1"] == 4
assert source_types["audio_references"] == "H3ContinuumReferenceAudios"
def test_v38_public_workflow_preserves_spectrum_default_and_model_chain():
workflow = _workflow()
nodes, links = _graph(workflow)
def source(node, name):
item = next(item for item in node["inputs"] if item["name"] == name)
return nodes[links[item["link"]][1]]
sampler = _one_node(workflow, "H3ContinuumSamplerV38")
spectrum = source(sampler, "model")
assert spectrum["type"] == "SpectrumApplyMiniMaxH3"
assert spectrum["widgets_values"][0] is True
lora = source(spectrum, "model")
assert lora["type"] == "Power Lora Loader (rgthree)"
loras = [item for item in lora["widgets_values"] if isinstance(item, dict) and "lora" in item]
assert len(loras) == 4
assert all(item["on"] is False for item in loras)
sage = source(lora, "model")
assert sage["type"] == "MiniMaxH3MemoryEfficientSageAttentionPatch"
assert source(sage, "model")["type"] == "UNETLoader"
assert _one_node(workflow, "KSamplerSelect")["widgets_values"] == ["res_multistep"]
scheduler = _one_node(workflow, "BasicScheduler")
assert scheduler["widgets_values"] == ["simple", 20, 1]
assert source(scheduler, "model")["id"] == spectrum["id"]
def test_v38_public_workflow_keeps_decode_finalize_create_save_chain():
workflow = _workflow()
nodes, links = _graph(workflow)
save = _one_node(workflow, "SaveVideo")
cleanup = nodes[links[int(save["inputs"][0]["link"])][1]]
assert cleanup["type"] == "easy cleanGpuUsed"
create_link = links[int(cleanup["inputs"][0]["link"])]
assert nodes[int(create_link[1])]["type"] == "CreateVideo"
create = nodes[int(create_link[1])]
assert all(item["link"] is not None for item in create["inputs"][:2])
finalize = _one_node(workflow, "H3ContinuumAssembleSeamV35")
assert [links[item["link"]][1] for item in create["inputs"][:2]] == [finalize["id"]] * 2
incoming = [nodes[links[item["link"]][1]]["type"] for item in finalize["inputs"][:3]]
assert incoming == ["VAEDecode", "VAEDecodeAudio", "H3ContinuumSamplerV38"]
for node_type in ("VAEDecode", "VAEDecodeAudio"):
decode = _one_node(workflow, node_type)
assert nodes[links[decode["inputs"][0]["link"]][1]]["type"] == "H3ContinuumSamplerV38"
+492
View File
@@ -0,0 +1,492 @@
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
import gc
import inspect
from pathlib import Path
import threading
import weakref
import pytest
import torch
from ComfyUI_H3_Continuum_Join import reference, reference_audio, reference_video
from ComfyUI_H3_Continuum_Join.reference import ReferenceAssets
from ComfyUI_H3_Continuum_Join.reference_audio import (
ReferenceAudioAssets,
ReferenceAudioSource,
)
from ComfyUI_H3_Continuum_Join.temporal import video_latent_t
from ComfyUI_H3_Continuum_Join.v3 import driving_nodes
from ComfyUI_H3_Continuum_Join.v3.ref_encode_cache import (
RefEncodeCache,
clear_ref_encode_cache,
format_ref_encode_cache_diagnostics,
get_ref_encode_cache,
inspect_ref_encode_cache,
make_ref_encode_cache_key,
)
ROOT = Path(__file__).resolve().parents[1]
@pytest.fixture(autouse=True)
def _clear_global_cache():
clear_ref_encode_cache()
yield
clear_ref_encode_cache()
class ImageVAE:
def __init__(self):
self.calls = 0
def encode(self, image):
self.calls += 1
value = float(image.mean().item())
return torch.full((1, 24, 7, 2, 2), value, dtype=torch.float32)
class VideoVAE:
def __init__(self):
self.calls = 0
def encode(self, frames):
self.calls += 1
latent_t = video_latent_t(int(frames.shape[0]))
value = float(frames.mean().item())
return torch.full((1, 24, latent_t, 2, 2), value, dtype=torch.float32)
class AudioVAE:
audio_sample_rate = 32000
def __init__(self):
self.calls = 0
def encode(self, waveform):
self.calls += 1
return torch.full(
(1, 32, 2, 9),
float(waveform.mean().item()),
dtype=torch.float32,
)
def _key(identity: str, *, kind: str = "reference_image"):
return make_ref_encode_cache_key(kind, 1, identity)
def _image_assets(*hashes: str) -> ReferenceAssets:
images = tuple(
torch.full((1, 32, 32, 3), float(index), dtype=torch.float32)
for index in range(len(hashes))
)
return ReferenceAssets(
images=images,
latents=tuple(None for _ in images),
image_hashes=tuple(hashes),
combined_hash="combined",
size_mode=reference.REFERENCE_SIZE_MATCH_OUTPUT,
)
def _video_source(
*,
frames: int = 40,
target_frames: int = 22,
size_mode: str = reference_video.REFERENCE_VIDEO_SIZE_EFFICIENT,
value: float = 0.25,
):
return reference_video.prepare_reference_video_source(
torch.full((frames, 32, 32, 3), value, dtype=torch.float32),
target_frames=target_frames,
output_width=64,
output_height=64,
size_mode=size_mode,
)
def _audio_source(identity: str = "audio-a") -> ReferenceAudioSource:
waveform = torch.zeros((1, 2, 3200), dtype=torch.float32)
return ReferenceAudioSource(
waveform=waveform,
source_sample_rate=32000,
source_shape=tuple(waveform.shape),
source_dtype=str(waveform.dtype),
source_sha256=f"source-{identity}",
resolved_vae_sample_rate=32000,
resampled_shape=tuple(waveform.shape),
resampled_dtype=str(waveform.dtype),
resampled_sha256=f"resampled-{identity}",
combined_hash=identity,
)
def test_cache_core_miss_store_hit_returns_private_clone():
cache = RefEncodeCache()
vae = ImageVAE()
key = _key("a")
source = torch.arange(8, dtype=torch.float32)
events = []
assert cache.lookup(vae, key, event_sink=events.append) is None
assert cache.store(vae, key, source, event_sink=events.append)
hit = cache.lookup(vae, key, event_sink=events.append)
assert [event.action for event in events] == ["miss", "store", "hit"]
assert torch.equal(hit, source)
assert hit is not source
assert hit.data_ptr() != source.data_ptr()
hit.add_(100)
assert torch.equal(cache.lookup(vae, key), source)
def test_cache_namespace_requires_same_vae_object():
cache = RefEncodeCache()
first = ImageVAE()
second = ImageVAE()
key = _key("same")
cache.store(first, key, torch.ones(2))
assert cache.lookup(first, key) is not None
assert cache.lookup(second, key) is None
def test_cache_lru_evicts_global_oldest_entry():
cache = RefEncodeCache(max_entries=2, max_bytes=1024)
vae = ImageVAE()
first, second, third = _key("1"), _key("2"), _key("3")
cache.store(vae, first, torch.ones(1))
cache.store(vae, second, torch.ones(1) * 2)
assert cache.lookup(vae, first) is not None
cache.store(vae, third, torch.ones(1) * 3)
assert cache.lookup(vae, first) is not None
assert cache.lookup(vae, second) is None
assert cache.lookup(vae, third) is not None
assert cache.inspect()["resident_entries"] == 2
def test_cache_byte_limit_and_oversize_bypass():
cache = RefEncodeCache(max_entries=16, max_bytes=16)
vae = ImageVAE()
events = []
assert not cache.store(
vae,
_key("too-large"),
torch.ones(5, dtype=torch.float32),
event_sink=events.append,
)
assert events[-1].action == "bypass"
assert events[-1].reason == "entry_exceeds_byte_limit"
assert cache.inspect()["resident_entries"] == 0
def test_cache_clear_resets_entries_and_stats():
cache = RefEncodeCache()
vae = ImageVAE()
cache.store(vae, _key("a"), torch.ones(1))
cache.lookup(vae, _key("a"))
cache.clear()
assert cache.inspect()["resident_entries"] == 0
assert cache.inspect()["stats"] == {}
def test_weak_vae_cleanup_releases_namespace():
cache = RefEncodeCache()
vae = ImageVAE()
cache.store(vae, _key("a"), torch.ones(1))
vae_ref = weakref.ref(vae)
del vae
gc.collect()
assert vae_ref() is None
assert cache.inspect()["resident_entries"] == 0
assert cache.inspect()["vae_namespaces"] == 0
@pytest.mark.parametrize("vae", [object(), []])
def test_unweakrefable_or_unhashable_vae_is_bypassed(vae):
cache = RefEncodeCache()
events = []
assert cache.lookup(vae, _key("a"), event_sink=events.append) is None
assert events[-1].action == "bypass"
assert events[-1].reason == "vae_not_weakrefable_or_hashable"
def test_concurrent_hits_do_not_share_returned_tensor_or_corrupt_cache():
cache = RefEncodeCache()
vae = ImageVAE()
key = _key("threaded")
expected = torch.arange(64, dtype=torch.float32)
cache.store(vae, key, expected)
barrier = threading.Barrier(8)
def lookup_and_mutate(index):
barrier.wait()
value = cache.lookup(vae, key)
assert value is not None
original_ptr = value.data_ptr()
value.add_(index)
return original_ptr
with ThreadPoolExecutor(max_workers=8) as pool:
pointers = list(pool.map(lookup_and_mutate, range(8)))
assert len(set(pointers)) == 8
assert torch.equal(cache.lookup(vae, key), expected)
def test_reference_image_cold_then_warm_skips_encode_and_is_exact():
vae = ImageVAE()
assets = _image_assets("a" * 64)
cold = reference.encode_reference_latents_cached(vae, assets)
warm = reference.encode_reference_latents_cached(vae, assets)
assert vae.calls == 1
assert torch.equal(cold.latents[0], warm.latents[0])
assert cold.latents[0] is not warm.latents[0]
def test_reference_image_hit_mutation_does_not_damage_cache_master():
vae = ImageVAE()
assets = _image_assets("a" * 64)
reference.encode_reference_latents_cached(vae, assets)
first_hit = reference.encode_reference_latents_cached(vae, assets)
first_hit.latents[0].add_(99)
second_hit = reference.encode_reference_latents_cached(vae, assets)
assert vae.calls == 1
assert not torch.equal(first_hit.latents[0], second_hit.latents[0])
assert torch.equal(second_hit.latents[0], torch.zeros_like(second_hit.latents[0]))
def test_reference_image_changed_preprocessed_hash_misses():
vae = ImageVAE()
reference.encode_reference_latents_cached(vae, _image_assets("size-a"))
reference.encode_reference_latents_cached(vae, _image_assets("size-b"))
assert vae.calls == 2
def test_three_reference_images_cache_independently():
vae = ImageVAE()
assets = _image_assets("one", "two", "three")
events = []
reference.encode_reference_latents_cached(vae, assets, cache_event=events.append)
reference.encode_reference_latents_cached(vae, assets, cache_event=events.append)
assert vae.calls == 3
assert sum(event.action == "hit" for event in events) == 3
assert sum(event.action == "miss" for event in events) == 3
def test_reference_video_same_combined_hash_hits_and_preserves_presentation():
vae = VideoVAE()
source = _video_source()
cold = reference_video.encode_reference_video_cached(vae, source)
warm = reference_video.encode_reference_video_cached(vae, source)
assert vae.calls == 1
assert torch.equal(cold.block["latent"], warm.block["latent"])
assert cold.block["latent"].data_ptr() != warm.block["latent"].data_ptr()
assert torch.equal(cold.item["data"], warm.item["data"])
assert cold.item["timestamps"] == warm.item["timestamps"]
def test_reference_video_frame_size_and_source_identity_changes_miss():
vae = VideoVAE()
sources = [
_video_source(target_frames=22),
_video_source(target_frames=39),
_video_source(
target_frames=22,
size_mode=reference_video.REFERENCE_VIDEO_SIZE_MATCH_OUTPUT,
),
_video_source(target_frames=22, value=0.5),
]
assert len({source.combined_hash for source in sources}) == len(sources)
for source in sources:
reference_video.encode_reference_video_cached(vae, source)
assert vae.calls == len(sources)
def test_reference_video_cache_does_not_retain_source_frames():
vae = VideoVAE()
source = _video_source()
frames_ref = weakref.ref(source.frames)
assets = reference_video.encode_reference_video_cached(vae, source)
del assets
del source
gc.collect()
assert frames_ref() is None
assert inspect_ref_encode_cache()["resident_entries"] == 1
def test_reference_audio_cpu_output_cold_then_warm_is_exact():
vae = AudioVAE()
source = _audio_source()
cold = reference_audio.encode_reference_audio_cached(vae, source)
warm = reference_audio.encode_reference_audio_cached(vae, source)
assert vae.calls == 1
assert torch.equal(cold.audio_latent, warm.audio_latent)
assert cold.audio_latent.data_ptr() != warm.audio_latent.data_ptr()
def test_reference_audio_source_or_vae_change_misses():
first_vae = AudioVAE()
second_vae = AudioVAE()
reference_audio.encode_reference_audio_cached(first_vae, _audio_source("a"))
reference_audio.encode_reference_audio_cached(first_vae, _audio_source("b"))
reference_audio.encode_reference_audio_cached(second_vae, _audio_source("a"))
assert first_vae.calls == 2
assert second_vae.calls == 1
def test_reference_audio_non_cpu_output_is_safely_bypassed(monkeypatch):
vae = AudioVAE()
source = _audio_source()
calls = []
def fake_encode(_vae, active_source):
calls.append(active_source.combined_hash)
return ReferenceAudioAssets(
source=active_source,
audio_latent=torch.empty((1, 32, 2, 9), device="meta"),
)
monkeypatch.setattr(reference_audio, "encode_reference_audio", fake_encode)
events = []
first = reference_audio.encode_reference_audio_cached(
vae, source, cache_event=events.append
)
second = reference_audio.encode_reference_audio_cached(
vae, source, cache_event=events.append
)
assert first.audio_latent.device.type == "meta"
assert second.audio_latent.device.type == "meta"
assert calls == [source.combined_hash, source.combined_hash]
assert [event.action for event in events] == [
"miss",
"bypass",
"miss",
"bypass",
]
assert all(
event.reason == "payload_not_cpu"
for event in events
if event.action == "bypass"
)
def test_detailed_cache_report_has_kind_totals_and_resident_limits():
vae = ImageVAE()
events = []
assets = _image_assets("a")
reference.encode_reference_latents_cached(vae, assets, cache_event=events.append)
reference.encode_reference_latents_cached(vae, assets, cache_event=events.append)
line = format_ref_encode_cache_diagnostics(events)
assert line.startswith("Reference encode cache:")
assert "image hit=1/miss=1/store=1/bypass=0" in line
assert "total hits=1, misses=1, stores=1, bypasses=0" in line
assert "MiB/512.0 MiB" in line
assert "1/16 entries" in line
def test_v38_enables_internal_cache_without_public_schema_change(monkeypatch):
captured = {}
sentinel = object()
def fake_v37_run(_self, **kwargs):
captured.update(kwargs)
return sentinel
monkeypatch.setattr(driving_nodes.H3ContinuumSamplerV37, "run", fake_v37_run)
result = driving_nodes.H3ContinuumSamplerV38().run(
aspect="Square 1:1",
preset="Custom",
custom_mp=0.3,
chunks=1,
chunk_seconds=5.0,
diagnostics="Off",
)
schema = driving_nodes.H3ContinuumSamplerV38.INPUT_TYPES()
assert result is sentinel
assert captured["reference_encode_cache"] is True
assert all(
"reference_encode_cache" not in group
for group in (
schema.get("required", {}),
schema.get("optional", {}),
schema.get("hidden", {}),
)
)
def test_production_facade_accepts_internal_cache_flag():
signature = inspect.signature(driving_nodes.H3ContinuumSamplerProduction.run)
assert "reference_encode_cache" in signature.parameters
assert signature.parameters["reference_encode_cache"].default is False
source = inspect.getsource(driving_nodes.H3ContinuumSamplerProduction.run)
assert "reference_encode_cache=bool(reference_encode_cache)" in source
def test_v37_and_older_do_not_enable_internal_cache(monkeypatch):
captured = {}
def fake_v36_run(_self, **kwargs):
captured.update(kwargs)
return (), (), {}, "status", None, None
monkeypatch.setattr(driving_nodes.H3ContinuumSamplerV36, "run", fake_v36_run)
driving_nodes.H3ContinuumSamplerV37().run(
guide=None,
width=32,
height=32,
)
assert "reference_encode_cache" not in captured
for sampler in (
driving_nodes.H3ContinuumSamplerV34,
driving_nodes.H3ContinuumSamplerV35,
driving_nodes.H3ContinuumSamplerV36,
driving_nodes.H3ContinuumSamplerV37,
):
schema = sampler.INPUT_TYPES()
assert "reference_encode_cache" not in schema.get("required", {})
assert "reference_encode_cache" not in schema.get("optional", {})
def test_cache_flag_is_not_part_of_run_storage_or_public_workflow_identity():
assert "reference_encode_cache" not in (ROOT / "run_storage.py").read_text(
encoding="utf-8"
)
assert "reference_encode_cache" not in (
ROOT / "examples" / "workflows" / "MiniMax_H3_Continuum_V38.json"
).read_text(encoding="utf-8")
def test_full_reuse_skips_cache_and_partial_regenerate_enters_cached_encode_stage():
source = (ROOT / "v2" / "sequence.py").read_text(encoding="utf-8")
partial_regenerate_guard = source.index("if len(preserved)<chunks:")
image = source.index("encode_reference_latents_cached", partial_regenerate_guard)
audio = source.index("encode_reference_audio_input", partial_regenerate_guard)
video = source.index("encode_reference_video_cached", partial_regenerate_guard)
entries = source.index("entries=preserved[:]", partial_regenerate_guard)
assert partial_regenerate_guard < image < entries
assert partial_regenerate_guard < audio < entries
assert partial_regenerate_guard < video < entries

Some files were not shown because too many files have changed in this diff Show More