release: publish H3 Continuum V3.8X (3.8.1)

This commit is contained in:
ukr8b3g-cmyk
2026-09-15 03:46:57 +09:00
parent c421913bf1
commit 764179869f
62 changed files with 5707 additions and 2018 deletions
+28 -67
View File
@@ -53,6 +53,7 @@ from .memory_action_policy import (
make_memory_action_policy,
resolve_memory_action_policy,
)
from .node_facade import execute_v38_runtime_request, make_runtime_request
from .nodes import CATEGORY as CONTINUUM_CATEGORY, H3ContinuumSamplerProduction
from .resolution import (
H3_ASPECT_AUTO,
@@ -732,75 +733,35 @@ class H3ContinuumSamplerV38(H3ContinuumSamplerV37):
custom_mp=custom_mp,
first_frame=kwargs.get("first_frame"),
)
outputs = super().run(
width=resolution.width,
height=resolution.height,
generation_mode=generation_mode,
review_action=review_action,
take_group=take_group,
take_revision_id=take_revision_id,
take_action=take_action,
reference_encode_cache=True,
**kwargs,
)
# Preserve non-runtime test doubles and any future non-standard facade
# result rather than turning diagnostics into an execution requirement.
if not isinstance(outputs, tuple) or len(outputs) < 4:
return outputs
if size_source != H3_SIZE_SOURCE_LEGACY:
resolution_lines = [
(
f"Resolution: {resolution.width} x {resolution.height} "
f"({resolution.actual_mp:.2f} MP); source={resolution.aspect_source}."
)
]
resolution_lines.extend(resolution.warnings)
status = str(outputs[3]).rstrip() + "\n" + "\n".join(resolution_lines)
outputs = (*outputs[:3], status, *outputs[4:])
diagnostics_mode = str(kwargs.get("diagnostics", "Basic"))
normalized_diagnostics_mode = normalize_diagnostics_mode(diagnostics_mode)
if normalized_diagnostics_mode == DIAGNOSTICS_OFF:
return outputs
try:
diagnostics = build_v38_diagnostics(
video_latents=outputs[0],
audio_latents=outputs[1],
assembly_plan=outputs[2],
output_width=resolution.width,
output_height=resolution.height,
chunk_seconds=float(kwargs["chunk_seconds"]),
reference_images=(
kwargs.get("reference_image_1"),
kwargs.get("reference_image_2"),
kwargs.get("reference_image_3"),
),
reference_size=str(kwargs.get("reference_size", "Match Output")),
video_guide=kwargs.get("reference_video_1"),
video_guide_size=str(
kwargs.get(
"video_reference_size",
REFERENCE_VIDEO_SIZE_EFFICIENT,
)
),
still_guide_active=kwargs.get("guide") is not None,
)
status = append_v38_status(
outputs[3],
diagnostics,
mode=diagnostics_mode,
)
except Exception as exc:
# Generation already succeeded. Reliability reporting must never
# discard or replace a valid Production result.
status = str(outputs[3])
message = (
"V3.8 Reliability\n"
"Reliability diagnostics unavailable; generation result was preserved."
)
if normalized_diagnostics_mode == DIAGNOSTICS_FULL:
message += f" ({type(exc).__name__}: {exc})"
status = status.rstrip() + "\n" + message
return (*outputs[:3], status, *outputs[4:])
request = make_runtime_request(
runtime_kwargs=kwargs,
fixed_runtime_kwargs={
"width": resolution.width,
"height": resolution.height,
"generation_mode": generation_mode,
"review_action": review_action,
"take_group": take_group,
"take_revision_id": take_revision_id,
"take_action": take_action,
"reference_encode_cache": True,
},
resolution=resolution,
size_source=size_source,
diagnostics_mode=normalized_diagnostics_mode,
diagnostics_inputs=kwargs,
)
return execute_v38_runtime_request(
request,
runtime_adapter=super(H3ContinuumSamplerV38, self).run,
legacy_size_source=H3_SIZE_SOURCE_LEGACY,
diagnostics_off=DIAGNOSTICS_OFF,
diagnostics_full=DIAGNOSTICS_FULL,
reference_video_size_default=REFERENCE_VIDEO_SIZE_EFFICIENT,
build_diagnostics=build_v38_diagnostics,
append_status=append_v38_status,
)
class H3ContinuumMemoryActionPolicyExperimental:
+191
View File
@@ -0,0 +1,191 @@
"""Pure physical-group planner for the staged V3.8 runtime redesign.
The caller owns continuation-source priority and passes exactly one selected
``ContinuationSourceFacts``. This module performs no repository, Session,
State, tensor, ComfyUI, or sampling work.
"""
from __future__ import annotations
from ..branch_provenance import BranchProvenanceError, physical_groups
from .planning_types import (
ContinuationSourceFacts,
ExecutionPlan,
PhysicalGroupDescriptor,
ProjectionDecision,
)
from .review_control import (
REVISION_STATUS_COMPLETE,
REVISION_STATUS_INTERRUPTED,
REVISION_STATUS_REVIEW_READY,
ReviewExecution,
ReviewUnit,
)
PROJECTION_FULL_ACCEPTED_PREFIX = "full_accepted_prefix"
PROJECTION_CURRENT_REVIEW_UNIT = "current_review_unit"
class ExecutionPlanningError(ValueError):
"""Raised when already-selected planning facts are internally inconsistent."""
def resolve_projection_decision(
*,
review_execution: ReviewExecution | None,
effective_result_status: str,
accepted_chunks: int,
physical_group_facts: tuple[tuple[int, ...], ...],
) -> ProjectionDecision:
"""Resolve output-only projection from finalized, source-neutral facts."""
full = ProjectionDecision(PROJECTION_FULL_ACCEPTED_PREFIX)
if str(effective_result_status) != REVISION_STATUS_REVIEW_READY:
return full
if review_execution is None or bool(
getattr(review_execution, "finish_remaining", False)
):
return full
if not (
bool(getattr(review_execution, "partial_review", False))
or bool(getattr(review_execution, "smart_regenerate", False))
):
return full
start = getattr(review_execution, "next_review_unit_start", None)
end = getattr(review_execution, "next_review_unit_end", None)
if start is None or end is None:
return full
start, end = int(start), int(end)
if start < 1 or end < start or end > int(accepted_chunks):
return full
selected = set(range(start, end + 1))
if not physical_group_facts:
return full
for group in physical_group_facts:
group_indices = set(group)
if selected.intersection(group_indices) and not group_indices.issubset(selected):
return full
return ProjectionDecision(PROJECTION_CURRENT_REVIEW_UNIT, start, end)
def build_execution_plan(
*,
continuation_source_facts: ContinuationSourceFacts,
configured_chunks: int,
terminal_merge_enabled: bool,
max_new_physical_groups: int | None,
review_execution: ReviewExecution | None,
retained_review_unit: ReviewUnit | None = None,
) -> ExecutionPlan:
"""Plan physical groups without selecting or validating runtime sources."""
if not isinstance(continuation_source_facts, ContinuationSourceFacts):
raise ExecutionPlanningError(
"continuation_source_facts must be one selected ContinuationSourceFacts"
)
if continuation_source_facts.kind not in {
"run_storage",
"explicit_session",
"initial_state",
"none",
}:
raise ExecutionPlanningError(
f"unknown continuation source kind: {continuation_source_facts.kind!r}"
)
if isinstance(configured_chunks, bool) or not isinstance(configured_chunks, int):
raise ExecutionPlanningError("configured_chunks must be an integer")
if configured_chunks < 1:
raise ExecutionPlanningError("configured_chunks must be positive")
if type(terminal_merge_enabled) is not bool:
raise ExecutionPlanningError("terminal_merge_enabled must be a boolean")
if max_new_physical_groups is not None and (
isinstance(max_new_physical_groups, bool)
or not isinstance(max_new_physical_groups, int)
or max_new_physical_groups < 0
):
raise ExecutionPlanningError(
"max_new_physical_groups must be None or a non-negative integer"
)
accepted = continuation_source_facts.accepted_chunks
if isinstance(accepted, bool) or not isinstance(accepted, int):
raise ExecutionPlanningError("accepted_chunks must be an integer")
if not 0 <= accepted <= configured_chunks:
raise ExecutionPlanningError(
"accepted_chunks must be within the configured sequence"
)
try:
runtime_groups = physical_groups(
chunks=configured_chunks,
terminal_merge_enabled=terminal_merge_enabled,
)
except BranchProvenanceError as exc:
raise ExecutionPlanningError(str(exc)) from exc
descriptors = tuple(
PhysicalGroupDescriptor(
physical_group=int(group.physical_group),
logical_chunks=tuple(range(int(group.start), int(group.end) + 1)),
terminal_atomic=int(group.start) != int(group.end),
)
for group in runtime_groups
)
accepted_boundaries = tuple(
(descriptor.logical_chunks[0], descriptor.logical_chunks[-1])
for descriptor in descriptors
if descriptor.logical_chunks[-1] <= accepted
)
if accepted_boundaries and accepted_boundaries[-1][1] != accepted:
raise ExecutionPlanningError("accepted prefix ends inside a physical group")
if accepted and not accepted_boundaries:
raise ExecutionPlanningError("accepted prefix has no complete physical group")
if continuation_source_facts.physical_group_boundaries != accepted_boundaries:
raise ExecutionPlanningError(
"selected continuation source physical groups do not match its prefix"
)
pending = tuple(
descriptor
for descriptor in descriptors
if descriptor.logical_chunks[0] > accepted
)
groups_to_generate = (
pending
if max_new_physical_groups is None
else pending[:max_new_physical_groups]
)
expected_chunks = accepted + sum(
len(descriptor.logical_chunks) for descriptor in groups_to_generate
)
expected_review_unit = retained_review_unit
if groups_to_generate and max_new_physical_groups is not None:
final_group = groups_to_generate[-1]
expected_review_unit = ReviewUnit(
start=final_group.logical_chunks[0],
end=final_group.logical_chunks[-1],
physical_group=final_group.physical_group,
)
if expected_chunks == configured_chunks:
expected_status = REVISION_STATUS_COMPLETE
elif max_new_physical_groups is not None and expected_review_unit is not None:
expected_status = REVISION_STATUS_REVIEW_READY
else:
expected_status = REVISION_STATUS_INTERRUPTED
projection = resolve_projection_decision(
review_execution=review_execution,
effective_result_status=expected_status,
accepted_chunks=expected_chunks,
physical_group_facts=tuple(
descriptor.logical_chunks for descriptor in descriptors
),
)
return ExecutionPlan(
groups_to_generate=groups_to_generate,
projection=projection,
expected_status=expected_status,
expected_review_unit=expected_review_unit,
)
+165
View File
@@ -0,0 +1,165 @@
"""Thin V3.8 public-node to runtime boundary.
This module deliberately owns no continuation, review, storage, planning, or
sampling decision. It only carries already-resolved public-node values into
the existing hardening/runtime call and preserves its public return value.
"""
from __future__ import annotations
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from types import MappingProxyType
from typing import Any
@dataclass(frozen=True)
class RuntimeRequest:
"""Resolved V3.8 node inputs for one existing runtime invocation.
Tensor and model objects deliberately keep their identity. Only the two
keyword containers are copied and frozen so the facade cannot mutate the
caller's widget/input mapping after the request boundary.
"""
runtime_kwargs: Mapping[str, Any]
resolution: Any
size_source: str
diagnostics_mode: str
diagnostics_inputs: Mapping[str, Any]
def __post_init__(self) -> None:
object.__setattr__(
self,
"runtime_kwargs",
MappingProxyType(dict(self.runtime_kwargs)),
)
object.__setattr__(
self,
"diagnostics_inputs",
MappingProxyType(dict(self.diagnostics_inputs)),
)
@dataclass(frozen=True)
class RuntimeOutput:
"""Existing runtime result with status-only facade decoration helpers."""
value: Any
@property
def has_status(self) -> bool:
return isinstance(self.value, tuple) and len(self.value) >= 4
@property
def status(self) -> str:
if not self.has_status:
raise TypeError("runtime output has no public status field")
return str(self.value[3])
def with_status(self, status: str) -> "RuntimeOutput":
if not self.has_status:
return self
return RuntimeOutput((*self.value[:3], str(status), *self.value[4:]))
def as_public_tuple(self) -> Any:
"""Return the unchanged nonstandard test double or public tuple."""
return self.value
def make_runtime_request(
*,
runtime_kwargs: Mapping[str, Any],
fixed_runtime_kwargs: Mapping[str, Any],
resolution: Any,
size_source: str,
diagnostics_mode: str,
diagnostics_inputs: Mapping[str, Any],
) -> RuntimeRequest:
"""Build the one R6 request without silently accepting duplicate inputs."""
duplicate = set(runtime_kwargs).intersection(fixed_runtime_kwargs)
if duplicate:
name = sorted(duplicate)[0]
raise TypeError(
"H3 Continuum Sampler V3.8 received multiple values for "
f"runtime keyword {name!r}"
)
merged = dict(runtime_kwargs)
merged.update(fixed_runtime_kwargs)
return RuntimeRequest(
runtime_kwargs=merged,
resolution=resolution,
size_source=str(size_source),
diagnostics_mode=str(diagnostics_mode),
diagnostics_inputs=diagnostics_inputs,
)
def execute_v38_runtime_request(
request: RuntimeRequest,
*,
runtime_adapter: Callable[..., Any],
legacy_size_source: str,
diagnostics_off: str,
diagnostics_full: str,
reference_video_size_default: str,
build_diagnostics: Callable[..., Any],
append_status: Callable[..., str],
) -> Any:
"""Call the existing runtime once and add V3.8 display-only diagnostics."""
output = RuntimeOutput(runtime_adapter(**request.runtime_kwargs))
if not output.has_status:
return output.as_public_tuple()
if request.size_source != legacy_size_source:
resolution = request.resolution
lines = [
(
f"Resolution: {resolution.width} x {resolution.height} "
f"({resolution.actual_mp:.2f} MP); source={resolution.aspect_source}."
)
]
lines.extend(resolution.warnings)
output = output.with_status(output.status.rstrip() + "\n" + "\n".join(lines))
if request.diagnostics_mode == diagnostics_off:
return output.as_public_tuple()
try:
inputs = request.diagnostics_inputs
diagnostics = build_diagnostics(
video_latents=output.value[0],
audio_latents=output.value[1],
assembly_plan=output.value[2],
output_width=request.resolution.width,
output_height=request.resolution.height,
chunk_seconds=float(inputs["chunk_seconds"]),
reference_images=(
inputs.get("reference_image_1"),
inputs.get("reference_image_2"),
inputs.get("reference_image_3"),
),
reference_size=str(inputs.get("reference_size", "Match Output")),
video_guide=inputs.get("reference_video_1"),
video_guide_size=str(
inputs.get("video_reference_size", reference_video_size_default)
),
still_guide_active=inputs.get("guide") is not None,
)
status = append_status(
output.status,
diagnostics,
mode=request.diagnostics_mode,
)
except Exception as exc:
message = (
"V3.8 Reliability\n"
"Reliability diagnostics unavailable; generation result was preserved."
)
if request.diagnostics_mode == diagnostics_full:
message += f" ({type(exc).__name__}: {exc})"
status = output.status.rstrip() + "\n" + message
return output.with_status(status).as_public_tuple()
+168 -5
View File
@@ -1,8 +1,8 @@
"""Public latent-first facade nodes for H3 Continuum V3."""
from __future__ import annotations
import time
from __future__ import annotations
import time
from ..constants import (
CHUNK_SECONDS_DEFAULT,
@@ -23,8 +23,15 @@ from ..v2.nodes import (
validate_sparse_prompt_overrides,
)
from .assembly import H3ContinuumAssembleSeamExperimental, H3ContinuumAssembleV3
from .plan import make_assembly_plan
from ..timeline_video import TIMELINE_VIDEO_SIZE_OPTIONS
from .plan import make_assembly_plan
from .execution_planner import (
PROJECTION_CURRENT_REVIEW_UNIT,
PROJECTION_FULL_ACCEPTED_PREFIX,
resolve_projection_decision as _resolve_projection_decision,
)
from .planning_types import ProjectionDecision
from .review_control import REVISION_STATUS_REVIEW_READY
from ..timeline_video import TIMELINE_VIDEO_SIZE_OPTIONS
REGENERATE_AUTO = "Auto"
@@ -67,6 +74,51 @@ _PARTIAL_REVIEW_SECOND_PASS_WARNING = (
)
def resolve_projection_decision(
*,
review_execution,
effective_result_status: str,
session,
physical_group_facts: tuple[tuple[int, ...], ...],
) -> ProjectionDecision:
"""Compatibility adapter for the R1 pure resolver API."""
entries = session.get("chunks") if isinstance(session, dict) else None
return _resolve_projection_decision(
review_execution=review_execution,
effective_result_status=effective_result_status,
accepted_chunks=(len(entries) if isinstance(entries, list) else 0),
physical_group_facts=physical_group_facts,
)
def _physical_group_facts(assembly_plan) -> tuple[tuple[int, ...], ...]:
"""Extract immutable logical membership facts from an existing assembly plan."""
if not isinstance(assembly_plan, dict):
return ()
groups = assembly_plan.get("decode_groups") or assembly_plan.get("chunks")
if not isinstance(groups, list):
return ()
facts = []
for group in groups:
if not isinstance(group, dict):
return ()
indices = group.get("logical_chunk_indices")
if indices is None:
indices = [group.get("chunk_index")]
if not isinstance(indices, list) or not indices:
return ()
try:
normalized = tuple(int(index) for index in indices)
except (TypeError, ValueError):
return ()
if any(index < 1 for index in normalized):
return ()
facts.append(normalized)
return tuple(facts)
def _partial_review_warning(storage, *, capture_refine_context: bool) -> str:
execution = getattr(storage, "review_execution", None)
if (
@@ -78,6 +130,107 @@ def _partial_review_warning(storage, *, capture_refine_context: bool) -> str:
return ""
def _review_decode_chunk_range(storage, *, capture_refine_context: bool):
# Refine context is a separate, preserved output; capturing it does not
# require external VAE nodes to decode the entire accepted prefix.
if getattr(storage, "review_generation_mode", None) != "Review Each Chunk":
return None
execution = getattr(storage, "review_execution", None)
if execution is None or bool(getattr(execution, "finish_remaining", False)):
return None
start = getattr(execution, "next_review_unit_start", None)
end = getattr(execution, "next_review_unit_end", None)
if start is None or end is None:
return None
if not (
bool(getattr(execution, "partial_review", False))
or bool(getattr(execution, "smart_regenerate", False))
):
return None
return int(start), int(end)
def _apply_review_decode_scope(
outputs,
*,
storage,
capture_refine_context: bool,
configured_chunks: int,
chunk_seconds: float,
first_frame,
last_frame,
timeline_video_source,
):
_, _, assembly_plan, result, *tail = outputs
session = result.get("session") if isinstance(result, dict) else None
entries = session.get("chunks") if isinstance(session, dict) else None
if not isinstance(entries, list):
return outputs
execution_plan = getattr(storage, "execution_plan", None)
decision = getattr(execution_plan, "projection", None)
if not isinstance(decision, ProjectionDecision):
# Compatibility for isolated callers that replace the sequence runtime
# and therefore cannot carry its Queue-local plan. The same pure
# resolver remains the only Projection owner.
effective_status = (
REVISION_STATUS_REVIEW_READY
if getattr(storage, "review_generation_mode", None)
== "Review Each Chunk"
else "complete"
)
decision = resolve_projection_decision(
review_execution=getattr(storage, "review_execution", None),
effective_result_status=effective_status,
session=session,
physical_group_facts=_physical_group_facts(assembly_plan),
)
if decision.kind != PROJECTION_CURRENT_REVIEW_UNIT:
return outputs
start = int(decision.start_chunk)
end = int(decision.end_chunk)
selected_entries = entries[start - 1 : end]
sequence_complete = len(entries) == int(configured_chunks)
from ..v2.sequence import _terminal_flf_merge_enabled
from .plan import prepare_physical_decode_entries
terminal_merged = sequence_complete and _terminal_flf_merge_enabled(
multi_chunk_flf=(
first_frame is not None
and last_frame is not None
and int(configured_chunks) > 1
),
chunks=int(configured_chunks),
chunk_seconds=float(chunk_seconds),
prompt_hashes=[str(entry["prompt_hash"]) for entry in entries],
timeline_video_source=timeline_video_source,
)
selected_terminal_merged = terminal_merged and (
end == int(configured_chunks)
and start <= int(configured_chunks) - 1
)
decode_entries, scoped_plan = prepare_physical_decode_entries(
selected_entries,
chunk_seconds=float(chunk_seconds),
preserve_final_frame=(
sequence_complete
and end == int(configured_chunks)
and last_frame is not None
),
terminal_merged=selected_terminal_merged,
terminal_initial_pair=(start == 1),
)
scoped_video = [{"samples": entry["video"]} for entry in decode_entries]
scoped_audio = [{"samples": entry["audio"]} for entry in decode_entries]
scoped_result = dict(result)
scoped_result["report"] = str(scoped_result.get("report", "")).rstrip() + (
f"\nDecode preview: Chunk {start}"
if start == end
else f"\nDecode preview: Chunks {start}-{end}"
)
return (scoped_video, scoped_audio, scoped_plan, scoped_result, *tail)
def _format_review_status(storage, *, detailed: bool = False) -> str:
"""Format Phase D facts after finalize without reading storage in frontend."""
@@ -1005,6 +1158,16 @@ class H3ContinuumSamplerProduction(H3ContinuumSamplerV3):
take_action=str(take_action),
)
execute_outputs = execute()
execute_outputs = _apply_review_decode_scope(
execute_outputs,
storage=storage,
capture_refine_context=bool(capture_refine_context),
configured_chunks=int(chunks),
chunk_seconds=float(chunk_seconds),
first_frame=first_frame,
last_frame=last_frame,
timeline_video_source=timeline_video_source,
)
if bool(capture_refine_context):
video_latents, audio_latents, assembly_plan, result, refine_context = execute_outputs
else:
+35 -13
View File
@@ -223,13 +223,21 @@ def _attach_second_pass_contract(
logical_entries: list[dict[str, Any]],
physical_entries: list[dict[str, Any]],
chunk_seconds: float,
logical_chunk_indices: list[int] | None = None,
) -> None:
"""Attach additive V3.5 metadata without changing V3.4 generation semantics."""
chunk_indices = (
list(range(1, len(logical_entries) + 1))
if logical_chunk_indices is None
else [int(value) for value in logical_chunk_indices]
)
if len(chunk_indices) != len(logical_entries):
raise ValueError("logical chunk identity count does not match entries")
decode_groups = plan.get("decode_groups")
if not isinstance(decode_groups, list):
decode_groups = [
{
"logical_chunk_indices": [index + 1],
"logical_chunk_indices": [chunk_indices[index]],
"terminal_merged": False,
"total_frames": plan["chunks"][index]["total_frames"],
"trim_frames": plan["chunks"][index]["trim_frames"],
@@ -237,6 +245,10 @@ def _attach_second_pass_contract(
for index in range(len(physical_entries))
]
prompt_by_chunk = {
chunk_indices[index]: str(entry.get("prompt", ""))
for index, entry in enumerate(logical_entries)
}
groups: list[dict[str, Any]] = []
for group_id, (entry, decode_group) in enumerate(
zip(physical_entries, decode_groups, strict=True)
@@ -244,7 +256,7 @@ def _attach_second_pass_contract(
video = entry["video"]
audio = entry["audio"]
logical_chunks = [int(value) for value in decode_group["logical_chunk_indices"]]
prompts = [str(logical_entries[index - 1].get("prompt", "")) for index in logical_chunks]
prompts = [prompt_by_chunk[index] for index in logical_chunks]
if len(prompts) == 1:
physical_prompt = prompts[0]
prompt_policy = "single"
@@ -284,26 +296,31 @@ def _attach_second_pass_contract(
def prepare_physical_decode_entries(
entries,
*,
chunk_seconds: float,
preserve_final_frame: bool,
terminal_merged: bool,
):
entries,
*,
chunk_seconds: float,
preserve_final_frame: bool,
terminal_merged: bool,
terminal_initial_pair: bool | None = None,
):
"""Return external-VAE decode units while preserving logical plan metadata."""
logical_entries = list(entries)
plan = make_assembly_plan(
logical_entries = list(entries)
plan = make_assembly_plan(
logical_entries,
chunk_seconds=float(chunk_seconds),
preserve_final_frame=bool(preserve_final_frame),
)
preserve_final_frame=bool(preserve_final_frame),
)
logical_chunk_indices = [
int(chunk["chunk_index"]) for chunk in plan["chunks"]
]
if not terminal_merged:
_attach_second_pass_contract(
plan,
logical_entries=logical_entries,
physical_entries=logical_entries,
chunk_seconds=float(chunk_seconds),
logical_chunk_indices=logical_chunk_indices,
)
return logical_entries, plan
if len(logical_entries) < 2:
@@ -311,7 +328,11 @@ def prepare_physical_decode_entries(
from ..v2.sequence import _terminal_pair_contract
initial_pair = len(logical_entries) == 2
initial_pair = (
len(logical_entries) == 2
if terminal_initial_pair is None
else bool(terminal_initial_pair)
)
contract = _terminal_pair_contract(
initial_pair=initial_pair,
chunk_seconds=float(chunk_seconds),
@@ -382,6 +403,7 @@ def prepare_physical_decode_entries(
logical_entries=logical_entries,
physical_entries=decode_entries,
chunk_seconds=float(chunk_seconds),
logical_chunk_indices=logical_chunk_indices,
)
validate_assembly_plan(plan)
return decode_entries, plan
+83
View File
@@ -0,0 +1,83 @@
"""Immutable facts shared by the pure Continuum execution planner.
This module must remain free of torch and ComfyUI imports. Runtime payloads
stay in their existing adapters and are projected into these facts only after
the active continuation source has already been selected.
"""
from __future__ import annotations
from dataclasses import dataclass
from .review_control import ReviewUnit
@dataclass(frozen=True, slots=True)
class PrefixFacts:
"""Immutable planning projection of one fully validated storage prefix."""
accepted_chunks: int
configured_chunks: int
revision_id: str | None
status: str | None
review_unit: ReviewUnit | None
effective_nonce: int
branch_regenerate_from: int
physical_group_boundaries: tuple[tuple[int, int], ...]
@dataclass(frozen=True, slots=True)
class ExplicitSessionFacts:
"""Characterized facts for an explicit Session runtime input."""
present: bool
compatible: bool
accepted_chunks: int
reroll_from_chunk: int | None
physical_group_boundaries: tuple[tuple[int, int], ...]
@dataclass(frozen=True, slots=True)
class InitialStateFacts:
"""Characterized facts for an initial State runtime input."""
present: bool
usable: bool
@dataclass(frozen=True, slots=True)
class ContinuationSourceFacts:
"""Planning projection of the single source selected by the runtime."""
kind: str
accepted_chunks: int
reroll_from_chunk: int | None
physical_group_boundaries: tuple[tuple[int, int], ...]
@dataclass(frozen=True, slots=True)
class ProjectionDecision:
"""Describe which accepted chunks may be exposed to external decode."""
kind: str
start_chunk: int | None = None
end_chunk: int | None = None
@dataclass(frozen=True, slots=True)
class PhysicalGroupDescriptor:
"""One atomic sampling group expressed in one-based logical chunks."""
physical_group: int
logical_chunks: tuple[int, ...]
terminal_atomic: bool
@dataclass(frozen=True, slots=True)
class ExecutionPlan:
"""Pure plan consumed by the unchanged runtime execution loops."""
groups_to_generate: tuple[PhysicalGroupDescriptor, ...]
projection: ProjectionDecision
expected_status: str
expected_review_unit: ReviewUnit | None
+1 -2
View File
@@ -10,7 +10,7 @@ from typing import Any
import torch
from .temporal import align_frame_count_up
from ..temporal import align_frame_count_up
REFERENCE_VIDEO_CONTRACT_VERSION = 1
@@ -279,4 +279,3 @@ def validate_reference_video_prompts(
"<Video 1> tag; video still conditions generation, but an explicit tag is "
"recommended."
)
+45
View File
@@ -397,6 +397,51 @@ def _branch_contract(
return nonce, branch_start
def validate_review_prefix_metadata(
*,
configured_chunks: int,
validated_prefix_count: int,
terminal_merge_enabled: bool,
terminal_pair_start: int | None,
latest_review_unit: ReviewUnit | Mapping[str, Any] | None,
latest_revision_status: str | None,
latest_effective_nonce: int,
latest_branch_regenerate_from: Any = 0,
) -> ReviewUnit | None:
"""Validate persisted Review metadata without creating an execution decision.
Repository reads and finalization use this boundary after raw prefix
validation. It deliberately returns no ``ReviewExecution`` so those paths
cannot become a second policy owner.
"""
chunks, prefix, pair_start = _review_geometry(
configured_chunks=configured_chunks,
validated_prefix_count=validated_prefix_count,
terminal_merge_enabled=terminal_merge_enabled,
terminal_pair_start=terminal_pair_start,
)
status = _revision_status(
latest_revision_status,
prefix=prefix,
chunks=chunks,
)
unit = _validated_review_unit(
latest_review_unit,
configured_chunks=chunks,
validated_prefix_count=prefix,
terminal_pair_start=pair_start,
)
_branch_contract(
latest_effective_nonce=latest_effective_nonce,
latest_branch_regenerate_from=latest_branch_regenerate_from,
validated_prefix_count=prefix,
configured_chunks=chunks,
latest_revision_status=status,
)
return unit
def _nonce_decision(
*,
manual_regenerate_from: int,
+223
View File
@@ -0,0 +1,223 @@
"""Internal owner of Continuum runtime continuation-source priority.
The pure execution planner receives only the source selected here. Runtime
payload validation remains outside the planner so Run Storage, explicit
Session, and initial State can never become competing planner inputs.
"""
from __future__ import annotations
from dataclasses import dataclass
import logging
from typing import Any
from ..branch_provenance import physical_groups
from ..run_storage import RunStorageError
from ..state import validate_state
from ..v2.session import SessionValidationError, entry_to_state
from .planning_types import ContinuationSourceFacts
LOG = logging.getLogger("h3_continuum_join")
class RuntimeCoordinatorError(ValueError):
"""Raised when the characterized runtime source contract is invalid."""
@dataclass(slots=True)
class RuntimeContinuationSelection:
"""Selected runtime payload plus its single planning projection."""
entries: list[dict[str, Any]]
previous_state: dict[str, Any] | None
continuation_source_facts: ContinuationSourceFacts
notes: tuple[str, ...]
def project_selected_continuation_source(
*,
kind: str,
selected_source: dict[str, Any] | None,
) -> ContinuationSourceFacts:
"""Project one already-selected runtime source into planning-only facts."""
normalized_kind = str(kind)
if normalized_kind == "none":
if selected_source is not None:
raise RuntimeCoordinatorError("the none continuation source has no payload")
return ContinuationSourceFacts(
kind="none",
accepted_chunks=0,
reroll_from_chunk=0,
physical_group_boundaries=(),
)
if normalized_kind not in {
"run_storage",
"explicit_session",
"initial_state",
}:
raise RuntimeCoordinatorError(
f"unknown selected continuation source: {normalized_kind!r}"
)
if not isinstance(selected_source, dict):
raise RuntimeCoordinatorError(
"the selected continuation source requires normalized runtime facts"
)
try:
accepted_chunks = int(selected_source["accepted_chunks"])
reroll_from_chunk = int(selected_source["reroll_from_chunk"])
boundaries = tuple(
(int(start), int(end))
for start, end in selected_source["physical_group_boundaries"]
)
except (KeyError, TypeError, ValueError) as exc:
raise RuntimeCoordinatorError(
"selected continuation source facts are invalid"
) from exc
return ContinuationSourceFacts(
kind=normalized_kind,
accepted_chunks=accepted_chunks,
reroll_from_chunk=reroll_from_chunk,
physical_group_boundaries=boundaries,
)
class InternalRuntimeCoordinator:
"""Own the established Storage / Session / State priority contract."""
def __init__(
self,
*,
storage_controller: Any,
input_session: dict[str, Any] | None,
initial_state: dict[str, Any] | None,
) -> None:
self.storage_controller = storage_controller
self.input_session = input_session
self.initial_state = initial_state
self.session_present = input_session is not None
@property
def storage_enabled(self) -> bool:
return self.storage_controller is not None
def prepare_inputs(
self,
) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
"""Suppress State as soon as an explicit Session is present."""
if self.session_present and self.initial_state is not None:
LOG.warning(
"Both session and initial_state were supplied; using the session "
"and ignoring initial_state"
)
self.initial_state = None
return self.input_session, self.initial_state
def assert_storage_session_compatible(self) -> None:
"""Preserve the existing Run Storage plus explicit Session hard error."""
if self.storage_enabled and self.session_present:
raise RunStorageError(
"Run Storage cannot be combined with an explicit Session"
)
def validate_initial_state_reroll(self, reroll_from_chunk: int) -> None:
"""Apply the existing reroll restriction to the effective State only."""
if self.initial_state is not None and int(reroll_from_chunk) not in (0, 1):
raise RuntimeCoordinatorError(
"with initial_state, reroll_from_chunk can only be 0 or 1"
)
def select_continuation_source(
self,
*,
preserved: list[dict[str, Any]],
initial_state: dict[str, Any] | None,
chunks: int,
width: int,
height: int,
reroll_from_chunk: int,
effective_reroll_from_chunk: int,
terminal_merge_enabled: bool,
) -> RuntimeContinuationSelection:
"""Select exactly one runtime continuation source, then project it."""
entries = preserved[:]
previous_state = None
notes: list[str] = []
if entries:
try:
previous_state = entry_to_state(entries[-1])
except (SessionValidationError, ValueError) as exc:
notes.append(
"saved continuation state was rejected; generated a fresh run "
f"({exc})"
)
entries = []
previous_state = None
# An initial State is considered only if no usable Storage/Session prefix
# survived. Explicit Session presence already suppressed it in
# prepare_inputs(), before Session validity was known.
if not entries and initial_state is not None:
try:
candidate = validate_state(initial_state)
if int(candidate["width"]) != int(width) or int(
candidate["height"]
) != int(height):
notes.append(
"initial_state resolution differs; generated a fresh run"
)
else:
previous_state = candidate
except ValueError as exc:
notes.append(
f"initial_state was rejected; generated a fresh run ({exc})"
)
if entries:
selected_kind = (
"run_storage" if self.storage_enabled else "explicit_session"
)
source_reroll = (
int(reroll_from_chunk)
if self.storage_enabled
else int(effective_reroll_from_chunk)
)
accepted_boundaries = tuple(
(int(group.start), int(group.end))
for group in physical_groups(
chunks=int(chunks),
terminal_merge_enabled=bool(terminal_merge_enabled),
)
if int(group.end) <= len(entries)
)
selected_source = {
"accepted_chunks": len(entries),
"reroll_from_chunk": source_reroll,
"physical_group_boundaries": accepted_boundaries,
}
elif previous_state is not None and initial_state is not None:
selected_kind = "initial_state"
selected_source = {
"accepted_chunks": 0,
"reroll_from_chunk": int(reroll_from_chunk),
"physical_group_boundaries": (),
}
else:
selected_kind = "none"
selected_source = None
return RuntimeContinuationSelection(
entries=entries,
previous_state=previous_state,
continuation_source_facts=project_selected_continuation_source(
kind=selected_kind,
selected_source=selected_source,
),
notes=tuple(notes),
)
+71
View File
@@ -0,0 +1,71 @@
"""One-physical-group Sampling Engine for the Continuum runtime."""
from __future__ import annotations
from typing import Any, Callable
def sample_physical_group(
*,
sample_callable: Callable[..., Any],
model: Any,
conditioning: Any,
latent: Any,
sampler: Any,
sigmas: Any,
seed: int,
enable_preview: bool,
physical_group: int,
logical_chunks: tuple[int, ...],
terminal_atomic: bool,
layout_validation_profiler: Any = None,
packed_row_planner: Any = None,
planner_event: Any = None,
diagnostic_policy: Any = None,
context_frames: int = 0,
) -> tuple[Any, Any]:
"""Run exactly one physical sample with unchanged observer ordering."""
normalized_chunks = tuple(int(value) for value in logical_chunks)
layout_profile_token = (
layout_validation_profiler.begin_sampling_group(
physical_group=int(physical_group),
logical_chunks=normalized_chunks,
sampling_steps=max(0, int(sigmas.shape[-1]) - 1),
)
if layout_validation_profiler is not None
else None
)
diagnostic_sample_token = None
if diagnostic_policy is not None:
diagnostic_sample_token = diagnostic_policy.before_sampling(
physical_group=int(physical_group),
logical_chunks=normalized_chunks,
context_frames=int(context_frames),
latent=latent,
conditioning=conditioning,
seed=int(seed),
sigmas=sigmas,
)
if planner_event is not None:
planner_event(
packed_row_planner,
"begin_group",
physical_group=int(physical_group),
logical_chunks=normalized_chunks,
terminal_atomic=bool(terminal_atomic),
)
sampled = sample_callable(
model=model,
conditioning=conditioning,
latent=latent,
sampler=sampler,
sigmas=sigmas,
seed=int(seed),
enable_preview=bool(enable_preview),
)
if planner_event is not None:
planner_event(packed_row_planner, "finish_group")
if layout_validation_profiler is not None and layout_profile_token is not None:
layout_validation_profiler.finish_sampling_group(layout_profile_token)
return sampled, diagnostic_sample_token