From d8300bed03921d7f5baf3f62702735686e2c5a28 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Fri, 13 Nov 2026 19:15:49 -0600 Subject: [PATCH 001/412] chore: open 0.21.0-alpha.1 on develop --- plugins/dw/.claude-plugin/plugin.json | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/dw/.claude-plugin/plugin.json b/plugins/dw/.claude-plugin/plugin.json index 6e2ffa6ee..d25f12248 100644 --- a/plugins/dw/.claude-plugin/plugin.json +++ b/plugins/dw/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "dw", "description": "Compose MiniMax H3 video, MiniMax Music 3, LTX-2.5, Kandinsky 6.0 and FLUX 3 Klein workflows over a dw MCP server, cut a multi-episode series from them, direct camera and look in each family's caption format, storyboard a scene before it is filmed, and plan a piece longer than one clip from measured levers: which template fits which shape, the hard rules, cost, and how to judge the output. Prompt format comes from the vendors' own guides.", - "version": "0.20.0", + "version": "0.21.0-alpha.1", "author": { "name": "Don Kackman" }, diff --git a/pyproject.toml b/pyproject.toml index a7c3b1d78..510995c54 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ name = "diffusers-workflow" # runtime (static in TOML because importing dw at build time would drag # torch into the build environment). Release tags must match it - see # docs/RELEASING.md -version = "0.20.0" +version = "0.21.0-alpha.1" description = "Declarative workflow engine and web UI for Hugging Face Diffusers" readme = "README.md" requires-python = ">=3.12" From 52c3fd7d755b568ee32148c8dc1a340809f7b9ec Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Fri, 13 Nov 2026 19:30:08 -0600 Subject: [PATCH 002/412] fix(worker): #1333 - trust refusal runs before the cached-model release, so a refused job leaves warm models alone Co-Authored-By: Claude Sonnet 5.5 --- dw/pipeline_processors/pipeline.py | 20 ++----------- dw/trust.py | 23 +++++++++++++++ dw/worker.py | 3 ++ dw/workflow_run.py | 45 +++++++++++++++++++++-------- tests/test_worker_execute.py | 46 ++++++++++++++++++++++++++++++ 5 files changed, 107 insertions(+), 30 deletions(-) diff --git a/dw/pipeline_processors/pipeline.py b/dw/pipeline_processors/pipeline.py index 66000a3f9..c83a40445 100644 --- a/dw/pipeline_processors/pipeline.py +++ b/dw/pipeline_processors/pipeline.py @@ -42,7 +42,7 @@ from .remote import remote_text_encoder from ..type_helpers import has_method from ..trust import ( - require_trusted_from_pretrained_arguments, + require_trusted_block, require_trusted_pre_load_modules, ) from .. import empty_device_cache, resolve_device @@ -317,23 +317,7 @@ def check_trusted(self): # Walk the whole definition rather than the component names this class # knows: a gate that only covers what it remembers to enumerate stops # covering a block added later - self._check_trusted_block(self.pipeline_definition, "pipeline") - - @staticmethod - def _check_trusted_block(block, what): - if not isinstance(block, dict): - return - require_trusted_from_pretrained_arguments( - block.get("from_pretrained_arguments"), what - ) - for key, value in block.items(): - if key == "from_pretrained_arguments": - continue - if isinstance(value, dict): - Pipeline._check_trusted_block(value, key) - elif isinstance(value, list): - for entry in value: - Pipeline._check_trusted_block(entry, key) + require_trusted_block(self.pipeline_definition, "pipeline") def apply_runtime_settings(self): """Re-apply what a run may have changed without changing the weights: diff --git a/dw/trust.py b/dw/trust.py index fef69066a..b466a1008 100644 --- a/dw/trust.py +++ b/dw/trust.py @@ -277,6 +277,29 @@ def require_trusted_from_pretrained_arguments(arguments, what: str) -> None: ) +def require_trusted_block(block, what: str) -> None: + """require_trusted_from_pretrained_arguments over a whole definition: + every nested block's from_pretrained_arguments, so a gate that covers a + block added later without enumerating it. + + Raises: + UntrustedWorkflowError: If untrusted and any block sets a remote-code key + """ + if not isinstance(block, dict): + return + require_trusted_from_pretrained_arguments( + block.get("from_pretrained_arguments"), what + ) + for key, value in block.items(): + if key == "from_pretrained_arguments": + continue + if isinstance(value, dict): + require_trusted_block(value, key) + elif isinstance(value, list): + for entry in value: + require_trusted_block(entry, key) + + # generate() arguments that load and run code from the Hub. transformers' # generate() hands `custom_generate` (a repo id) to load_custom_generate, which # downloads that repo's custom_generate/generate.py and executes it in place of diff --git a/dw/worker.py b/dw/worker.py index db18ae852..e60824c70 100644 --- a/dw/worker.py +++ b/dw/worker.py @@ -380,6 +380,9 @@ def _prepare_workflow(self, command: Dict[str, Any], job: "_Job"): changed.""" job.workflow, identity = self._load_workflow(command, command["output_dir"]) + # A refusal leaves the warm cache where it was + workflow_run.require_trusted_pipelines(job.workflow, command.get("arguments")) + # Switching to a different workflow frees the old one's models # before the new one loads - on one accelerator, holding both is # what runs out of memory diff --git a/dw/workflow_run.py b/dw/workflow_run.py index 52de9c006..7cfd1f242 100644 --- a/dw/workflow_run.py +++ b/dw/workflow_run.py @@ -69,6 +69,7 @@ step_pipeline_keys, ) from .subfolders import step_subfolder +from .trust import require_trusted_block from .variable_constraints import apply_constraints from .vram_estimate import apply_vram_estimate @@ -561,6 +562,37 @@ def cache_hits(workflow, arguments): deactivate_output_root(output_root_token) +def _prepared_steps(workflow, arguments): + output_root_token = activate_output_root(workflow.output_dir) + try: + workflow_def = copy.deepcopy(workflow.workflow_definition) + base_dir = run_base_dir(workflow) + workflow_def, _, _ = prepare_definition( + workflow, workflow_def, arguments or {}, base_dir + ) + steps = workflow_def.get("steps", []) + realize_args(steps, base_dir) + return steps + finally: + deactivate_output_root(output_root_token) + + +def require_trusted_pipelines(workflow, arguments): + """Refuse an untrusted workflow whose pipeline steps reach for remote + code, before the worker releases the previous workflow's models: the run + would be refused at load, and a refusal should leave the warm cache where + it was. Raises what the loader's own gate raises; a definition that + cannot be prepared is left for the run to report.""" + try: + steps = _prepared_steps(workflow, arguments) + except Exception as e: + logger.debug(f"Could not prepare the definition for the trust check: {e}") + return + for step in steps: + if isinstance(step, dict): + require_trusted_block(step.get("pipeline"), "pipeline") + + def pipeline_keys(workflow, arguments): """The set of pipeline cache keys a run of `workflow` with `arguments` loads its steps under - the table run() and cache_hits() take @@ -574,18 +606,7 @@ def pipeline_keys(workflow, arguments): the price of loading step media once per switch (the price cache_hits already pays). """ - output_root_token = activate_output_root(workflow.output_dir) - try: - workflow_def = copy.deepcopy(workflow.workflow_definition) - base_dir = run_base_dir(workflow) - workflow_def, _, _ = prepare_definition( - workflow, workflow_def, arguments or {}, base_dir - ) - steps = workflow_def.get("steps", []) - realize_args(steps, base_dir) - return set(step_pipeline_keys(steps).values()) - finally: - deactivate_output_root(output_root_token) + return set(step_pipeline_keys(_prepared_steps(workflow, arguments)).values()) def prepare_run(workflow, record): diff --git a/tests/test_worker_execute.py b/tests/test_worker_execute.py index 2fea7a729..1fb7f3912 100644 --- a/tests/test_worker_execute.py +++ b/tests/test_worker_execute.py @@ -742,3 +742,49 @@ def test_poisons_cuda_context_matches_sticky_errors_only(): assert poisons_cuda_context("x", "Returning 710 (CUDA_ERROR_ASSERT) from y") assert not poisons_cuda_context("CUDA out of memory", None) + + +class TestRefusalKeepsWarmCache: + """#1333: a job the trust gate refuses must not evict the warm models + of the workflow before it.""" + + def test_refused_job_keeps_loaded_pipelines_and_emits_no_release(self, tmp_path): + from dw.trust import set_trust_workflows + + definition = { + "id": "hostile", + "steps": [ + { + "name": "gen", + "pipeline": { + "configuration": { + "model_name": "m/p", + "pipeline_type": "StableDiffusionPipeline", + }, + "from_pretrained_arguments": {"trust_remote_code": True}, + }, + } + ], + } + worker = _make_worker() + worker.workflow_identity = ("path", "/w/warm.json") + worker.loaded_pipelines["warm"] = object() + command = snapshot_command( + file_spec="/w/hostile.json", + definition=definition, + output_dir=str(tmp_path), + ) + set_trust_workflows(False) + with patch("dw.worker.workflow_from_snapshot") as admit: + from dw.workflow import Workflow + + admit.return_value = Workflow( + definition, str(tmp_path), "/w/hostile.json", None + ) + worker._handle_execute(command) + messages = _drain(worker.result_queue) + assert "warm" in worker.loaded_pipelines + assert worker.workflow_identity == ("path", "/w/warm.json") + assert not any("Workflow changed" in str(m) for m in messages) + failed = [m for m in messages if m["type"] == "error"] + assert failed and "trust_remote_code" in str(failed[0]) From 8e15807e713c9644a07b1a09a013b1d2d297412f Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Fri, 13 Nov 2026 19:50:36 -0600 Subject: [PATCH 003/412] feat(plan): #1334 - a checked chain's quote is floored at the same chain unchecked at its worst case A thin, fast checked history tempered to the unchecked chain's curated figure (C-F747). The checked run is also priced from the unchecked shape's own history (or the curated row) worst-cased, and the higher quoted. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 2 +- docs/WORKFLOW_GUIDE.md | 4 +- dw/plan.py | 119 +++++++++++++++++++++++++++++++++++++++-- tests/test_plan.py | 71 ++++++++++++++++++++++++ 4 files changed, 189 insertions(+), 7 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e3d26f7c9..596b51be8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -116,7 +116,7 @@ one to open. | Download sources | `dw/plan_downloads.py`: `downloads_required`, `_collect_sources`, `_collect_component_overrides`, `_sub_workflow_paths` (which `plan.estimate` walks children by too; the module never imports `dw/plan.py` back, and `plan.py` re-exports `downloads_required` and `gate_warnings`) | `downloads_required` lists every `model_name`, `loras` repo (a `loras` entry naming a resolved `weight_name` is listed instead as a `{repo, filename, revision}` file entry built by `file_entries`, sized as that file), single-file URL and `load_components.pretrained_model_name_or_path` override (string, per-component dict, `default`), once each. The base repo stays listed whole: an override's replaced subfolder is not subtracted, so the list is a floor. | `tests/test_plan.py::TestDownloadsRequired::test_a_load_components_repo_override_is_listed` | | Task weights | each fetching task's `*_source(arguments)` (e.g. `dw/tasks/remove_object.py`: `remover_source`); `dw/tasks/weights.py`: `argument_or_default`, `file_entries`, `package_dir`; `dw/tasks/registry.py`: `required_weights_hook`, `register_weights_fallback`; `dw/tasks/image_utils.py`: `processor_weights_hook`; `dw/security.py`: `validate_weight_name`; `dw/plan_downloads.py`: `_collect_task_weights`, `_file_info` | A model-backed task declares `required_weights(arguments)` on its `register_command`, and `downloads_required` lists those repos beside the pipeline `model_name`s (a shared repo once; a reference or local-path argument none). A single-file task lists `{repo, filename, revision}` entries, checked per file against the cache; `restore_faces` also lists facexlib's weights as URL entries. A task's declaration and its loader read the same resolution of which argument wins (a single-file task's `*_source(arguments)`, an overridable whole-repo task's `argument_or_default` call, a fixed repo's module constant), so they cannot differ; `argument_or_default` is the shared helper only where `None` means the default (`remover_source` and `upscaler_source` treat any falsy value as absent; `spandrel_source` has no default). `file_entries` builds a file entry (its name checked by `validate_weight_name`), `package_dir` finds facexlib's weights dir without importing it, and `_file_info` sizes one file. The lookup path is acyclic: `dw/locations.py` reads the registry's tables and the task modules import the location policy and `weights.py`, so the registry imports no task module (an image processor's hook reaches it through `register_weights_fallback`, which `image_utils` calls at import) and `weights.py` imports only `dw/security.py`, where `validate_weight_name` lives for that reason. A task module the hook lookup imports keeps `transformers` out of its module top (`hf_pipeline` is a lazy wrapper, patched by name in the tests), so a validate never pays for it. | `tests/test_task_weights.py`, `tests/test_task_weights.py::TestTheHookPathStaysAcyclic::test_weights_imports_only_the_security_leaf_from_dw`, `tests/test_task_weights.py::TestTheHookPathStaysAcyclic::test_the_registry_imports_nothing_from_dw` | | Observed cost | `dw/server/observed_cost.py`: `declared_drivers`, `ObservedCosts._on_this_card`, `ObservedCosts.card` | `observed` comes only from this box's finished jobs on the named card (the one `route` names, for `plan.estimate`), else the server's own card; `ObservedCosts.card` owns a card's (kind, name), including the default card's name. Rows are matched by card name whatever index they ran on (a job from before jobs carried a `device` counts as the default card's name, so it matches any card of that model), and never writes `cost`. Cold and warm runs are reported separately. | `tests/test_observed_cost.py::TestColdIsNotWarm::test_the_two_are_reported_separately_each_with_its_runs`, `tests/test_observed_cost.py::TestByCard::test_only_rows_from_this_card_count_whichever_index_they_had`, `tests/test_observed_cost.py::TestByCard::test_rows_from_before_jobs_carried_a_device_do_not_count_for_another_model`, `tests/test_observed_cost.py::TestByCard::test_rows_from_before_jobs_carried_a_device_count_on_the_default_card` | -| The estimate | `dw/plan.py`: `estimate`, `_tempered`; the driver scaling is `dw/cost_scaling.py`: `scale_curated`, `_driver_scaling` | `plan.estimate` quotes the observed figure ahead of the curated one, and blends it toward the curated figure below three runs. A `cost` entry is measured at the workflow's variable defaults; a run moving `num_inference_steps`, `width`/`height`, `num_frames` or a driver the entry names in `scales_with` (per list entry, summed) scales it in proportion (`scale_curated`, which `dw/server/deps.py` reuses for an inherited figure), basis `derived` with `scaled` naming each axis, times the list-length re-price, and that scaled figure is what a thin observed one blends toward (#866). A `cost` entry's optional `fixed_minutes` (model load, warm-up, decode setup) is held out of the scaling: `fixed + (minutes - fixed) x factor` (`fixed_minutes` reads the entry `_choose_entry` picked, the one `_price` quotes from; `_scaled`; #1224). Observed history scaled by a driver or by a checked chain's worst-case re-rolls holds the same entry's fixed *share* of itself (`fixed_share`: `fixed_minutes / minutes`), not its minutes, since this box can be far faster or slower than the curated card. A preset tier with no history of its own, or too thin a bucket, is priced from (or blended toward) this box's observed default-tier figure scaled by the same rule instead, a driver the tier moves that nothing scales named in `differs` (#1236). | `tests/test_plan.py::TestObservedEstimate::test_history_beats_a_curated_figure`, `tests/test_plan.py::TestLowConfidenceObservedEstimate::test_a_single_run_blends_toward_the_curated_figure`, `tests/test_plan.py::TestDriverScaling::test_steps_canvas_and_frames_multiply`, `tests/test_plan.py::TestScalingAccuracy::test_within_thirty_percent`, `tests/test_plan.py::TestTiersPriceFromTheObservedDefault::test_a_thin_draft_bucket_tempers_toward_the_observed_default`, `tests/test_plan.py::TestDeclaredProportionalDrivers::test_a_declared_scalar_scales_in_proportion`, `tests/test_cost_fixed_minutes.py::test_the_fixed_share_is_not_multiplied`, `tests/test_cost_fixed_minutes.py::test_the_fixed_share_comes_from_the_entry_price_quoted`, `tests/test_chain_check.py::test_an_observed_worst_case_holds_the_fixed_share` | +| The estimate | `dw/plan.py`: `estimate`, `_tempered`; the driver scaling is `dw/cost_scaling.py`: `scale_curated`, `_driver_scaling` | `plan.estimate` quotes the observed figure ahead of the curated one, and blends it toward the curated figure below three runs. A `cost` entry is measured at the workflow's variable defaults; a run moving `num_inference_steps`, `width`/`height`, `num_frames` or a driver the entry names in `scales_with` (per list entry, summed) scales it in proportion (`scale_curated`, which `dw/server/deps.py` reuses for an inherited figure), basis `derived` with `scaled` naming each axis, times the list-length re-price, and that scaled figure is what a thin observed one blends toward (#866). A `cost` entry's optional `fixed_minutes` (model load, warm-up, decode setup) is held out of the scaling: `fixed + (minutes - fixed) x factor` (`fixed_minutes` reads the entry `_choose_entry` picked, the one `_price` quotes from; `_scaled`; #1224). Observed history scaled by a driver or by a checked chain's worst-case re-rolls holds the same entry's fixed *share* of itself (`fixed_share`: `fixed_minutes / minutes`), not its minutes, since this box can be far faster or slower than the curated card. A preset tier with no history of its own, or too thin a bucket, is priced from (or blended toward) this box's observed default-tier figure scaled by the same rule instead, a driver the tier moves that nothing scales named in `differs` (#1236). A checked chain's quote is floored at the same chain unchecked (`check` off, `retries` 0) priced at its worst case, from that shape's own history or else the curated row (`_checked_estimate`), so a thin fast checked bucket never quotes no more than the unchecked chain (#1334). | `tests/test_plan.py::TestCheckedChainQuotesMoreThanUnchecked::test_a_thin_fast_checked_history_quotes_above_the_unchecked`, `tests/test_plan.py::TestObservedEstimate::test_history_beats_a_curated_figure`, `tests/test_plan.py::TestLowConfidenceObservedEstimate::test_a_single_run_blends_toward_the_curated_figure`, `tests/test_plan.py::TestDriverScaling::test_steps_canvas_and_frames_multiply`, `tests/test_plan.py::TestScalingAccuracy::test_within_thirty_percent`, `tests/test_plan.py::TestTiersPriceFromTheObservedDefault::test_a_thin_draft_bucket_tempers_toward_the_observed_default`, `tests/test_plan.py::TestDeclaredProportionalDrivers::test_a_declared_scalar_scales_in_proportion`, `tests/test_cost_fixed_minutes.py::test_the_fixed_share_is_not_multiplied`, `tests/test_cost_fixed_minutes.py::test_the_fixed_share_comes_from_the_entry_price_quoted`, `tests/test_chain_check.py::test_an_observed_worst_case_holds_the_fixed_share` | | Cost drivers | `dw/server/observed_cost.py`: `declared_drivers` | A cost driver that names no declared variable is dropped. | `tests/test_observed_cost.py::TestComparability::test_a_driver_naming_no_variable_is_dropped`, `tests/test_observed_cost.py::TestTheCatalogsDriversAreReal::test_every_declared_driver_is_a_variable_of_its_workflow` | | Raw workflow GET | `dw/server/routes/library.py`: `get_workflow` | The raw workflow GET is served verbatim, with no `observed`, because the editor saves what it reads. | — | | VRAM projection | `dw/vram_estimate.py`, `dw/guides.py`: `guide_lengths` | A template's `vram_estimate` is projected per step after `for_each` expansion, and only the largest step over the ceiling is reported. With `bytes_per_guide_voxel` declared, each guide the step lays in (its own non-null `guides` plus a guide chain's) adds its snapped frames times the canvas; an unprobeable clip is charged at `num_frames`, and validate, admission and run project the same number. | `tests/test_vram_estimate.py::test_only_the_largest_over_ceiling_step_is_reported_once_per_cost_entry`, `tests/test_vram_guides.py::test_validate_apply_and_required_agree_on_a_guided_definition` | diff --git a/docs/WORKFLOW_GUIDE.md b/docs/WORKFLOW_GUIDE.md index 313599f10..39357648c 100644 --- a/docs/WORKFLOW_GUIDE.md +++ b/docs/WORKFLOW_GUIDE.md @@ -2878,7 +2878,9 @@ any other checked chain never re-rolls segment 1 and costs up to 1 + (N - 1)(1 + `retries`). The curated figure, measured without re-rolls, paid N. With `words` active the estimate adds about 0.05 min (one Whisper CPU pass) per worst-case attempt, (segments - kept) x (1 + `retries`) passes with segment 1 counted as checked, named in -the estimate's `scaled` text as "words check: N Whisper pass(es)". +the estimate's `scaled` text as "words check: N Whisper pass(es)". A checked chain never quotes less than the same chain unchecked at that worst +case: when this box's checked history is thin and fast enough to blend below it, the +quote is floored there and `scaled` says so ("floored at the same chain unchecked"). ## Schedulers diff --git a/dw/plan.py b/dw/plan.py index b53c1a62f..933f30f72 100644 --- a/dw/plan.py +++ b/dw/plan.py @@ -35,6 +35,8 @@ _scaled, with_words_check, words_check_term, + _chain_blocks, + _chain_retries, _chain_render_scaling, ) from .elision import elide_definition @@ -185,17 +187,16 @@ def build_plan( "downloads_required": downloads_required( expanded, base_dir, candidate.workflow_dir, cache_dir, lookup_sizes ), - "estimate": estimate( + "estimate": _checked_estimate( + candidate, + arguments, definition, expanded, entries, device, base_dir, - candidate.workflow_dir, measured_entries=measured_entries, - observed=_observed_block( - observed, arguments, definition, expanded, entries, device - ), + observed=observed, cached_steps=cache_hits, total_steps=step_count, observed_for_child=observed_for_child, @@ -203,6 +204,114 @@ def build_plan( } +def _checked_estimate( + candidate, + arguments, + definition, + expanded, + entries, + device, + base_dir, + *, + measured_entries, + observed, + cached_steps, + total_steps, + observed_for_child, +): + """`estimate` for the run, floored, for a checked chain, at the same + chain unchecked priced at its worst case (#1334). + + A checked chain's history and the same chain's unchecked history are + separate buckets (`check` and `retries` are cost drivers). A thin checked + bucket from a fast box tempers below the curated figure, while the + unchecked shape with no history quotes the curated one at full + authority, so a checked chain could quote no more than the same chain + unchecked. The floor is the checked run priced from the *unchecked* + run's own history (`_with_worst_case` adds the re-rolls and the words + passes to it, tempered as usual), or from the curated row when that + shape has none: whatever the unchecked chain would quote, plus the worst + case. The higher of the two is quoted, with `scaled` saying the floor + was taken and what this box's checked history alone said.""" + + def quote(block): + return estimate( + definition, + expanded, + entries, + device, + base_dir, + candidate.workflow_dir, + measured_entries=measured_entries, + observed=block, + cached_steps=cached_steps, + total_steps=total_steps, + observed_for_child=observed_for_child, + ) + + result = quote( + _observed_block(observed, arguments, definition, expanded, entries, device) + ) + if result.get("minutes") is None or not _chain_is_checked(definition, expanded): + return result + unchecked = _unchecked_arguments(definition, arguments) + if unchecked is None: + return result + try: + # The unchecked run's own history (a fixed block is this run's, so + # there is none to read), priced at this checked run's worst case + block = None + if callable(observed): + block = _observed_block( + observed, + unchecked, + definition, + candidate.expanded_definition(unchecked), + entries, + device, + ) + floor = quote(block) + except Exception: + logger.debug("No unchecked floor for the checked chain", exc_info=True) + return result + if floor.get("minutes") is None or floor["minutes"] <= result["minutes"]: + return result + note = ( + f"floored at the same chain unchecked at its worst case; this box's " + f"checked history alone quoted {_shown_minutes(result['minutes'])} min" + ) + return { + **floor, + "scaled": "; ".join(part for part in (floor.get("scaled"), note) if part), + } + + +def _chain_is_checked(definition, expanded): + """Whether the workflow's one chain may re-roll or words-check at + `expanded`'s variables - what the worst case adds to its quote.""" + variables = (expanded or {}).get("variables") or {} + words_minutes, _ = words_check_term(definition, variables) + return _chain_retries(definition, variables) > 0 or bool(words_minutes) + + +def _unchecked_arguments(definition, arguments): + """`arguments` with the one chain's `check` off and its `retries` 0, or + None when the chain's `check` is not a variable an argument can turn + off (a literal `check` has no unchecked twin to price).""" + blocks = list(_chain_blocks(definition.get("steps"))) + if len(blocks) != 1: + return None + chain = blocks[0][0] + check = references.ref_name(references.VARIABLE, chain.get("check")) + if check is None: + return None + twin = {**(arguments or {}), check: False} + retries = references.ref_name(references.VARIABLE, chain.get("retries")) + if retries is not None: + twin[retries] = 0 + return twin + + def _observed_block( observed, arguments, definition=None, expanded=None, entries=None, device=None ): diff --git a/tests/test_plan.py b/tests/test_plan.py index 7e4b78805..5f57e922b 100644 --- a/tests/test_plan.py +++ b/tests/test_plan.py @@ -2720,6 +2720,77 @@ def test_a_thin_bucket_with_no_default_history_tempers_toward_curated(self, plan assert "scaled from the curated 13.5 min" in draft["scaled"] +class TestCheckedChainQuotesMoreThanUnchecked: + """#1334 (C-F747): a checked dialogue chain whose thin history tempers + below the curated figure still quotes more than the same chain + unchecked, which has no history and quotes the curated figure.""" + + COMMON = { + "shot": "dialogue", + "segments": 2, + "num_frames": 124, + "seed": 1262, + "prompts": [ + "A man speaks. We the people of the United States.", + "A man speaks. In order to form a more perfect union.", + ], + } + CHECKED = {**COMMON, "retries": 1, "check": {"words_similarity_min": 0.8}} + UNCHECKED = {**COMMON, "retries": 0, "check": False} + + @staticmethod + def history(checked=None, unchecked=None): + def answer(arguments): + return unchecked if arguments.get("check") is False else checked + + return answer + + def quote(self, plan, arguments, history): + return plan(_repo_json(CATALOG_CHAINED), arguments=arguments, observed=history)[ + "estimate" + ] + + def test_a_thin_fast_checked_history_quotes_above_the_unchecked(self, plan): + history = self.history(checked=observed(minutes=5.5, runs=1)) + checked = self.quote(plan, self.CHECKED, history) + unchecked = self.quote(plan, self.UNCHECKED, history) + assert unchecked["minutes"] == pytest.approx(12.3, abs=0.05) + assert checked["minutes"] > unchecked["minutes"] + # Floored at the unchecked chain (curated, no history) at its worst + # case: the curated 13.5 for 2 of 3 segments, 4 renders for 2, plus + # 4 Whisper passes + assert checked["minutes"] == pytest.approx(14.87, abs=0.05) + assert "4 renders for 2" in checked["scaled"] + assert "words check: 4 Whisper pass(es)" in checked["scaled"] + assert "floored at the same chain unchecked" in checked["scaled"] + assert "checked history alone quoted 12.3 min" in checked["scaled"] + + def test_the_floor_reads_the_unchecked_chains_own_history(self, plan): + history = self.history( + checked=observed(minutes=5.5, runs=1), + unchecked=observed(minutes=12.0, runs=5), + ) + checked = self.quote(plan, self.CHECKED, history) + unchecked = self.quote(plan, self.UNCHECKED, history) + assert unchecked["minutes"] == 12.0 + assert checked["minutes"] > unchecked["minutes"] + assert "from the observed 12 min" in checked["scaled"] + + def test_a_checked_history_above_the_floor_stands(self, plan): + history = self.history( + checked=observed(minutes=20.0, runs=5), + unchecked=observed(minutes=6.0, runs=5), + ) + checked = self.quote(plan, self.CHECKED, history) + assert "floored" not in checked["scaled"] + assert "from the observed 20 min" in checked["scaled"] + + def test_an_unchecked_chain_is_not_floored(self, plan): + history = self.history(unchecked=observed(minutes=6.0, runs=1)) + unchecked = self.quote(plan, self.UNCHECKED, history) + assert "floored" not in (unchecked.get("scaled") or "") + + class TestResumedChainEstimate: """A chain resumed from an earlier run's kept segments prices only the segments it renders (chain_resume.kept_count, cost_scaling).""" From bca9735e0458a835e2d86219bf13758deb0369f8 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Fri, 13 Nov 2026 21:40:22 -0600 Subject: [PATCH 004/412] feat(plan): #1334 - a checked chain quotes strictly more than the same chain unchecked The floor is now the unchecked twin's own quote (its own expansion and history, what validating it returns) plus the worst-case extra checking carries (curated checked less curated unchecked), so a checked chain can never quote at or under its unchecked twin. The checked quote's scaled text, naming the re-rolls and the words passes, is kept, with the floor noted after it. A failure to price the twin is now logged as a warning. Co-Authored-By: Claude Opus 5.5 --- dw/plan.py | 71 ++++++++++++++++++++++++++-------------------- tests/test_plan.py | 21 +++++++++++++- 2 files changed, 61 insertions(+), 31 deletions(-) diff --git a/dw/plan.py b/dw/plan.py index b43731aef..6aa603efd 100644 --- a/dw/plan.py +++ b/dw/plan.py @@ -219,25 +219,27 @@ def _checked_estimate( total_steps, observed_for_child, ): - """`estimate` for the run, floored, for a checked chain, at the same - chain unchecked priced at its worst case (#1334). + """`estimate` for the run, floored, for a checked chain, at what the + same chain unchecked quotes plus what checking adds (#1334). A checked chain's history and the same chain's unchecked history are separate buckets (`check` and `retries` are cost drivers). A thin checked bucket from a fast box tempers below the curated figure, while the unchecked shape with no history quotes the curated one at full authority, so a checked chain could quote no more than the same chain - unchecked. The floor is the checked run priced from the *unchecked* - run's own history (`_with_worst_case` adds the re-rolls and the words - passes to it, tempered as usual), or from the curated row when that - shape has none: whatever the unchecked chain would quote, plus the worst - case. The higher of the two is quoted, with `scaled` saying the floor - was taken and what this box's checked history alone said.""" - - def quote(block): + unchecked. The floor is the unchecked twin's own quote - its own + expansion and its own history, exactly what validating it returns - + plus the worst-case extra the check carries (the re-rolls and the words + passes: the curated checked figure less the curated unchecked one). + That extra is positive whenever the chain is checked, so a checked chain + always quotes strictly more than its unchecked twin. The higher of the + checked quote and the floor is quoted, with `scaled` still naming the + checked worst case and saying the floor was taken.""" + + def quote(shape, block): return estimate( definition, - expanded, + shape, entries, device, base_dir, @@ -250,7 +252,8 @@ def quote(block): ) result = quote( - _observed_block(observed, arguments, definition, expanded, entries, device) + expanded, + _observed_block(observed, arguments, definition, expanded, entries, device), ) if result.get("minutes") is None or not _chain_is_checked(definition, expanded): return result @@ -258,31 +261,39 @@ def quote(block): if unchecked is None: return result try: - # The unchecked run's own history (a fixed block is this run's, so - # there is none to read), priced at this checked run's worst case - block = None - if callable(observed): - block = _observed_block( - observed, - unchecked, - definition, - candidate.expanded_definition(unchecked), - entries, - device, + twin_expanded = candidate.expanded_definition(unchecked) + if _chain_is_checked(definition, twin_expanded): + return result + # A fixed block is this run's own history, so the twin has none + twin_block = ( + _observed_block( + observed, unchecked, definition, twin_expanded, entries, device ) - floor = quote(block) + if callable(observed) + else None + ) + twin = quote(twin_expanded, twin_block) + extra = (quote(expanded, None).get("minutes") or 0) - ( + quote(twin_expanded, None).get("minutes") or 0 + ) except Exception: - logger.debug("No unchecked floor for the checked chain", exc_info=True) + logger.warning("No unchecked floor for the checked chain", exc_info=True) + return result + if twin.get("minutes") is None or extra <= 0: return result - if floor.get("minutes") is None or floor["minutes"] <= result["minutes"]: + floor = round(twin["minutes"] + extra, 1) + if floor <= result["minutes"]: return result note = ( - f"floored at the same chain unchecked at its worst case; this box's " - f"checked history alone quoted {_shown_minutes(result['minutes'])} min" + f"floored at the same chain unchecked ({_shown_minutes(twin['minutes'])} " + f"min) plus its worst case ({_shown_minutes(round(extra, 1))} min); this " + f"box's checked history alone quoted {_shown_minutes(result['minutes'])} min" ) return { - **floor, - "scaled": "; ".join(part for part in (floor.get("scaled"), note) if part), + **result, + "minutes": floor, + "cached_minutes": _cached_minutes(floor, cached_steps, total_steps), + "scaled": "; ".join(part for part in (result.get("scaled"), note) if part), } diff --git a/tests/test_plan.py b/tests/test_plan.py index 5f57e922b..5c80bc53e 100644 --- a/tests/test_plan.py +++ b/tests/test_plan.py @@ -2773,8 +2773,27 @@ def test_the_floor_reads_the_unchecked_chains_own_history(self, plan): checked = self.quote(plan, self.CHECKED, history) unchecked = self.quote(plan, self.UNCHECKED, history) assert unchecked["minutes"] == 12.0 + # The twin's own 12 min plus the curated worst-case extra (14.87 - + # 12.33), while the scaled text still names the checked worst case + assert checked["minutes"] == pytest.approx(14.6, abs=0.05) + assert "same chain unchecked (12 min)" in checked["scaled"] + assert "4 renders for 2" in checked["scaled"] + assert "words check: 4 Whisper pass(es)" in checked["scaled"] + + @pytest.mark.parametrize("twin_minutes", [5.5, 7.1, 9.0, 12.0]) + def test_strictly_above_the_twin_whatever_its_history(self, plan, twin_minutes): + # The bounce: with both buckets thin and from a fast box, pricing the + # checked shape on the twin's history could land at or under the + # twin's own quote; the floor is the twin's quote plus the extra + history = self.history( + checked=observed(minutes=5.5, runs=1), + unchecked=observed(minutes=twin_minutes, runs=1), + ) + checked = self.quote(plan, self.CHECKED, history) + unchecked = self.quote(plan, self.UNCHECKED, history) assert checked["minutes"] > unchecked["minutes"] - assert "from the observed 12 min" in checked["scaled"] + assert "4 renders for 2" in checked["scaled"] + assert "words check: 4 Whisper pass(es)" in checked["scaled"] def test_a_checked_history_above_the_floor_stands(self, plan): history = self.history( From a2b56e5aed17a6c47652a966275870982c53aec3 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Sat, 14 Nov 2026 00:39:43 -0600 Subject: [PATCH 005/412] feat(long-form): #1336 - name the multi-passage recipe and expose boundary_slack_seconds One narration-long track retimed once, cut into passages with slice_audio, one narrated take per passage on its own still, joined by an authored concat_videos step at trim_frames 0 and match_levels lufs. Stated in run-and-repair.md, pointed to from SKILL.md, levers.md, audio.md, the workflow guide and narrated-take's description. narration-retime now carries boundary_slack_seconds to retime_narration. Co-Authored-By: Claude Opus 5.5 --- docs/WORKFLOW_GUIDE.md | 24 +++++- plugins/dw/skills/long-form/SKILL.md | 3 +- .../dw/skills/long-form/references/audio.md | 6 ++ .../dw/skills/long-form/references/levers.md | 5 +- .../long-form/references/run-and-repair.md | 31 ++++++- tests/test_catalog_structure.py | 3 + tests/test_narration_retime_template.py | 85 +++++++++++++++++++ tests/test_plugin_skills.py | 34 ++++++++ .../templates/minimax/narrated-take.json | 2 +- workflows/templates/narration-retime.json | 6 +- 10 files changed, 186 insertions(+), 13 deletions(-) create mode 100644 tests/test_narration_retime_template.py diff --git a/docs/WORKFLOW_GUIDE.md b/docs/WORKFLOW_GUIDE.md index 359aaa454..e0fc014e1 100644 --- a/docs/WORKFLOW_GUIDE.md +++ b/docs/WORKFLOW_GUIDE.md @@ -2995,10 +2995,26 @@ eye called was 0.146 at 36 s on `dialogue`. measured past 86 s. `experimental_latent_carry` with `experimental_capstone` and the latent keystone (`anchor_every`) stay experimental. -A piece longer than one clean take is split into passages, one narrated take per -passage (its own `narration-retime`, its own opening still or angle), joined as -cuts. That composition is not yet run end to end. The design is -`docs/proposals/complete/narrated-long-take-complete.md`. +A piece longer than one clean take is passages joined as cuts, one narrated take +per passage. That composition is not yet run end to end. The recipe: + +1. **One narration for the whole script**: `templates/narration-long` from one + voice reference, retimed once with `templates/narration-retime`. One track + keeps one voice, room tone and level across the cuts. +2. **Passages** split at paragraph or section breaks to fit the preset: about + 60 words for `dialogue` (about 30 s), about 175 for `standing` (about 85 s), + at the retimed pace of about 126 words a minute. Cut the retimed track in + the middle of those section-break pauses with `slice_audio`, and + `keep_output` each slice. +3. **One `templates/minimax/narrated-take` per passage**, with its slice, its + text and a different still or angle; a cut to the same still reads as a + reset. +4. **Join** with an authored one-step `concat_videos` workflow: the takes as + `output:` references, `trim_frames: 0` (a hard cut), `match_levels: "lufs"` + (off by default). Every take must be the same frame size. Then + `export_timeline` if an editor is wanted. + +The design is `docs/proposals/complete/narrated-long-take-complete.md`. ## Schedulers diff --git a/plugins/dw/skills/long-form/SKILL.md b/plugins/dw/skills/long-form/SKILL.md index 791bcbbd3..304b7c3db 100644 --- a/plugins/dw/skills/long-form/SKILL.md +++ b/plugins/dw/skills/long-form/SKILL.md @@ -84,7 +84,8 @@ Set `shot` on `templates/minimax/chained-segments` from the shot's `shot: standing` (no keyframes) holds to about 85 s (seed 1 only); choose `standing` unless the user supplies keyframes; `walk_keyframed` needs a hand-built keyframe per segment. Longer than a - take is passages joined as cuts, one take each: not yet run end to end + take is passages joined as cuts: one `narration-long` track, + `slice_audio`, a take each, `concat_videos`; not yet run end to end (`bench/records/narrated.md`). Procedure: `references/run-and-repair.md`, *A narrated take*. diff --git a/plugins/dw/skills/long-form/references/audio.md b/plugins/dw/skills/long-form/references/audio.md index 809b72d76..8fea2e2b7 100644 --- a/plugins/dw/skills/long-form/references/audio.md +++ b/plugins/dw/skills/long-form/references/audio.md @@ -154,3 +154,9 @@ boundary cuts through a word, and checks the result against the script. The report's `mid_word_boundaries` is advisory: a few are fine, since the narration is held and a cut inside a word is heard unbroken (it only splits that word between two segments' lines); if many appear, raise `boundary_slack_seconds`. + +For a piece of several narrated passages, make and retime **one** narration for +the whole script and cut it into passages with `slice_audio`, rather than a +narration per passage: one track keeps one voice, room tone and level across +the cuts, and `concat_videos`' `match_levels: "lufs"` evens what is left +(`run-and-repair.md`, *A narrated take*). diff --git a/plugins/dw/skills/long-form/references/levers.md b/plugins/dw/skills/long-form/references/levers.md index 54783f8c7..668ad9c66 100644 --- a/plugins/dw/skills/long-form/references/levers.md +++ b/plugins/dw/skills/long-form/references/levers.md @@ -118,7 +118,10 @@ motion together at 86 s, and nothing is measured past 86 s. - **Kandinsky S2V 1.0 Lite distilled** (86 s spike): failed on identity, the face drifting to a different, darker one by 85 s. - **Passages joined as cuts**: the released shape for a piece longer than one - clean take. Not yet run end to end. + clean take: one narration for the whole script (`templates/narration-long`, + retimed once), cut into passages with `slice_audio`, one take per passage, + joined by `concat_videos` at `trim_frames: 0`, `match_levels: "lufs"` + (`run-and-repair.md`, *A narrated take*). Not yet run end to end. ## Measured and cut: do not re-propose diff --git a/plugins/dw/skills/long-form/references/run-and-repair.md b/plugins/dw/skills/long-form/references/run-and-repair.md index 391379947..f35ebdd9d 100644 --- a/plugins/dw/skills/long-form/references/run-and-repair.md +++ b/plugins/dw/skills/long-form/references/run-and-repair.md @@ -194,10 +194,33 @@ seed 1; about 18-19 min per segment on dialogue and walk_keyframed; standing too that drifted on its own is not repaired this way: `templates/minimax/face-repair` had no reference to aim at and was dropped. -Longer than one clean take: split the script into passages, make one narrated -take per passage (its own `narration-retime`, its own opening still or angle), -and join them as cuts with the tools named above. Not yet run end to end. -Nothing is measured past 86 s. +### Longer than one take: passages joined as cuts + +A piece longer than one clean take is passages joined as cuts, one narrated +take each. Not yet run end to end; nothing is measured past 86 s. + +1. **One narration for the whole script.** Speak it once with + `templates/narration-long` from one voice reference (`audio.md`), then + retime it once with `templates/narration-retime`. One track gives one + voice, one room tone and one level across every cut; a narration made per + passage gives none of those. +2. **Passages.** Split the script at paragraph or section breaks so each + passage fits its preset. At the retimed pace (about 126 words a minute, + `bench/records/narrated.md`) that is about 60 words for `shot: dialogue` + (about 30 s) and about 175 words for `shot: standing` (about 85 s). Cut + the retimed track at those section-break pauses with `slice_audio` + (`start_seconds`/`duration_seconds`, the cut in the middle of the pause; + the retime report's `words` give the times), and `keep_output` each slice. + A slice's segment boundaries restart at its cut, so its + `mid_word_boundaries` are not the whole track's: they stay advisory. +3. **Takes.** Run one `templates/minimax/narrated-take` per passage: that + passage's slice as `narration`, that passage's text as `script`, and **a + different still or angle** for each. A cut to the same still reads as a + reset. Probe passage 1 first, as above. +4. **Join.** Author a one-step `concat_videos` workflow: the takes as + `output:` refs in order, `trim_frames: 0` (a hard cut), `match_levels: + "lufs"` (off by default), `fps: 24`. Every take must be the same frame + size. Then `export_timeline` (below) if an editor is wanted. ## Export the cut for an editor diff --git a/tests/test_catalog_structure.py b/tests/test_catalog_structure.py index af41e623f..9b3e8766d 100644 --- a/tests/test_catalog_structure.py +++ b/tests/test_catalog_structure.py @@ -607,6 +607,9 @@ def test_no_stale_entry_in_the_allowlist(): # Then to 14_450 (measured 14_425) for `minimax/narrated-take`: one new entry, # the catalog's only long take held to a retimed narration, with no cost # block until a per-segment figure is measured. +# Re-measured at 14_449.75 after `narration-retime` gained the +# `boundary_slack_seconds` variable its own description advises raising +# (#1311, stage #1336), so the budget stands, with no headroom left. COMPACT_BUDGET = 14_450 FILTERED_BUDGET = 1_500 diff --git a/tests/test_narration_retime_template.py b/tests/test_narration_retime_template.py new file mode 100644 index 000000000..218307a4d --- /dev/null +++ b/tests/test_narration_retime_template.py @@ -0,0 +1,85 @@ +"""templates/narration-retime exposes `boundary_slack_seconds` (#1311, stage +#1336): the template description, audio.md and TASKS.md all advise raising it +when many `mid_word_boundaries` appear, so the template must carry it to the +`retime_narration` task, and refuse a value the task would refuse.""" + +import json +from pathlib import Path + +import pytest + +from dw.validation import workflow_errors +from dw.variables import replace_variables, resolve_variable_values +from dw.workflow import workflow_from_definition + +TEMPLATE = ( + Path(__file__).resolve().parent.parent / "workflows/templates/narration-retime.json" +) +SCRIPT = "We the People of the United States, in Order to form a more perfect Union." + + +def load(): + return json.loads(TEMPLATE.read_text()) + + +def retime_arguments(variables): + definition = load() + merged = resolve_variable_values({**definition["variables"], **variables}) + substituted = replace_variables(definition, merged) + steps = {s["name"]: s for s in substituted["steps"]} + return steps["retime"]["task"]["arguments"] + + +def messages(tmp_path, arguments): + workflow = workflow_from_definition(load(), str(tmp_path)) + return [str(e.get("message")) for e in workflow_errors(workflow, arguments)] + + +def test_the_variable_defaults_to_the_tasks_own_default(): + import inspect + + from dw.tasks.narration_retime import retime_narration + + default = inspect.signature(retime_narration).parameters["boundary_slack_seconds"] + assert load()["variables"]["boundary_slack_seconds"] == default.default + + +def test_boundary_slack_seconds_reaches_the_retime_task(): + assert retime_arguments({})["boundary_slack_seconds"] == 0.25 + assert retime_arguments({"boundary_slack_seconds": 0.6})[ + "boundary_slack_seconds" + ] == pytest.approx(0.6) + + +def test_the_registered_handler_passes_it_to_the_implementation(monkeypatch): + """The real dispatch path: the substituted step arguments go through the + registered `retime_narration` handler into the implementation.""" + import dw.tasks # noqa: F401 (registers the commands) + from dw.tasks import narration_retime + from dw.tasks.registry import _COMMAND_REGISTRY + + seen = {} + + def capture(**kwargs): + seen.update(kwargs) + return {} + + monkeypatch.setattr(narration_retime, "retime_narration", capture) + + class Task: + def device_for(self, arguments): + return "cpu" + + arguments = retime_arguments({"script": SCRIPT, "boundary_slack_seconds": 0.5}) + _COMMAND_REGISTRY["retime_narration"](Task(), dict(arguments), {}) + assert seen["boundary_slack_seconds"] == pytest.approx(0.5) + + +def test_a_valid_value_validates(tmp_path): + assert messages(tmp_path, {"script": SCRIPT, "boundary_slack_seconds": 0.5}) == [] + + +@pytest.mark.parametrize("value", [-0.1, "wide"]) +def test_an_invalid_value_is_refused_at_validate(tmp_path, value): + found = messages(tmp_path, {"script": SCRIPT, "boundary_slack_seconds": value}) + assert any("boundary_slack_seconds" in m for m in found), found diff --git a/tests/test_plugin_skills.py b/tests/test_plugin_skills.py index 66764ec17..a7e8406ee 100644 --- a/tests/test_plugin_skills.py +++ b/tests/test_plugin_skills.py @@ -1939,6 +1939,40 @@ def test_the_narrated_take_rule_cites_its_record_and_presets(self): body = _flat(_read(os.path.join(LONG_FORM_DIR, "references", name))) assert "bench/records/narrated.md" in body, name + def test_the_passage_procedure_names_its_tools(self): + """#1311 stage #1336: the multi-passage procedure names its narration, + its cut and its join, where it once said "the tools named above" and + named none: one `narration-long` track, `slice_audio` passages, a + `concat_videos` join at `trim_frames: 0` with `match_levels`.""" + body = _read(os.path.join(LONG_FORM_DIR, "references", "run-and-repair.md")) + start = body.index("### Longer than one take: passages joined as cuts") + end = body.index("\n## ", start) + procedure = _flat(body[start:end]) + for name in ( + "`templates/narration-long`", + "`templates/narration-retime`", + "`slice_audio`", + "`keep_output`", + "`templates/minimax/narrated-take`", + "different still or angle", + "`concat_videos`", + "`trim_frames: 0`", + '`match_levels: "lufs"`', + "`output:`", + "Not yet run end to end", + ): + assert name in procedure, name + assert "tools named above" not in body + for name in ("levers.md", "audio.md"): + other = _flat(_read(os.path.join(LONG_FORM_DIR, "references", name))) + for tool in ("narration-long", "slice_audio", "concat_videos"): + assert tool in other, (name, tool) + guide = _read(os.path.join(REPO_ROOT, "docs", "WORKFLOW_GUIDE.md")) + start = guide.index("### A narrated long take") + section = _flat(guide[start : guide.index("\n## ", start)]) + for name in ("`concat_videos`", "`trim_frames: 0`", "`match_levels"): + assert name in section, name + def test_the_move_class_comes_from_the_vocabulary(self): """#1255: the "until #1200" stand-in is replaced by a pointer to the cinematography vocabulary's `class` column, in both files.""" diff --git a/workflows/templates/minimax/narrated-take.json b/workflows/templates/minimax/narrated-take.json index f21426ef7..0b104c71e 100644 --- a/workflows/templates/minimax/narrated-take.json +++ b/workflows/templates/minimax/narrated-take.json @@ -1,7 +1,7 @@ { "id": "MiniMaxH3NarratedTake", "shape": "sequence", - "description": "A long H3 take of one speaker held to a retimed narration, a segment per line, probed then continued. The narration is made first with templates/narration-retime, whose 'num_frames' and 'guide_frames' must equal this template's (192 and 22 by default), or the segment boundaries land in the wrong places; listen to the retimed track before spending GPU time on it, and pass it as 'narration' and the same text as 'script'. The first step (narration_lines) cuts the narration at the chain's own segment boundaries and fills 'prompt_template' once per segment with that segment's line and 'scene', 'speaker' and 'soundscape', so the plan derives the segment count from the narration's length; the 'take' step is a guide chain matched to the narration and holding it as the soundtrack, so the speech heard is the narration itself and the guide carries picture only. 'prompt_template' takes bare placeholders ({line}, {scene}, {speaker}, {soundscape}); write a literal brace doubled. Its default has no spoken cue and no breath: the held narration already starts each segment mid-sentence. What it holds, measured (bench/records/narrated.md, 12 segments of about 86 s at tier best): the narration is held unbroken under every 'shot'. 'shot' 'dialogue' (the default) etches the face by about 30 s and steps face_drop up at segment 6 (36 s), so it suits a take of about 30 s (4 segments). 'shot' 'standing' holds face and backdrop to about 85 s with face_drop within 0.015 (seed 1 only), with no keyframes: she stands, and each segment eases back to the opening frame. 'shot' 'walk_keyframed' holds the face to 85 s (face_drop at most 0.041 on two seeds) and moves, at the price of a hand-built keyframe per segment. Nothing is measured past 86 s, and no 'shot' cleared face, lip sync and motion together at 86 s. A piece longer than one clean take is split into passages, one narrated take per passage with its own narration-retime and its own opening still, joined as cuts (not yet run end to end). Wall time measured: about 18-19 min per segment on dialogue and walk_keyframed; standing took 282 min for 12 segments (about 23.5, with two re-rolls), at tier best on an RTX 3090. The procedure: first validate with 'stop_after' set for a probe, k = (the seconds the 'shot' holds) / ((num_frames - guide_frames) / 24): 4 for 'dialogue', up to 12 for 'standing' (a whole number; the estimate prices only the k segments it renders). Run the probe and judge its segments with get_output_frames and compare_outputs, and read each shot's check values (face_drop is recorded, never failed, since 'check' leaves its ceiling null). If the probe holds, run again with 'resume_from' set to the output: reference of the probe's last kept segment file and 'stop_after' cleared to null, which renders only the segments after it; a bad segment is re-rendered in place with templates/minimax/repair-segment ('keep_segments' stays true for that). Judge lip sync by eye on the finished take, or with the measure_lip_sync task; the chain's check does not measure it, and it holds no words check, since the held audio is the narration itself. 'shot' has three presets: 'dialogue' (guide continuity, the default), 'standing' (guide continuity with keystone 'segment_1' at keystone_slot 'last' and no keyframes) and 'walk_keyframed' (the same keystone with keyframes), the moving keystone: pass 'keyframes', a list of stills one per segment (or one previous_result: list of them), and segment k ends on keyframe k as its last image, so the camera moves and the face holds (docs/proposals/complete/narrated-long-take-complete.md, Amendment 1). Each keyframe needs an open, mid-word mouth, since a closed-mouth keyframe drops lip sync at the segment's end, and a keyframe face that differs from the still is followed and accumulates; a walk did not read at chest-up framing and a slow lateral camera arc did. Draw the keyframes from the speaker still (FLUX 3 Klein edit) and review them before any video is rendered: an inconsistent series shows as a pulse at every segment end. 'keyframes' (default null, off) needs 'shot' 'walk_keyframed' (or keystone 'segment_1' with keystone_slot 'last') and at least one keyframe per planned segment, the full take's even for a probe; it is refused otherwise. 'tier' 'best' (the default) is 1344x768 on int8 weights and 'standard' 960x544 on int4, both at 20 steps with no turbo LoRA ('lora_model_name' null), since the turbo LoRA flattens H3 voices and lip sync. Keep 'num_frames' on H3's 3-frame audio grid (141, 192, 243, 294, 345) or validate warns that the held slices drift. No cost row: the figure above is wall time at one tier, not a calibrated row.", + "description": "A long H3 take of one speaker held to a retimed narration, a segment per line, probed then continued. The narration is made first with templates/narration-retime, whose 'num_frames' and 'guide_frames' must equal this template's (192 and 22 by default), or the segment boundaries land in the wrong places; listen to the retimed track before spending GPU time on it, and pass it as 'narration' and the same text as 'script'. The first step (narration_lines) cuts the narration at the chain's own segment boundaries and fills 'prompt_template' once per segment with that segment's line and 'scene', 'speaker' and 'soundscape', so the plan derives the segment count from the narration's length; the 'take' step is a guide chain matched to the narration and holding it as the soundtrack, so the speech heard is the narration itself and the guide carries picture only. 'prompt_template' takes bare placeholders ({line}, {scene}, {speaker}, {soundscape}); write a literal brace doubled. Its default has no spoken cue and no breath: the held narration already starts each segment mid-sentence. What it holds, measured (bench/records/narrated.md, 12 segments of about 86 s at tier best): the narration is held unbroken under every 'shot'. 'shot' 'dialogue' (the default) etches the face by about 30 s and steps face_drop up at segment 6 (36 s), so it suits a take of about 30 s (4 segments). 'shot' 'standing' holds face and backdrop to about 85 s with face_drop within 0.015 (seed 1 only), with no keyframes: she stands, and each segment eases back to the opening frame. 'shot' 'walk_keyframed' holds the face to 85 s (face_drop at most 0.041 on two seeds) and moves, at the price of a hand-built keyframe per segment. Nothing is measured past 86 s, and no 'shot' cleared face, lip sync and motion together at 86 s. A piece longer than one clean take is passages joined as cuts (not yet run end to end): one narration-long track for the whole script retimed once, cut at section breaks with slice_audio, one take per passage with its own still or angle, joined by a concat_videos step at trim_frames 0 and match_levels lufs (the workflow guide's A narrated long take). Wall time measured: about 18-19 min per segment on dialogue and walk_keyframed; standing took 282 min for 12 segments (about 23.5, with two re-rolls), at tier best on an RTX 3090. The procedure: first validate with 'stop_after' set for a probe, k = (the seconds the 'shot' holds) / ((num_frames - guide_frames) / 24): 4 for 'dialogue', up to 12 for 'standing' (a whole number; the estimate prices only the k segments it renders). Run the probe and judge its segments with get_output_frames and compare_outputs, and read each shot's check values (face_drop is recorded, never failed, since 'check' leaves its ceiling null). If the probe holds, run again with 'resume_from' set to the output: reference of the probe's last kept segment file and 'stop_after' cleared to null, which renders only the segments after it; a bad segment is re-rendered in place with templates/minimax/repair-segment ('keep_segments' stays true for that). Judge lip sync by eye on the finished take, or with the measure_lip_sync task; the chain's check does not measure it, and it holds no words check, since the held audio is the narration itself. 'shot' has three presets: 'dialogue' (guide continuity, the default), 'standing' (guide continuity with keystone 'segment_1' at keystone_slot 'last' and no keyframes) and 'walk_keyframed' (the same keystone with keyframes), the moving keystone: pass 'keyframes', a list of stills one per segment (or one previous_result: list of them), and segment k ends on keyframe k as its last image, so the camera moves and the face holds (docs/proposals/complete/narrated-long-take-complete.md, Amendment 1). Each keyframe needs an open, mid-word mouth, since a closed-mouth keyframe drops lip sync at the segment's end, and a keyframe face that differs from the still is followed and accumulates; a walk did not read at chest-up framing and a slow lateral camera arc did. Draw the keyframes from the speaker still (FLUX 3 Klein edit) and review them before any video is rendered: an inconsistent series shows as a pulse at every segment end. 'keyframes' (default null, off) needs 'shot' 'walk_keyframed' (or keystone 'segment_1' with keystone_slot 'last') and at least one keyframe per planned segment, the full take's even for a probe; it is refused otherwise. 'tier' 'best' (the default) is 1344x768 on int8 weights and 'standard' 960x544 on int4, both at 20 steps with no turbo LoRA ('lora_model_name' null), since the turbo LoRA flattens H3 voices and lip sync. Keep 'num_frames' on H3's 3-frame audio grid (141, 192, 243, 294, 345) or validate warns that the held slices drift. No cost row: the figure above is wall time at one tier, not a calibrated row.", "vram_estimate": { "base_gb": 16.3, "bytes_per_voxel": 28.71, diff --git a/workflows/templates/narration-retime.json b/workflows/templates/narration-retime.json index d50a574f7..8d4d2f2f4 100644 --- a/workflows/templates/narration-retime.json +++ b/workflows/templates/narration-retime.json @@ -8,7 +8,8 @@ "sentence_seconds": 0.6, "section_seconds": 1.0, "num_frames": 192, - "guide_frames": 22 + "guide_frames": 22, + "boundary_slack_seconds": 0.25 }, "variable_constraints": { "script": { @@ -29,7 +30,8 @@ "sentence_seconds": "variable:sentence_seconds", "section_seconds": "variable:section_seconds", "segment_frames": "variable:num_frames", - "guide_frames": "variable:guide_frames" + "guide_frames": "variable:guide_frames", + "boundary_slack_seconds": "variable:boundary_slack_seconds" } }, "result": { From 6316cc98760a6bd8ea233e638b8c7cd1da812f78 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Sat, 14 Nov 2026 01:01:32 -0600 Subject: [PATCH 006/412] fix(variables): #1354 - refuse a boolean for a float variable Co-Authored-By: Claude Sonnet 5.5 --- dw/variables.py | 12 ++++++++++++ tests/test_variables.py | 13 +++++++++++++ 2 files changed, 25 insertions(+) diff --git a/dw/variables.py b/dw/variables.py index dae1ae424..dd2266794 100644 --- a/dw/variables.py +++ b/dw/variables.py @@ -402,6 +402,18 @@ def get_value(v, desired_type, name=None): logger.error(message) raise ValueError(message) + # A JSON boolean for a variable typed float by its default would be taken + # as 1.0/0.0 through float(True) with no word (#1354): refuse it + if desired_type is float and isinstance(v, bool): + var_label = name if name is not None else "" + message = ( + f"Cannot convert variable '{var_label}' value {v!r} to type float: " + f"this variable is typed float by its default and takes a number, " + f"not true or false" + ) + logger.error(message) + raise ValueError(message) + # A string cannot be coerced into a dict or a None - dict('/a/b.png') is # nonsense, NoneType('x') a TypeError. Those defaults are how media # variables ({'location': ...}) and optional inputs (null) are declared, diff --git a/tests/test_variables.py b/tests/test_variables.py index 3a409623a..16c416d9f 100644 --- a/tests/test_variables.py +++ b/tests/test_variables.py @@ -364,6 +364,19 @@ def test_argument_errors_reports_a_dict_passed_for_a_string_variable(): assert "takes a plain string" in errors[0]["message"] +def test_argument_errors_refuses_a_boolean_for_a_float_variable(): + """float(True) is 1.0: a JSON boolean for a float default was accepted + silently (#1354). A number, and a numeric string, still pass.""" + definition = {"variables": {"comma_seconds": 0.3}} + + errors = argument_errors(definition, {"comma_seconds": True}) + assert [error["path"] for error in errors] == ["arguments.comma_seconds"] + assert "to type float" in errors[0]["message"] + assert argument_errors(definition, {"comma_seconds": False}) + assert argument_errors(definition, {"comma_seconds": 0.5}) == [] + assert argument_errors(definition, {"comma_seconds": "0.5"}) == [] + + class TestResolveVariableValues: """A list-valued variable's entries may name other variables - a shot entry says "from_file": "variable:character_a_voice" and one variable From 56b2749bf3ae56015d59fd2311b00e1e8ca18c82 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Sat, 14 Nov 2026 01:27:57 -0600 Subject: [PATCH 007/412] feat(pipeline): #1340 - ready for diffusers 0.43 on 0.42 - A modular pipeline call drops its top-level None arguments, so a block's default applies under 0.43 too; classic pipelines and nested None untouched (pipeline.py main call, h3_tiles text path). - Unfinished MagCache calibration is read before the state manager's reset, so 0.43's in-call reset no longer drops it (#927). - The attention-backend save/restore runs only while _AttentionBackendRegistry._active_backend exists. - available_attention_backends drops a backend diffusers' requirement check reports unusable. Co-Authored-By: Claude Opus 5.5 --- docs/ACCELERATION.md | 1 + dw/acceleration_warnings.py | 38 ++++++- dw/pipeline_processors/components.py | 14 ++- dw/pipeline_processors/h3_tiles.py | 9 +- dw/pipeline_processors/mag_calibration.py | 95 +++++++++++++---- dw/pipeline_processors/modular_arguments.py | 44 ++++++++ dw/pipeline_processors/pipeline.py | 12 ++- tests/test_cache_blocks.py | 59 +++++++++++ tests/test_modular_arguments.py | 110 ++++++++++++++++++++ tests/test_sparse_attention_backends.py | 38 ++++++- 10 files changed, 390 insertions(+), 30 deletions(-) create mode 100644 dw/pipeline_processors/modular_arguments.py create mode 100644 tests/test_modular_arguments.py diff --git a/docs/ACCELERATION.md b/docs/ACCELERATION.md index 6548f564a..ab7493e16 100644 --- a/docs/ACCELERATION.md +++ b/docs/ACCELERATION.md @@ -157,6 +157,7 @@ Values are diffusers' `AttentionBackendName` enum, plus dw's [`sparse`](#sparse- - diffusers refuses a Hub kernel from a publisher it does not list as trusted - `sage_hub` among them (SageAttention 2 from `SageAttention/sage-attention`) - until `DIFFUSERS_TRUST_REMOTE_KERNELS=true` is set in the server's environment (`.env`). That allows remote code from any such publisher. - The local `sage` backend needs `sageattention>=2.1.1`, which PyPI does not carry. - The flash, flash-3, sage and xformers families need CUDA, `_hub` variants included. On a server whose device is not CUDA, `validate_workflow` warns `attention_backend_unavailable`, naming the backend and the device: the job would fail at load. A `native`-family backend never warns, and a backend diffusers adds later draws no warning until dw's list (`CUDA_ONLY_ATTENTION_BACKENDS`) is updated. +- The backends the server offers (`/api/health`'s `attention_backends`, the web UI's menu) follow diffusers' own requirement check: a backend whose package is missing here, or older than the installed diffusers needs, is left out (#1315). diffusers 0.43 raised several of those minimums, so an upgrade can shorten the list until the package is updated. dw states none of the minimums itself; they move with diffusers. On an RTX 3090 `sage_hub` measured about 30% faster per MiniMax-H3 step than `native` (13.8 s against 19.2 s at 960x544x124, 54.7 s against 81.2 s at 345 frames). LTX-2.5 cannot use sage: its transformer passes an attention mask, which sage refuses ("`attn_mask` is not supported for sage attention", measured 2026-10-10), so the LTX templates expose no backend. diff --git a/dw/acceleration_warnings.py b/dw/acceleration_warnings.py index 915f4d598..e88305fcb 100644 --- a/dw/acceleration_warnings.py +++ b/dw/acceleration_warnings.py @@ -293,12 +293,14 @@ def available_attention_backends(device_type: str) -> list[str]: `native` first, then the other `native`-family names; on CUDA, `sparse` (only where the compiled kernels loaded) and the CUDA-only names. A name - diffusers' `AttentionBackendName` lacks is dropped, so the menu never - offers one the pipeline would refuse. + diffusers' `AttentionBackendName` lacks is dropped, and so is one diffusers' + own requirement check reports unusable here (a missing package, or one + older than that diffusers needs), so the menu never offers one the pipeline + would refuse. """ from diffusers.models.attention_dispatch import AttentionBackendName - known = {backend.value for backend in AttentionBackendName} + known = {backend.value: backend for backend in AttentionBackendName} cuda = device_type == "cuda" names = ["native", "_native_flash", "_native_efficient", "_native_math"] if cuda: @@ -308,4 +310,32 @@ def available_attention_backends(device_type: str) -> list[str]: if sparse_attention._kernels_importable(): names.append(SPARSE_BACKEND) names.extend(sorted(CUDA_ONLY_ATTENTION_BACKENDS)) - return [name for name in names if name == SPARSE_BACKEND or name in known] + return [ + name + for name in names + if name == SPARSE_BACKEND + or (name in known and attention_backend_usable(known[name])) + ] + + +def attention_backend_usable(backend) -> bool: + """Whether diffusers itself would accept `backend` (an + `AttentionBackendName`) on this install. + + diffusers raises from its requirement check when a backend's package is + missing or older than it needs, and only that check knows its minimums - + they move with the diffusers release (0.43 refuses too-old packages), so + dw restates none of them. The check is private to diffusers and has no + public equivalent: a diffusers without it filters nothing, as before. + """ + try: + from diffusers.models.attention_dispatch import ( + _check_attention_backend_requirements as check, + ) + except ImportError: + return True + try: + check(backend) + except (RuntimeError, ImportError, ValueError): + return False + return True diff --git a/dw/pipeline_processors/components.py b/dw/pipeline_processors/components.py index b14c698b6..558bb3c6d 100644 --- a/dw/pipeline_processors/components.py +++ b/dw/pipeline_processors/components.py @@ -23,9 +23,9 @@ from huggingface_hub.errors import HfHubHTTPError from .timing import counting_forwards, report_cache_stats from .mag_calibration import ( # noqa: F401 - re-exported for pipeline.py - _report_unfinished_mag_calibration, captured_mag_calibration, get_cache_transformer, + watching_unfinished_mag_calibration, ) from .h3_anchor import insert_latent_anchor from .h3_guides import insert_guides, insert_keystone_restore @@ -195,9 +195,15 @@ def set_component_attention_backend(component, backend): and models sage cannot serve (Music3's head_dim-256 audio decoder, LTX's attention mask) crash. Restoring the active backend keeps the pin on the component it was asked for; its processors pass their own backend explicitly. + + The restore reads a private registry attribute, so it runs only while that + attribute exists (#1315): a diffusers that renamed it just pins the backend. """ from diffusers.models.attention_dispatch import _AttentionBackendRegistry + if not hasattr(_AttentionBackendRegistry, "_active_backend"): + component.set_attention_backend(backend) + return active_backend = _AttentionBackendRegistry._active_backend try: component.set_attention_backend(backend) @@ -970,16 +976,20 @@ def stateful_cache_context(pipeline, segment=None): logger.debug(f"Entering cache context for {transformer.__class__.__name__}") counter, stop_counting = counting_forwards(transformer) + report_calibration, stop_watching = watching_unfinished_mag_calibration(transformer) try: with transformer.cache_context(_CACHE_CONTEXT_NAME): yield # Only a call that completed has ratios worth pasting - _report_unfinished_mag_calibration(transformer) + report_calibration() finally: try: + # The counter's own tallies, taken per forward: a hook state the + # call has already reset (diffusers 0.43) is never read here report_cache_stats(counter, segment) finally: stop_counting() + stop_watching() # Private, but it is what diffusers' own pipelines call and there is no # public equivalent. Also clears the context an errored call left set transformer._reset_stateful_cache() diff --git a/dw/pipeline_processors/h3_tiles.py b/dw/pipeline_processors/h3_tiles.py index 1dff373bd..40b2f13ab 100644 --- a/dw/pipeline_processors/h3_tiles.py +++ b/dw/pipeline_processors/h3_tiles.py @@ -54,6 +54,7 @@ REFINE_TILES_INPUT, tile_plan, ) +from .modular_arguments import without_none from .progress import decoded_later, reported_blocks TEXT_BLOCK = "text_encoder" @@ -322,7 +323,11 @@ def run_tiled_refine(pipeline, arguments, label, decode=None): f"block to leave out, and {type(pipeline).__name__} has none" ) settings = arguments[REFINE_TILES_INPUT] - arguments = {k: v for k, v in arguments.items() if k != REFINE_TILES_INPUT} + # Every call below is modular: a None argument is absent, not None (the + # None rule, dw/pipeline_processors/modular_arguments.py) + arguments = without_none( + {k: v for k, v in arguments.items() if k != REFINE_TILES_INPUT} + ) latents = arguments["latents"] canvas_width = latents.shape[-1] * LATENT_SCALE canvas_height = latents.shape[-2] * LATENT_SCALE @@ -347,7 +352,7 @@ def run_tiled_refine(pipeline, arguments, label, decode=None): # What the tiles take instead of the prompt itself kept = _input_names(tile_blocks) arguments = {k: v for k, v in arguments.items() if k not in takes or k in kept} - arguments.update(encoded) + arguments = without_none({**arguments, **encoded}) with swapped_blocks(pipeline, tile_blocks), decoded_later(): tiles, held = _refine_tiles(pipeline, arguments, plan, noise, label) diff --git a/dw/pipeline_processors/mag_calibration.py b/dw/pipeline_processors/mag_calibration.py index e5a6080bd..53694f313 100644 --- a/dw/pipeline_processors/mag_calibration.py +++ b/dw/pipeline_processors/mag_calibration.py @@ -2,9 +2,10 @@ `get_cache_transformer` names the component a cache hook attaches to, and `captured_mag_calibration` turns diffusers' end-of-run calibration log record -into job events (#891), `_report_unfinished_mag_calibration` the ratios a call -that ran fewer forwards than its schedule left behind (#927). Imported by -dw/pipeline_processors/components.py, which re-exports the two public names for +into job events (#891), and `watching_unfinished_mag_calibration` the ratios a +call that ran fewer forwards than its schedule left behind (#927), taken before +the call's reset drops them. Imported by +dw/pipeline_processors/components.py, which re-exports the public names for dw/pipeline_processors/pipeline.py, and never imports it back. """ @@ -91,28 +92,84 @@ def _report_mag_ratios(ratios, context): emit_warning(text) -def _report_unfinished_mag_calibration(transformer): - """Report the ratios a calibrating call left in its mag state (#927). - - diffusers logs a calibration only when its step counter reaches the - config's num_inference_steps, and a scheduler can run fewer forwards than - that: MiniMax-H3's turns N sigmas into N - 1 evaluations. Such a call ends - with its ratios still in the state, which the call's reset then drops. A - call that did finish has nothing left here - diffusers clears the list - when it logs - so nothing is reported twice. - """ - if not getattr(getattr(transformer, "_cache_config", None), "calibrate", False): - return +def _tail_state_manager(transformer): + """The StateManager of the transformer's tail mag hook, which holds the + calibration ratios, or None.""" from diffusers.hooks.mag_cache import MagCacheBlockHook for module in transformer.modules(): registry = getattr(module, "_diffusers_hook", None) for hook in getattr(registry, "hooks", {}).values(): if isinstance(hook, MagCacheBlockHook) and hook.is_tail: - for name, state in hook.state_manager._state_cache.items(): - if state.calibration_ratios: - _report_mag_ratios(list(state.calibration_ratios), name) - return + return getattr(hook, "state_manager", None) + return None + + +class _UnfinishedCalibration: + """The ratios a calibrating call left unfinished, read while they exist. + + diffusers logs a calibration only when its step counter reaches the + config's num_inference_steps, and a scheduler can run fewer forwards than + that: MiniMax-H3's turns N sigmas into N - 1 evaluations. Such a call ends + with its ratios still in the mag state. + + When that state is dropped changed with diffusers 0.43 (#1315). 0.42 kept it + until dw's own reset after the call, and 0.43's ModularPipeline resets every + component's cache hooks in its own `finally`, before the call returns. So the + ratios are taken in the state manager's `reset`, just before either reset + clears them, and once more after the call for a state no reset has reached. + A call that did finish has nothing left - diffusers clears the list when it + logs - so nothing is reported twice. + """ + + def __init__(self, manager): + self.manager = manager + self.ratios = {} + + def _take(self): + for name, state in list(getattr(self.manager, "_state_cache", {}).items()): + ratios = list(getattr(state, "calibration_ratios", None) or ()) + if ratios: + self.ratios[name] = ratios + else: + self.ratios.pop(name, None) + + def install(self): + reset = self.manager.reset + + def taking_reset(*args, **kwargs): + self._take() + return reset(*args, **kwargs) + + self.manager.reset = taking_reset + + def remove(self): + # The wrapper is an instance attribute over the class's own method + self.manager.__dict__.pop("reset", None) + + def report(self): + self._take() + for name, ratios in self.ratios.items(): + _report_mag_ratios(ratios, name) + self.ratios = {} + + +def watching_unfinished_mag_calibration(transformer): + """Start holding the ratios a calibrating call leaves unfinished (#927). + + Returns: + (report, remove): `report()` emits them, once the call has completed; + `remove()` stops watching. Both are no-ops unless the transformer's + cache is a MagCacheConfig with calibrate on. + """ + if not getattr(getattr(transformer, "_cache_config", None), "calibrate", False): + return (lambda: None), (lambda: None) + manager = _tail_state_manager(transformer) + if manager is None or not callable(getattr(manager, "reset", None)): + return (lambda: None), (lambda: None) + watch = _UnfinishedCalibration(manager) + watch.install() + return watch.report, watch.remove @contextlib.contextmanager diff --git a/dw/pipeline_processors/modular_arguments.py b/dw/pipeline_processors/modular_arguments.py new file mode 100644 index 000000000..2e382f256 --- /dev/null +++ b/dw/pipeline_processors/modular_arguments.py @@ -0,0 +1,44 @@ +"""What a modular pipeline call is handed: its keyword arguments, minus None. + +The None rule (#1315, plan Q1): before dw calls a modular pipeline (a +diffusers `ModularPipeline` - MiniMax-H3, FLUX 3 Klein), it drops every +top-level keyword argument whose value is `None`, so `null` means "the +block's default", whatever the source - a `previous_result:` that resolved +to nothing, a literal `null`, or an H3 wrapper's explicit `guides=None`. + +That was diffusers 0.42's own meaning: a modular block treated an explicit +None as absent and took its `InputParam` default. 0.43 keeps an explicit None +and hands it to the block, so without this drop the same workflow would +change meaning on a diffusers upgrade. + +- A classic `DiffusionPipeline` is untouched: it never had the fallback, and + None is a real value to many of its signatures. +- Only the top level is filtered. A None inside a list (a null variable in a + list argument) is left as is. +- A falsy non-None value (0, False, "", []) is a value, and is kept. + +Used by dw/pipeline_processors/pipeline.py (the main call) and +dw/pipeline_processors/h3_tiles.py (the tiled refine's text and tile calls). +""" + + +def is_modular_pipeline(pipeline): + """Whether `pipeline` is a diffusers ModularPipeline.""" + try: + from diffusers.modular_pipelines import ModularPipeline + except ImportError: # pragma: no cover - every supported diffusers has it + return False + return isinstance(pipeline, ModularPipeline) + + +def without_none(arguments): + """`arguments` without its top-level None values (a new dict).""" + return {key: value for key, value in arguments.items() if value is not None} + + +def call_arguments(pipeline, arguments): + """The keyword arguments to call `pipeline` with: `arguments` without its + top-level None values when the pipeline is modular, unchanged otherwise.""" + if is_modular_pipeline(pipeline): + return without_none(arguments) + return arguments diff --git a/dw/pipeline_processors/pipeline.py b/dw/pipeline_processors/pipeline.py index c83a40445..0740f5f91 100644 --- a/dw/pipeline_processors/pipeline.py +++ b/dw/pipeline_processors/pipeline.py @@ -36,6 +36,7 @@ REFINE_TILES_INPUT, ) from .h3_tiles import run_tiled_refine +from .modular_arguments import call_arguments from .pipeline_h3 import H3Arguments, latent_anchor_source # noqa: F401 - re-exported from .progress import reported_blocks, reported_progress_bars from .timing import denoise_start_hook, is_compiled, mark @@ -626,7 +627,12 @@ def _execute_pipeline(self, arguments): return self._call_pipeline(arguments, attn_backend) def _call_pipeline(self, arguments, attn_backend): - """Call the pipeline with optional attention backend and cache contexts.""" + """Call the pipeline with optional attention backend and cache contexts. + + A modular pipeline is called without its None arguments, so a block's + own default applies (diffusers 0.43 keeps an explicit None); a classic + pipeline gets them as given (#1315, modular_arguments.py). + """ arguments = self._with_step_callback(arguments) self._check_refine(arguments) self._check_selflift(arguments) @@ -695,7 +701,9 @@ def _call_pipeline(self, arguments, attn_backend): self.pipeline, arguments, self.segment_label or self.name ) else: - output = self.pipeline(**arguments) + # A modular call drops its None arguments (the None + # rule, dw/pipeline_processors/modular_arguments.py) + output = self.pipeline(**call_arguments(self.pipeline, arguments)) except IndexError as e: cache = self.configuration.get("cache") if ( diff --git a/tests/test_cache_blocks.py b/tests/test_cache_blocks.py index 383847eb3..6cfab3f64 100644 --- a/tests/test_cache_blocks.py +++ b/tests/test_cache_blocks.py @@ -633,3 +633,62 @@ def test_mag_calibration_an_errored_call_reports_no_partial_lists(monkeypatch): raise RuntimeError("out of memory") assert not [w for w in warnings if w.startswith("MagCache calibration (")] + + +def _calibrate_call_reset_in_call(components, model, steps_run): + """As _calibrate_call, but the call resets its components' cache hooks before + it returns, the way diffusers 0.43's ModularPipeline.__call__ does in its + `finally` (#1315).""" + with components.captured_mag_calibration( + _FakePipeline(model), {"num_inference_steps": 4} + ): + with components.stateful_cache_context(_FakePipeline(model)): + try: + for context in ("cond", "uncond"): + _run_calibration_steps(model, context, steps_run) + finally: + model._reset_stateful_cache() + + +def test_mag_calibration_survives_a_reset_inside_the_call(monkeypatch): + """#1315: under 0.43 the state is reset before the call returns; the + unfinished ratios are still reported, one list per CFG context.""" + from dw.pipeline_processors import components, mag_calibration + + warnings = [] + monkeypatch.setattr(mag_calibration, "emit_log", lambda *a, **k: None) + monkeypatch.setattr(mag_calibration, "emit_warning", warnings.append) + + _calibrate_call_reset_in_call(components, _mag_model(4), steps_run=3) + + reported = [w for w in warnings if w.startswith("MagCache calibration (")] + assert len(reported) == 2 + assert "[cond]" in reported[0] and "[uncond]" in reported[1] + assert all("MagCache calibration (3 steps)" in w for w in reported) + + +def test_mag_calibration_a_finished_call_reset_inside_is_reported_once(monkeypatch): + from dw.pipeline_processors import components, mag_calibration + + warnings = [] + monkeypatch.setattr(mag_calibration, "emit_log", lambda *a, **k: None) + monkeypatch.setattr(mag_calibration, "emit_warning", warnings.append) + + _calibrate_call_reset_in_call(components, _mag_model(4), steps_run=4) + + reported = [w for w in warnings if w.startswith("MagCache calibration (")] + assert len(reported) == 2 + assert all("MagCache calibration (4 steps)" in w for w in reported) + + +def test_mag_calibration_watch_is_removed_after_the_call(monkeypatch): + """The reset wrapper does not outlive the call it watched.""" + from dw.pipeline_processors import components, mag_calibration + + monkeypatch.setattr(mag_calibration, "emit_log", lambda *a, **k: None) + monkeypatch.setattr(mag_calibration, "emit_warning", lambda *a, **k: None) + + model = _mag_model(4) + _calibrate_call_reset_in_call(components, model, steps_run=3) + manager = mag_calibration._tail_state_manager(model) + assert "reset" not in vars(manager) diff --git a/tests/test_modular_arguments.py b/tests/test_modular_arguments.py new file mode 100644 index 000000000..c1a9ca627 --- /dev/null +++ b/tests/test_modular_arguments.py @@ -0,0 +1,110 @@ +"""diffusers 0.43 readiness, stage A of #1315: the modular None rule and the +attention-backend guard.""" + +import pytest +from diffusers.modular_pipelines import ModularPipeline + +from dw.pipeline_processors.modular_arguments import call_arguments, without_none +from dw.pipeline_processors.pipeline import Pipeline + + +class _Modular(ModularPipeline): + """A ModularPipeline that records what it is called with.""" + + def __init__(self): + self.seen = None + + def __call__(self, **arguments): + self.seen = arguments + return "output" + + +class _Classic: + def __init__(self): + self.seen = None + + def __call__(self, **arguments): + self.seen = arguments + return "output" + + +def _wrapper(fake): + return Pipeline( + { + "configuration": {}, + "from_pretrained_arguments": {"model_name": "x"}, + "arguments": {}, + }, + 1, + "cpu", + pipeline=fake, + ) + + +ARGUMENTS = {"a": None, "b": 0, "c": [None], "d": False, "e": ""} + + +def test_a_modular_call_drops_its_none_arguments(): + """0.43 keeps an explicit None over a block's default; dw passes none.""" + fake = _Modular() + assert _wrapper(fake)._execute_pipeline(dict(ARGUMENTS)) == "output" + assert "a" not in fake.seen + # Falsy values and a nested None are the caller's, and stay + assert fake.seen == {"b": 0, "c": [None], "d": False, "e": ""} + + +def test_a_classic_call_keeps_its_none_arguments(): + fake = _Classic() + assert _wrapper(fake)._execute_pipeline(dict(ARGUMENTS)) == "output" + assert fake.seen == ARGUMENTS + + +def test_without_none_is_top_level_only(): + assert without_none({"a": None, "b": {"c": None}}) == {"b": {"c": None}} + + +def test_call_arguments_leaves_a_classic_pipelines_arguments_alone(): + arguments = {"a": None} + assert call_arguments(_Classic(), arguments) is arguments + assert call_arguments(_Modular(), arguments) == {} + + +class _Component: + def __init__(self): + self.backends = [] + + def set_attention_backend(self, backend): + self.backends.append(backend) + + +def test_backend_pin_without_the_registry_attribute_just_pins(monkeypatch): + """#1315: the save/restore reads a private attribute; a diffusers without + it still gets the pin, and nothing raises.""" + from diffusers.models.attention_dispatch import _AttentionBackendRegistry + + from dw.pipeline_processors.components import set_component_attention_backend + + monkeypatch.delattr(_AttentionBackendRegistry, "_active_backend") + + def no_restore(*args, **kwargs): + pytest.fail("the restore ran without the attribute it restores") + + monkeypatch.setattr(_AttentionBackendRegistry, "set_active_backend", no_restore) + component = _Component() + set_component_attention_backend(component, "sage_hub") + assert component.backends == ["sage_hub"] + + +def test_backend_pin_with_the_registry_attribute_restores_it(monkeypatch): + from diffusers.models.attention_dispatch import _AttentionBackendRegistry + + from dw.pipeline_processors.components import set_component_attention_backend + + monkeypatch.setattr(_AttentionBackendRegistry, "_active_backend", "native") + restored = [] + monkeypatch.setattr( + _AttentionBackendRegistry, "set_active_backend", restored.append + ) + component = _Component() + set_component_attention_backend(component, "sage_hub") + assert component.backends == ["sage_hub"] and restored == ["native"] diff --git a/tests/test_sparse_attention_backends.py b/tests/test_sparse_attention_backends.py index debb6b135..c988d0630 100644 --- a/tests/test_sparse_attention_backends.py +++ b/tests/test_sparse_attention_backends.py @@ -3,7 +3,7 @@ import pytest import torch -from dw import sparse_attention +from dw import acceleration_warnings, sparse_attention from dw.acceleration_warnings import CUDA_ONLY_ATTENTION_BACKENDS from dw.acceleration_warnings import available_attention_backends @@ -29,6 +29,10 @@ def test_mps_lists_no_cuda_backends(): def test_cuda_lists_sparse_when_kernels_present(monkeypatch): + # The full list, as on a CUDA box with every backend's package installed + monkeypatch.setattr( + acceleration_warnings, "attention_backend_usable", lambda b: True + ) monkeypatch.setattr(sparse_attention, "_kernels_importable", lambda: True) names = available_attention_backends("cuda") assert names[0] == "native" @@ -109,3 +113,35 @@ def test_health_carries_attention_backends(server): # noqa: F811 body = client.get("/api/health").json() assert "native" in body["attention_backends"] assert isinstance(body["attention_backends"], list) + + +def _unusable(*unusable): + """A stand-in for diffusers' requirement check refusing `unusable`.""" + + def check(backend): + if backend.value in unusable: + raise RuntimeError(f"{backend.value} needs a package this install lacks") + + return check + + +def test_a_backend_diffusers_reports_unavailable_is_not_listed(monkeypatch): + """#1315: the list follows diffusers' own requirement check.""" + import diffusers.models.attention_dispatch as dispatch + + monkeypatch.setattr( + dispatch, "_check_attention_backend_requirements", _unusable("sage_hub", "flex") + ) + monkeypatch.setattr(sparse_attention, "_kernels_importable", lambda: True) + names = available_attention_backends("cuda") + assert "sage_hub" not in names and "flex" not in names + assert "native" in names and "sparse" in names and "_native_cudnn" in names + + +def test_a_diffusers_without_the_check_filters_nothing(monkeypatch): + import diffusers.models.attention_dispatch as dispatch + + monkeypatch.delattr(dispatch, "_check_attention_backend_requirements") + monkeypatch.setattr(sparse_attention, "_kernels_importable", lambda: True) + names = available_attention_backends("cuda") + assert "sage_hub" in names and "flex" in names From 4b1940b8de614d444561d8b7e2a1a0738c895634 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Sat, 14 Nov 2026 01:39:08 -0600 Subject: [PATCH 008/412] docs(proposal): #1355 - task-only job lane vs queue-wait hint Co-Authored-By: Claude Sonnet 5.5 --- docs/proposals/1355-task-only-lane.md | 30 +++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 docs/proposals/1355-task-only-lane.md diff --git a/docs/proposals/1355-task-only-lane.md b/docs/proposals/1355-task-only-lane.md new file mode 100644 index 000000000..09a4ef0e2 --- /dev/null +++ b/docs/proposals/1355-task-only-lane.md @@ -0,0 +1,30 @@ +# #1355 - task-only jobs wait FIFO behind GPU jobs + +Problem: `Dispatcher._pick` (`dw/server/dispatch.py`) hands a job a free card +slot in queue order. A task-only workflow (no pipeline step; ffmpeg-class +tasks, 9-14 s) holds a slot like any other, so it waits behind every H3-class +job, minutes to tens of minutes. A consumer that assembles between +generations loses that wait each time. + +## Options + +A. **Task lane (the issue's first ask).** A job whose definition has no + pipeline step (`dw/plan.py::_unpriced_reason` already detects it) skips + `_pending`'s slot gate and runs on its own thread via a separate + CPU-side worker (not a card's persistent worker, which is busy and + holds the model cache). Needs: a lane worker (spawned subprocess, one at + a time, or N), host-RAM accounting for it, `get_health.workers` + reporting it, `device: null` semantics, cancel and event plumbing. Risk: + tasks that use the GPU (upscale, resample on cuda) would contend with a + running job; the lane must be limited to tasks known to be CPU-only, or + it needs a per-task flag. + +B. **Wait hint only.** Keep FIFO; when a job is queued and no card is free, + emit a `queue_wait` event (reason `gpu_busy`) and fill `waiting_for` with + "queued behind N jobs on ; running jobs started T ago", plus the + observed-cost estimate of the running jobs where known + (`dw/server/observed_cost.py`). Consumers can tell waiting from stuck. Small, + reversible, no engine change. + +Recommendation: B now (it is cheap and solves "stuck vs waiting"), A as a +separate approved piece of work limited to CPU-only tasks. From 311a9aa8cff88b0af3442f1295a8fee31be51f07 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Sat, 14 Nov 2026 01:48:34 -0600 Subject: [PATCH 009/412] feat(engine): #1342 - count a fixed denoising_step_list as len - 1 passes dw/step_passes.py holds the rule: a pipeline whose config (or call) carries a denoising_step_list runs len - 1 passes. TST, MagCache calibration, per-step progress, cost scaling and the short-schedule cache warning read it; MagCache calibration and TST are skipped on such a pipeline with a 'not supported on a fixed step-list sampler' warning, at run time and at validate. Without a step list every count is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/ACCELERATION.md | 2 + dw/acceleration_warnings.py | 41 ++- dw/cost_scaling.py | 25 +- dw/pipeline_processors/h3_tst.py | 28 ++- dw/pipeline_processors/mag_calibration.py | 11 + dw/pipeline_processors/pipeline.py | 22 +- dw/plan.py | 5 + dw/step_passes.py | 110 ++++++++ tests/test_step_passes.py | 293 ++++++++++++++++++++++ 9 files changed, 524 insertions(+), 13 deletions(-) create mode 100644 dw/step_passes.py create mode 100644 tests/test_step_passes.py diff --git a/docs/ACCELERATION.md b/docs/ACCELERATION.md index ab7493e16..b1200efe0 100644 --- a/docs/ACCELERATION.md +++ b/docs/ACCELERATION.md @@ -77,6 +77,8 @@ For a model with no preset, run once with `"calibrate": true`: Calibration skips nothing. At the end of the run the ratios appear as a job warning and a `log` event (`get_job`'s `warnings`, `get_job_events`, `export_job`): `MagCache calibration (N steps): [ ... ] — paste into mag_ratios`. While calibrating, the run's own `num_inference_steps` is used, and a mismatch with the cache's is reported as a warning. Paste the array into `mag_ratios`, drop `calibrate`, and set the cache's `num_inference_steps` to the reported `N`, which counts the forwards actually made: MiniMax-H3's scheduler turns N sigmas into N - 1 evaluations, so a 30-step H3 call reports 29 ratios. +A pipeline whose config fixes a `denoising_step_list` (a distilled sampler that takes no `num_inference_steps`) runs `len - 1` passes, and that count is what the short-schedule warning, progress and cost scaling read. MagCache calibration and TST are keyed on `num_inference_steps`, so on such a pipeline both are skipped with a warning that they are not supported on a fixed step-list sampler (`dw/step_passes.py`). + A pipeline that runs classifier-free guidance as two passes in separate `cond` and `uncond` cache contexts (Qwen-Image-2.1 with `true_cfg_scale` above 1 and a `negative_prompt`, or the other Qwen-Image pipelines) emits two lists, labeled `[cond]` and `[uncond]`; use the `cond` one. A guidance-distilled pipeline such as Flux, or one that batches both passes into one forward, emits one unlabeled list. A pipeline the cache cannot attach to (see `cache_unsupported` above) reports nothing. ### TaylorSeerCache diff --git a/dw/acceleration_warnings.py b/dw/acceleration_warnings.py index e88305fcb..d6733c0eb 100644 --- a/dw/acceleration_warnings.py +++ b/dw/acceleration_warnings.py @@ -30,6 +30,10 @@ - `sparse_attention_fallback`: the `sparse` attention backend on a device that isn't CUDA. It never fails a run: it falls back to dense attention, so this says the speedup is not coming, not that the job will break. +- `step_list_unsupported`: MagCache calibration or TST on a pipeline whose + config fixes a `denoising_step_list` (#1316). Both are keyed on + `num_inference_steps`, so the run skips them; the short-schedule check + above counts such a pipeline's `len - 1` passes (`dw/step_passes.py`). Every one is a warning and never a refusal. A value that cannot be resolved before the run (a null variable, an unknown device) leaves its warning @@ -44,6 +48,7 @@ from .references import iter_steps, render_path from . import sparse_attention from .sparse_attention import SPARSE_BACKEND +from .step_passes import STEP_LIST_UNSUPPORTED, STEPS_KEY, step_list_passes from .vram_estimate import required_vram_gb # The fewest denoise steps a threshold cache is expected to skip any of. A @@ -89,6 +94,11 @@ BACKEND_UNAVAILABLE = "attention_backend_unavailable" SPARSE_FALLBACK = "sparse_attention_fallback" CACHE_UNSUPPORTED = "cache_unsupported" +STEP_LIST_FEATURE = "step_list_unsupported" + +# The call argument that turns TST on (h3_tst.TST_INPUT; that module loads +# torch, which validate does not) +_TST_INPUT = "experimental_tst" # The component names a cache hook attaches to, as in # dw.pipeline_processors.mag_calibration.get_cache_transformer @@ -97,11 +107,13 @@ def _steps(pipeline): """The resolved `num_inference_steps` the pipeline is called with, or - None when it is not a number known before the run.""" + None when it is not a number known before the run. A pipeline that fixes + a `denoising_step_list` runs its `len - 1` passes instead (#1316).""" + passes = step_list_passes(pipeline) + if passes is not None: + return passes arguments = pipeline.get("arguments") - value = (arguments if isinstance(arguments, dict) else {}).get( - "num_inference_steps" - ) + value = (arguments if isinstance(arguments, dict) else {}).get(STEPS_KEY) if isinstance(value, bool) or not isinstance(value, (int, float)): return None return value @@ -199,6 +211,15 @@ def _cache_warnings(cache, pipeline, path, where, context, component_type=None): f"for its threshold) and still perturbs the result{where}; drop the " f"cache or run >= {CACHE_MIN_USEFUL_STEPS} steps" ) + if ( + cache_type == "mag" + and cache.get("calibrate") is True + and step_list_passes(pipeline) is not None + ): + warnings.append( + f"{path}: {STEP_LIST_FEATURE}: MagCache calibration is " + f"{STEP_LIST_UNSUPPORTED}{where}; the run skips it" + ) reason = _cache_unsupported(component_type) if reason: warnings.append( @@ -242,6 +263,18 @@ def acceleration_warnings(context): configuration.get("component_type"), ) + arguments = pipeline.get("arguments") + if ( + isinstance(arguments, dict) + and arguments.get(_TST_INPUT) not in (None, False) + and step_list_passes(pipeline) is not None + ): + warnings.append( + f"{render_path(('steps', source, 'pipeline', 'arguments', _TST_INPUT))}: " + f"{STEP_LIST_FEATURE}: TST is {STEP_LIST_UNSUPPORTED}{where}; " + f"the run skips it" + ) + backends = [(base + ("attention_backend",), configuration)] for name, component in _components(configuration): component_path = base + ("components", name) diff --git a/dw/cost_scaling.py b/dw/cost_scaling.py index 4cf522722..450da2299 100644 --- a/dw/cost_scaling.py +++ b/dw/cost_scaling.py @@ -7,7 +7,8 @@ `height`, `num_frames`, per list entry summed) scales it in proportion (`scale_curated`), and so does any driver a `cost` entry names in its `scales_with` (a Music 3 `audio_duration`, or that field summed over a -list driver's entries - #1199); any other declared driver that moved has no +list driver's entries - #1199); a `denoising_step_list` driver scales by the +passes it runs, `len - 1` (#1316, `dw/step_passes.py`); any other declared driver that moved has no rule to scale by, so the figure is kept and flagged. `dw/plan.py` prices the run and applies the answer (`_scaled`); `dw/server/deps.py` scales an inherited figure with the same `scale_curated`, so an inline copy and its template @@ -23,6 +24,7 @@ from . import references from .presets import effective_variables +from .step_passes import STEP_LIST_KEY, step_list_passes # The basis an estimate quotes its minutes on UNKNOWN = "unknown" @@ -696,6 +698,19 @@ def _declared_axis_scaling(name, default_value, value, list_entries, proportiona return factor, axes +def _step_list_scaling(default_value, value): + """A `denoising_step_list` driver as (factor, axes): the ratio of the + passes it runs, `len - 1`, to the default's, or None when either is not a + step list (#1316).""" + was = step_list_passes(None, {STEP_LIST_KEY: default_value}) + now = step_list_passes(None, {STEP_LIST_KEY: value}) + if was is None or now is None: + return None + if was == now: + return 1.0, [] + return now / was, [f"passes {now} vs {was}"] + + def chain_segment_scaling( was_definition, was_variables, now_definition, now_variables, drivers ): @@ -753,6 +768,14 @@ def _driver_scaling(definition, expanded, list_entries, baseline=None): if name in CHAIN_LENGTH_DRIVERS: chain_drivers.append(name) continue + if name == STEP_LIST_KEY: + # A fixed sampler schedule: its passes, not a list's entries + moved = _step_list_scaling(default_value, effective.get(name)) + if moved is None: + return None + factor *= moved[0] + axes.extend(moved[1]) + continue if isinstance(default_value, list) or name in proportional: moved = _declared_axis_scaling( name, default_value, effective.get(name), list_entries, proportional diff --git a/dw/pipeline_processors/h3_tst.py b/dw/pipeline_processors/h3_tst.py index c0b37de1f..2f19bda9c 100644 --- a/dw/pipeline_processors/h3_tst.py +++ b/dw/pipeline_processors/h3_tst.py @@ -102,6 +102,12 @@ from ..events import emit_log from ..for_each import render_path from ..sparse_attention import forward_arg +from ..step_passes import ( + STEP_LIST_UNSUPPORTED, + STEPS_KEY, + pipeline_step_passes, + step_list_passes, +) from .h3_rules import REFINE_WINDOWS_ENV_VAR, not_h3 logger = logging.getLogger("dw") @@ -601,11 +607,23 @@ def _report(label, settings, states): def _evaluations(num_inference_steps): """The transformer evaluations a call runs. H3's `num_inference_steps` N counts sigma grid points (MiniMaxH3Scheduler), so it drives N - 1; a call - that names none (or not a whole number) runs the default.""" - steps = num_inference_steps - if isinstance(steps, bool) or not isinstance(steps, int) or steps < 2: - steps = DEFAULT_STEPS - return steps - 1 + that names none (or not a whole number) runs the default. The rule is + `dw.step_passes.pipeline_step_passes`'; a step-list pipeline never gets + here (`step_list_refusal`).""" + return pipeline_step_passes( + None, {STEPS_KEY: num_inference_steps}, default=DEFAULT_STEPS + ) + + +def step_list_refusal(pipeline, arguments): + """Why TST's step-keyed schedule is skipped for this call, or None. + + The ramp is keyed on the passes a `num_inference_steps` schedule runs; a + pipeline whose config fixes a `denoising_step_list` is skipped with a + warning rather than ramped over a step count it does not run (#1316).""" + if step_list_passes(pipeline, arguments) is None: + return None + return f"TST (experimental, #1196) is {STEP_LIST_UNSUPPORTED}; the call runs without it" @contextmanager diff --git a/dw/pipeline_processors/mag_calibration.py b/dw/pipeline_processors/mag_calibration.py index 53694f313..da93a50ae 100644 --- a/dw/pipeline_processors/mag_calibration.py +++ b/dw/pipeline_processors/mag_calibration.py @@ -14,6 +14,7 @@ import logging from ..events import emit_log, emit_warning +from ..step_passes import STEP_LIST_UNSUPPORTED, step_list_passes def get_cache_transformer(pipeline): @@ -191,6 +192,16 @@ def captured_mag_calibration(pipeline, arguments=None): yield return + if step_list_passes(pipeline, arguments) is not None: + # The calibration counts num_inference_steps, which a fixed step + # list does not take (#1316): skip it rather than end unlogged + emit_warning( + f"MagCache calibration is {STEP_LIST_UNSUPPORTED}; " + f"the call runs without calibrating" + ) + yield + return + steps = (arguments or {}).get("num_inference_steps") declared_steps = config.num_inference_steps if isinstance(steps, int) and steps != declared_steps: diff --git a/dw/pipeline_processors/pipeline.py b/dw/pipeline_processors/pipeline.py index 0740f5f91..0ad950290 100644 --- a/dw/pipeline_processors/pipeline.py +++ b/dw/pipeline_processors/pipeline.py @@ -52,7 +52,14 @@ # dw.prompt_weighting (transformers) and diffusers.hooks (peft, bitsandbytes) are # imported where they are used - at module scope they add seconds to every startup -from ..events import WorkflowCancelled, emit_log, emit_phase, get_context +from ..events import ( + WorkflowCancelled, + emit_log, + emit_phase, + emit_warning, + get_context, +) +from ..step_passes import step_list_passes from ..output_extraction import attach_video_frame_rate from ..step_cache import component_names, copy_containers from ..sparse_attention import ( @@ -665,8 +672,13 @@ def _call_pipeline(self, arguments, attn_backend): # (and reports a fallback) while the processors are still on stack.enter_context(sparse_call(self.pipeline, label)) if tst is not None: - from .h3_tst import tst_call + from .h3_tst import step_list_refusal, tst_call + skipped = step_list_refusal(self.pipeline, arguments) + if skipped: + emit_warning(f"{label}: {skipped}") + tst = None + if tst is not None: stack.enter_context( tst_call( self.pipeline, @@ -744,7 +756,11 @@ def _with_step_callback(self, arguments): return arguments run_context = get_context() - num_steps = arguments.get("num_inference_steps", None) + # A fixed step list runs len - 1 passes and takes no + # num_inference_steps (#1316, dw/step_passes.py) + num_steps = step_list_passes(self.pipeline, arguments) or arguments.get( + "num_inference_steps", None + ) def on_step_end(pipe, step_index, timestep, callback_kwargs): mark("pass_ended") diff --git a/dw/plan.py b/dw/plan.py index 6aa603efd..403587de3 100644 --- a/dw/plan.py +++ b/dw/plan.py @@ -11,6 +11,11 @@ describes the run and not an approximation of it. Nothing here knows a model: every minute comes from a `cost` block and every repo name from a `from_pretrained_arguments`. + +A step's denoising passes are counted by `dw/step_passes.py`: a pipeline +whose config fixes a `denoising_step_list` runs `len - 1` of them, and a +`denoising_step_list` cost driver scales the figure by that count +(`cost_scaling._driver_scaling`, #1316). """ import copy diff --git a/dw/step_passes.py b/dw/step_passes.py new file mode 100644 index 000000000..d595284d2 --- /dev/null +++ b/dw/step_passes.py @@ -0,0 +1,110 @@ +"""How many transformer passes a pipeline call runs (#1316). + +Most samplers take `num_inference_steps` N. A flow-matching sampler such as +MiniMax-H3's counts N sigma grid points and so runs N - 1 passes; that is the +rule the step-count consumers have read until now. A distilled sampler can +instead fix its schedule in the pipeline's config as a `denoising_step_list` +of sigma points and take no `num_inference_steps` at all: it runs one pass +between each pair of points, `len - 1`. Read without this module, every +consumer would fall back to its own default (50 steps for TST, the +`num_inference_steps` a cache declares, a bar of unknown length) and mis-key. + +The rule is generic: no model is named here. The step list is looked for in +the call's arguments first, then in the pipeline's config - a loaded +pipeline's `config` (or an attribute of that name, as a modular pipeline +exposes its config values), or, at validate time, a workflow step's +`pipeline` block, whose `arguments` and `from_pretrained_arguments` are the +only places a workflow can state one. + +Consumers: TST's step ramp (`pipeline_processors/h3_tst.py`), MagCache +calibration (`pipeline_processors/mag_calibration.py`), per-step progress +(`pipeline_processors/pipeline.py`), cost scaling (`cost_scaling.py`) and the +short-schedule cache warning (`acceleration_warnings.py`). A step-list +pipeline skips MagCache calibration and TST's step-keyed schedule, with +`STEP_LIST_UNSUPPORTED` said instead. +""" + +import math + +STEP_LIST_KEY = "denoising_step_list" +STEPS_KEY = "num_inference_steps" + +# The tail of the warning a step-keyed feature gives on a step-list pipeline +STEP_LIST_UNSUPPORTED = "not supported on a fixed step-list sampler" + + +def _as_step_list(value): + """`value` as a list of finite numbers of at least two points, or None.""" + if not isinstance(value, (list, tuple)) or len(value) < 2: + return None + for point in value: + if isinstance(point, bool) or not isinstance(point, (int, float)): + return None + if not math.isfinite(point): + return None + return list(value) + + +def _config_value(pipeline): + """The `denoising_step_list` a pipeline's config carries, as written.""" + if pipeline is None: + return None + if isinstance(pipeline, dict): + # A workflow step's `pipeline` block, at validate time + for key in ("arguments", "from_pretrained_arguments"): + block = pipeline.get(key) + if isinstance(block, dict) and STEP_LIST_KEY in block: + return block[STEP_LIST_KEY] + return None + config = getattr(pipeline, "config", None) + if hasattr(config, "get"): + try: + value = config.get(STEP_LIST_KEY) + except Exception: + value = None + if value is not None: + return value + try: + return getattr(pipeline, STEP_LIST_KEY, None) + except Exception: + return None + + +def step_list(pipeline, arguments=None): + """The fixed step list a call of `pipeline` with `arguments` runs, or None + when it runs a `num_inference_steps` schedule. + + Args: + pipeline: A loaded pipeline, a workflow step's `pipeline` block, or + None (only the arguments are read). + arguments: The call's arguments, or None. + """ + if isinstance(arguments, dict) and STEP_LIST_KEY in arguments: + points = _as_step_list(arguments[STEP_LIST_KEY]) + if points is not None: + return points + return _as_step_list(_config_value(pipeline)) + + +def step_list_passes(pipeline, arguments=None): + """The passes a step-list pipeline runs, `len - 1`, or None when the call + has no step list (the caller keeps its own `num_inference_steps` count).""" + points = step_list(pipeline, arguments) + return None if points is None else len(points) - 1 + + +def pipeline_step_passes(pipeline, arguments=None, default=None): + """The transformer passes a call of `pipeline` with `arguments` runs. + + A step list's `len - 1`; otherwise `num_inference_steps` N read as N - 1 + passes (N sigma points, the flow-matching rule). An N that is missing or + not a whole number of at least 2 falls back to `default` steps, and to + None when there is no default. + """ + passes = step_list_passes(pipeline, arguments) + if passes is not None: + return passes + steps = arguments.get(STEPS_KEY) if isinstance(arguments, dict) else None + if isinstance(steps, bool) or not isinstance(steps, int) or steps < 2: + steps = default + return None if steps is None else steps - 1 diff --git a/tests/test_step_passes.py b/tests/test_step_passes.py new file mode 100644 index 000000000..447e1b55d --- /dev/null +++ b/tests/test_step_passes.py @@ -0,0 +1,293 @@ +"""A fixed `denoising_step_list` counts len - 1 passes in every step-count +consumer, and a pipeline without one counts as it did (#1316, #1342).""" + +import types + +import pytest + +from dw import events +from dw.step_passes import ( + STEP_LIST_KEY, + STEP_LIST_UNSUPPORTED, + pipeline_step_passes, + step_list, + step_list_passes, +) + +SEVEN = [1.0, 0.9375, 0.8333, 0.6667, 0.5, 0.25, 0.0] + + +class StepListPipeline: + """A loaded pipeline whose config fixes a 7-point schedule.""" + + def __init__(self, points=SEVEN): + self.config = {STEP_LIST_KEY: points} + + def __call__(self, prompt=None, callback_on_step_end=None): + return None + + +class PlainPipeline: + def __init__(self): + self.config = {"num_train_timesteps": 1000} + + def __call__(self, prompt=None, callback_on_step_end=None): + return None + + +# The helper + + +def test_seven_points_are_six_passes(): + assert step_list_passes(StepListPipeline()) == 6 + assert pipeline_step_passes(StepListPipeline(), {}) == 6 + + +def test_the_step_list_wins_over_num_inference_steps(): + assert pipeline_step_passes(StepListPipeline(), {"num_inference_steps": 30}) == 6 + + +def test_an_argument_step_list_wins_over_the_config(): + assert step_list_passes(StepListPipeline(), {STEP_LIST_KEY: [1.0, 0.5, 0.0]}) == 2 + + +def test_a_modular_pipeline_exposes_it_as_an_attribute(): + pipeline = types.SimpleNamespace(denoising_step_list=SEVEN) + assert step_list_passes(pipeline) == 6 + + +def test_a_workflow_pipeline_block_is_read_at_validate_time(): + block = {"from_pretrained_arguments": {STEP_LIST_KEY: SEVEN}, "arguments": {}} + assert step_list_passes(block) == 6 + assert step_list_passes({"arguments": {STEP_LIST_KEY: SEVEN}}) == 6 + + +def test_without_a_step_list_the_n_minus_one_rule_holds(): + assert step_list(PlainPipeline()) is None + assert step_list_passes(PlainPipeline(), {"num_inference_steps": 30}) is None + assert pipeline_step_passes(PlainPipeline(), {"num_inference_steps": 30}) == 29 + assert pipeline_step_passes(None, {}, default=50) == 49 + assert pipeline_step_passes(None, {}) is None + + +@pytest.mark.parametrize( + "value", [[1.0], [], "1,0", [1.0, "x"], [1.0, True], [1.0, float("nan")], None] +) +def test_a_value_that_is_not_a_step_list_is_ignored(value): + assert step_list_passes(None, {STEP_LIST_KEY: value}) is None + + +def test_the_engine_names_no_model(): + import dw.step_passes as module + + with open(module.__file__) as f: + assert "pika" not in f.read().lower() + + +# TST + + +def test_tst_steps_without_a_step_list_are_unchanged(): + from dw.pipeline_processors.h3_tst import DEFAULT_STEPS, _evaluations + + assert _evaluations(30) == 29 + assert _evaluations(None) == DEFAULT_STEPS - 1 + + +def test_tst_is_refused_on_a_step_list(): + from dw.pipeline_processors.h3_tst import step_list_refusal + + reason = step_list_refusal(StepListPipeline(), {}) + assert reason is not None and STEP_LIST_UNSUPPORTED in reason + assert step_list_refusal(PlainPipeline(), {"num_inference_steps": 30}) is None + + +# MagCache calibration + + +class _MagConfig: + calibrate = True + num_inference_steps = 28 + + +class _MagPipeline(StepListPipeline): + def __init__(self, points=SEVEN): + super().__init__(points) + self.transformer = types.SimpleNamespace(_cache_config=_MagConfig()) + + +def test_mag_calibration_is_skipped_on_a_step_list(monkeypatch): + from dw.pipeline_processors import mag_calibration + + warnings = [] + monkeypatch.setattr(mag_calibration, "emit_warning", warnings.append) + pipeline = _MagPipeline() + with mag_calibration.captured_mag_calibration(pipeline, {}): + # No handler is installed and the declared count is not touched + assert pipeline.transformer._cache_config.num_inference_steps == 28 + assert not mag_calibration.logging.getLogger( + mag_calibration._MAG_LOGGER + ).handlers + assert len(warnings) == 1 + assert "MagCache calibration" in warnings[0] + assert STEP_LIST_UNSUPPORTED in warnings[0] + + +# Progress + + +def _step_totals(pipeline, arguments): + from dw.pipeline_processors.pipeline import Pipeline + + owner = types.SimpleNamespace(pipeline=pipeline, _takes_step_callback=lambda: True) + seen = [] + context = events.RunContext(on_event=seen.append) + token = events.activate_context(context) + try: + call = Pipeline._with_step_callback(owner, arguments) + call["callback_on_step_end"](pipeline, 0, None, {}) + finally: + events.deactivate_context(token) + return [ + e for e in seen if isinstance(e, dict) and e.get("event") == "pipeline_step" + ] + + +def _total(steps): + assert steps, "no pipeline_step event" + event = steps[0] + data = event.get("data", event) + return data.get("total_steps") + + +def test_progress_counts_six_passes_on_a_step_list(): + assert _total(_step_totals(StepListPipeline(), {"prompt": "x"})) == 6 + + +def test_progress_without_a_step_list_is_unchanged(): + totals = _step_totals(PlainPipeline(), {"prompt": "x", "num_inference_steps": 30}) + assert _total(totals) == 30 + + +# Validate-time warnings + + +def _accel_pipeline(steps=None, step_list=None, cache=None, tst=None): + arguments = {"prompt": "a cat"} + if steps is not None: + arguments["num_inference_steps"] = steps + if step_list is not None: + arguments[STEP_LIST_KEY] = step_list + if tst is not None: + arguments["experimental_tst"] = tst + configuration = {} + if cache is not None: + configuration["cache"] = cache + return {"configuration": configuration, "arguments": arguments} + + +def test_the_short_schedule_check_counts_six_passes(): + from dw.acceleration_warnings import _cache_warnings, _steps + + pipeline = _accel_pipeline(steps=30, step_list=SEVEN) + assert _steps(pipeline) == 6 + warnings = _cache_warnings({"type": "first_block"}, pipeline, "p", "", None) + assert any("cache_short_schedule" in w and "6 steps" in w for w in warnings) + + +def test_the_short_schedule_check_without_a_step_list_is_unchanged(): + from dw.acceleration_warnings import _cache_warnings, _steps + + pipeline = _accel_pipeline(steps=30) + assert _steps(pipeline) == 30 + assert _cache_warnings({"type": "first_block"}, pipeline, "p", "", None) == [] + + +def test_validate_warns_mag_calibration_on_a_step_list(): + from dw.acceleration_warnings import STEP_LIST_FEATURE, _cache_warnings + + pipeline = _accel_pipeline(step_list=SEVEN) + warnings = _cache_warnings( + {"type": "mag", "calibrate": True}, pipeline, "p", "", None + ) + found = [w for w in warnings if STEP_LIST_FEATURE in w] + assert len(found) == 1 and STEP_LIST_UNSUPPORTED in found[0] + plain = _cache_warnings( + {"type": "mag", "calibrate": True}, _accel_pipeline(steps=30), "p", "", None + ) + assert not [w for w in plain if STEP_LIST_FEATURE in w] + + +def _expanded_context(pipeline): + return types.SimpleNamespace( + expanded={"steps": [{"name": "gen", "pipeline": pipeline}]}, + source_indices=[0], + device_type="cuda", + capacity_gb=None, + ) + + +def test_validate_warns_tst_on_a_step_list(): + from dw.acceleration_warnings import STEP_LIST_FEATURE, acceleration_warnings + + tst = {"tau": 0.2} + warnings = acceleration_warnings( + _expanded_context(_accel_pipeline(step_list=SEVEN, tst=tst)) + ) + found = [w for w in warnings if STEP_LIST_FEATURE in w] + assert len(found) == 1 and "TST" in found[0] + plain = acceleration_warnings(_expanded_context(_accel_pipeline(steps=30, tst=tst))) + assert not [w for w in plain if STEP_LIST_FEATURE in w] + + +# Cost scaling + + +def _definition(default_points): + return { + "variables": {STEP_LIST_KEY: default_points, "num_inference_steps": 30}, + "cost_drivers": [STEP_LIST_KEY, "num_inference_steps"], + "cost": [{"device": "cuda", "vram_gb": 24, "minutes": 6.0}], + } + + +def test_cost_scales_by_the_passes_ratio(): + from dw.cost_scaling import _driver_scaling + + definition = _definition([1.0, 0.5, 0.25, 0.0]) # 3 passes measured + scaling = _driver_scaling( + definition, + {"variables": {STEP_LIST_KEY: SEVEN, "num_inference_steps": 30}}, + {}, + ) + factor, axes, unscaled = scaling + assert factor == pytest.approx(2.0) + assert "passes 6 vs 3" in axes + assert unscaled == [] + + +def test_cost_at_the_default_step_list_is_unscaled(): + from dw.cost_scaling import _driver_scaling + + definition = _definition(SEVEN) + factor, axes, unscaled = _driver_scaling( + definition, + {"variables": {STEP_LIST_KEY: list(SEVEN), "num_inference_steps": 30}}, + {}, + ) + assert factor == pytest.approx(1.0) and axes == [] and unscaled == [] + + +def test_cost_steps_scaling_without_a_step_list_is_unchanged(): + from dw.cost_scaling import _driver_scaling + + definition = { + "variables": {"num_inference_steps": 30}, + "cost_drivers": ["num_inference_steps"], + "cost": [{"device": "cuda", "vram_gb": 24, "minutes": 6.0}], + } + factor, axes, _ = _driver_scaling( + definition, {"variables": {"num_inference_steps": 60}}, {} + ) + assert factor == pytest.approx(2.0) + assert axes == ["steps 60 vs 30"] From eda971ec0f81cb13ef126c8f156d8e818603949e Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Sat, 14 Nov 2026 01:56:10 -0600 Subject: [PATCH 010/412] feat(bench): #1346 - bf16-transformer sibling of narrated-take for the #1319 burn probe The transformer's SDNQ config is removed so it loads in bf16 under the same block group offload; the text encoder and VAE stay int8. host_ram_gb raised to a provisional 100 GB until the gate run measures it. Co-Authored-By: Claude Opus 5.5 --- bench/workflows/narrated-take-bf16.json | 324 ++++++++++++++++++++++++ 1 file changed, 324 insertions(+) create mode 100644 bench/workflows/narrated-take-bf16.json diff --git a/bench/workflows/narrated-take-bf16.json b/bench/workflows/narrated-take-bf16.json new file mode 100644 index 000000000..a380918ff --- /dev/null +++ b/bench/workflows/narrated-take-bf16.json @@ -0,0 +1,324 @@ +{ + "id": "BenchNarratedTakeBf16", + "summary": "narrated-take bench with a bf16 (unquantized) H3 transformer: the #1319 precision probe.", + "description": "bf16-transformer burn probe (#1319 plan v1, stage #1346): a sibling copy of bench/workflows/narrated-take.json (plan Q4: a separate file, so existing arms stay reproducible) that differs in one thing - the transformer's SDNQ quantization config is removed, so the transformer loads in bf16 (load_components dtype) and stays under the same block_level group offload from host RAM. The text encoder keeps variable:weights_dtype (int8 at tier best) and the VAE keeps int8, as in the parent. Every other argument, default and preset is the parent's, so with shot dialogue, seed 1 and stop_after 12 it is CP1 control d5584b91816d (bench/records/narrated.md) with only the transformer precision changed. host_ram_gb is raised for the bf16 transformer's extra ~33 GB of host-resident weights.", + "shape": "sequence", + "vram_estimate": { + "base_gb": 16.3, + "bytes_per_voxel": 28.71, + "bytes_per_guide_voxel": 28.71, + "voxel_variables": [ + "width", + "height", + "num_frames" + ], + "reason": "each segment is one H3 run, so the ceiling is a segment's: the t2va calibration (#324) - peak activation memory scales with width * height * num_frames - plus, under 'guide' continuity, the guide each segment after the first is given, which is encoded on the target canvas and costs about as much per voxel as the clip itself (docs/proposals/h3-guide-vram.md, #694)" + }, + "host_ram_gb": "variable:host_ram_gb", + "cost_drivers": [ + "tier", + "continuity", + "shot", + "num_frames", + "num_inference_steps", + "width", + "height", + "weights_dtype", + "lora_model_name", + "attention_backend", + "cache", + "check", + "retries" + ], + "variables": { + "tier": "best", + "host_ram_gb": 100, + "image": "asset:bench/constitution-speaker.jpg", + "narration": "asset:bench/constitution-narration-retimed.wav", + "script": "We the People of the United States, in Order to form a more perfect Union, establish Justice, insure domestic Tranquility, provide for the common defence, promote the general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution for the United States of America.\n\nAmendment One. Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the Government for a redress of grievances.\n\nAmendment Two. A well regulated Militia, being necessary to the security of a free State, the right of the people to keep and bear Arms, shall not be infringed.\n\nAmendment Three. No Soldier shall, in time of peace be quartered in any house, without the consent of the Owner, nor in time of war, but in a manner to be prescribed by law.\n\nAmendment Four. The right of the people to be secure in their persons, houses, papers, and effects, against unreasonable searches and seizures, shall not be violated, and no Warrants shall issue, but upon probable cause, supported by Oath or affirmation, and particularly describing the place to be searched, and the persons or things to be seized.\n\nAmendment Five. No person shall be held to answer for a capital, or otherwise infamous crime, unless on a presentment or indictment of a Grand Jury, except in cases arising in the land or naval forces, or in the Militia, when in actual service in time of War or public danger; nor shall any person be subject for the same offence to be twice put in jeopardy of life or limb; nor shall be compelled in any criminal case to be a witness against himself, nor be deprived of life, liberty, or property, without due process of law; nor shall private property be taken for public use, without just compensation.\n\nAmendment Six. In all criminal prosecutions, the accused shall enjoy the right to a speedy and public trial, by an impartial jury of the State and district wherein the crime shall have been committed, which district shall have been previously ascertained by law, and to be informed of the nature and cause of the accusation; to be confronted with the witnesses against him; to have compulsory process for obtaining witnesses in his favor, and to have the Assistance of Counsel for his defence.\n\nAmendment Seven. In Suits at common law, where the value in controversy shall exceed twenty dollars, the right of trial by jury shall be preserved, and no fact tried by a jury, shall be otherwise re-examined in any Court of the United States, than according to the rules of the common law.\n\nAmendment Eight. Excessive bail shall not be required, nor excessive fines imposed, nor cruel and unusual punishments inflicted.\n\nAmendment Nine. The enumeration in the Constitution, of certain rights, shall not be construed to deny or disparage others retained by the people.\n\nAmendment Ten. The powers not delegated to the United States by the Constitution, nor prohibited by it to the States, are reserved to the States respectively, or to the people.", + "scene": "a close-up from the top of the shoulders up of the woman in , centred, with close-cropped silver natural hair, small gold stud earrings, a charcoal grey wool overcoat over a cream turtleneck and a deep burgundy wool scarf, the bare elm-lined gravel path and the pale neoclassical stone building softly out of focus behind her, in soft overcast late-afternoon light with a muted earthy grade. She walks slowly and steadily toward the camera, which travels backward on a smooth dolly at exactly her walking pace, her eyes level on the lens, her face composed and grave.", + "speaker": "a Black American woman in her mid-sixties with a low, warm alto voice that carries the settled weight of age, a faint natural huskiness, a slow, measured, serious delivery with clear diction and quiet resolve, never theatrical", + "soundscape": "Quiet open-air park ambience under her voice: a soft steady breeze through the bare elm branches, the slow, even crunch of her shoes on the gravel, faint distant birdsong.", + "prompt_template": "For the target video, at 0.00 seconds into the target video, (from [Shot 1]) is fully referenced.\n\nintegrated_multimodal_description: [Shot 1] Live-action, cinematic, photorealistic, one continuous shot that carries over without a break from the previous shot. The shot opens exactly on : {scene} Preserving the speaker's face, clothing, framing and the setting exactly, the camera holds its framing for the whole shot: it never pushes in, and the speaker stays the same size in frame from the first frame to the last. (S1), {speaker}, at the same quiet level and unhurried pace as before, is already speaking and continues mid-flow, lips and jaw shaping every word clearly and in time with the sound: [English] {line} The delivery carries straight on to the end of the shot, with no pause to start over.\n\noverall_soundscape: {soundscape} The ambience runs under the voice throughout and never drops out.\n\nnon_diegetic_music: N/A", + "shot": "dialogue", + "continuity": "guide", + "num_frames": 192, + "guide_frames": 22, + "stop_after": null, + "resume_from": null, + "keep_segments": true, + "check": { + "jump_ratio_max": 4.0, + "look_ratio_max": 5.5, + "cut_ratio_max": 3.5, + "words_similarity_min": null, + "face_drop_max": null + }, + "retries": 1, + "width": 1344, + "height": 768, + "num_inference_steps": 20, + "video_shift": 12.0, + "audio_shift": 3.0, + "weights_dtype": "{int8}", + "lora_scale": 1.0, + "lora_alpha": null, + "lora_model_name": null, + "lora_weight_name": "minimax_h3_fl2v_turbo_4step_v1.2_768p_bf16.safetensors", + "lora_adapter_name": "turbo", + "seed": null, + "attention_backend": "sparse", + "sparse_tau": 0.5, + "sparse_topk": 0.15, + "cache": null, + "experimental_latent_carry": false, + "keystone": "none", + "keystone_slot": null, + "keyframes": null, + "experimental_capstone": null, + "anchor_every": null + }, + "presets": { + "shot": { + "dialogue": { + "continuity": "guide" + }, + "standing": { + "continuity": "guide", + "keystone": "segment_1", + "keystone_slot": "last" + }, + "walk_keyframed": { + "continuity": "guide", + "keystone": "segment_1", + "keystone_slot": "last" + } + }, + "tier": { + "standard": { + "width": 960, + "height": 544, + "num_inference_steps": 20, + "weights_dtype": "{int4}", + "host_ram_gb": 84 + }, + "best": { + "width": 1344, + "height": 768, + "num_inference_steps": 20, + "weights_dtype": "{int8}", + "host_ram_gb": 100 + } + } + }, + "variable_constraints": { + "image": { + "required": true, + "reason": "the speaker's first frame, of every segment prompt; a placeholder would film the wrong person" + }, + "narration": { + "required": true, + "reason": "the retimed narration from templates/narration-retime, the take's held soundtrack and the source of its segment count; there is no sensible default track" + }, + "script": { + "required": true, + "min_length": 1, + "reason": "the text the narration speaks, so each segment's line carries its spelling and punctuation" + }, + "scene": { + "required": true, + "min_length": 1, + "reason": "the shot's framing, the speaker's look and the setting, written for this take; a placeholder would describe another scene" + }, + "speaker": { + "required": true, + "min_length": 1, + "reason": "the speaker's voice and delivery for the (S1) tag; a placeholder would describe another voice" + }, + "num_frames": { + "modulus": 17, + "remainder": 5, + "min_frames": 124, + "max_frames": 345, + "snap": "up", + "reason": "the video VAE encodes 17 * n + 5 frames, and MiniMax-H3 generates between 5 and 15 seconds at 24 fps" + }, + "width": { + "modulus": 32, + "remainder": 0, + "reason": "MiniMax-H3's pipeline refuses a `width` or `height` that is not a multiple of 32, and only after the weights have loaded; refused here instead, with no 'snap', since rounding would be a silent change to the size asked for" + }, + "height": { + "modulus": 32, + "remainder": 0, + "reason": "MiniMax-H3's pipeline refuses a `width` or `height` that is not a multiple of 32, and only after the weights have loaded; refused here instead, with no 'snap', since rounding would be a silent change to the size asked for" + } + }, + "seed": "variable:seed", + "steps": [ + { + "name": "lines", + "task": { + "command": "narration_lines", + "arguments": { + "audio": "variable:narration", + "text": "variable:script", + "segment_frames": "variable:num_frames", + "guide_frames": "variable:guide_frames", + "fps": 24, + "prompt_template": "variable:prompt_template", + "fill": { + "scene": "variable:scene", + "speaker": "variable:speaker", + "soundscape": "variable:soundscape" + } + } + }, + "result": { + "content_type": "application/json", + "file_base_name": "narration-lines", + "subfolder": "intermediate" + } + }, + { + "name": "take", + "pipeline": { + "configuration": { + "component_type": "ModularPipeline", + "pre_load_modules": [ + "sdnq" + ], + "load_components": { + "dtype": "torch.bfloat16", + "quantization_config": { + "text_encoder": { + "configuration": { + "config_type": "sdnq.SDNQConfig" + }, + "arguments": { + "weights_dtype": "variable:weights_dtype", + "quantization_device": "cuda", + "return_device": "cpu", + "dequantize_fp32": false, + "modules_to_not_convert": [ + ".model.visual", + "lm_head" + ] + } + }, + "vae": { + "configuration": { + "config_type": "sdnq.SDNQConfig" + }, + "arguments": { + "weights_dtype": "{int8}", + "quant_conv": true, + "use_quantized_matmul_conv": true, + "quantization_device": "cuda", + "return_device": "cpu", + "dequantize_fp32": false + } + } + } + }, + "components": { + "transformer": { + "attention_backend": "variable:attention_backend", + "sparse_tau": "variable:sparse_tau", + "sparse_topk": "variable:sparse_topk", + "group_offload": { + "offload_type": "block_level", + "num_blocks_per_group": 2, + "use_stream": true, + "record_stream": true, + "low_cpu_mem_usage": true + } + }, + "text_encoder": { + "remove_modules": [ + "lm_head" + ] + }, + "text_encoder.model": { + "truncate_layers": { + "language_model.layers": 51 + }, + "group_offload": { + "offload_type": "leaf_level" + } + }, + "vae": { + "device": "cuda", + "residency": "on_demand" + }, + "audio_vae": { + "device": "cuda", + "residency": "on_demand" + } + }, + "cache": "variable:cache" + }, + "from_pretrained_arguments": { + "model_name": "MiniMaxAI/MiniMax-H3", + "workflow": "fl2va" + }, + "loras": [ + { + "model_name": "variable:lora_model_name", + "weight_name": "variable:lora_weight_name", + "adapter_name": "variable:lora_adapter_name", + "scale": "variable:lora_scale", + "alpha": "variable:lora_alpha" + } + ], + "chain": { + "match_audio": true, + "prompts": "previous_result:lines.prompts", + "continuity": "variable:continuity", + "guide_frames": "variable:guide_frames", + "check": "variable:check", + "retries": "variable:retries", + "stop_after": "variable:stop_after", + "segment_argument": "image", + "trim_frames": 2, + "crossfade_ms": 80, + "fps": 24, + "frame_snap": "constraint:num_frames", + "save_segments": true, + "keep_segments": "variable:keep_segments", + "resume_from": "variable:resume_from", + "experimental_latent_carry": "variable:experimental_latent_carry", + "keystone": "variable:keystone", + "keystone_slot": "variable:keystone_slot", + "keystone_images": "variable:keyframes", + "experimental_capstone": "variable:experimental_capstone", + "anchor_every": "variable:anchor_every" + }, + "scheduler": { + "shift": "variable:video_shift" + }, + "audio_scheduler": { + "shift": "variable:audio_shift" + }, + "arguments": { + "image": "variable:image", + "hold_audio": "variable:narration", + "num_frames": "variable:num_frames", + "width": "variable:width", + "height": "variable:height", + "num_inference_steps": "variable:num_inference_steps", + "output": [ + "videos", + "audio", + "sampling_rate" + ] + } + }, + "result": { + "content_type": "video/mp4", + "fps": 24, + "subfolder": "final" + } + } + ] +} From 2780cbe4297a2a3a49231fe22d8945ff99106e12 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Sat, 14 Nov 2026 02:16:13 -0600 Subject: [PATCH 011/412] feat(bench): #1346 - host_ram_gb 110 from the gate's measured peak RSS (db33868da007) Co-Authored-By: Claude Opus 5.5 --- bench/workflows/narrated-take-bf16.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bench/workflows/narrated-take-bf16.json b/bench/workflows/narrated-take-bf16.json index a380918ff..2821d0de3 100644 --- a/bench/workflows/narrated-take-bf16.json +++ b/bench/workflows/narrated-take-bf16.json @@ -32,7 +32,7 @@ ], "variables": { "tier": "best", - "host_ram_gb": 100, + "host_ram_gb": 110, "image": "asset:bench/constitution-speaker.jpg", "narration": "asset:bench/constitution-narration-retimed.wav", "script": "We the People of the United States, in Order to form a more perfect Union, establish Justice, insure domestic Tranquility, provide for the common defence, promote the general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution for the United States of America.\n\nAmendment One. Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the Government for a redress of grievances.\n\nAmendment Two. A well regulated Militia, being necessary to the security of a free State, the right of the people to keep and bear Arms, shall not be infringed.\n\nAmendment Three. No Soldier shall, in time of peace be quartered in any house, without the consent of the Owner, nor in time of war, but in a manner to be prescribed by law.\n\nAmendment Four. The right of the people to be secure in their persons, houses, papers, and effects, against unreasonable searches and seizures, shall not be violated, and no Warrants shall issue, but upon probable cause, supported by Oath or affirmation, and particularly describing the place to be searched, and the persons or things to be seized.\n\nAmendment Five. No person shall be held to answer for a capital, or otherwise infamous crime, unless on a presentment or indictment of a Grand Jury, except in cases arising in the land or naval forces, or in the Militia, when in actual service in time of War or public danger; nor shall any person be subject for the same offence to be twice put in jeopardy of life or limb; nor shall be compelled in any criminal case to be a witness against himself, nor be deprived of life, liberty, or property, without due process of law; nor shall private property be taken for public use, without just compensation.\n\nAmendment Six. In all criminal prosecutions, the accused shall enjoy the right to a speedy and public trial, by an impartial jury of the State and district wherein the crime shall have been committed, which district shall have been previously ascertained by law, and to be informed of the nature and cause of the accusation; to be confronted with the witnesses against him; to have compulsory process for obtaining witnesses in his favor, and to have the Assistance of Counsel for his defence.\n\nAmendment Seven. In Suits at common law, where the value in controversy shall exceed twenty dollars, the right of trial by jury shall be preserved, and no fact tried by a jury, shall be otherwise re-examined in any Court of the United States, than according to the rules of the common law.\n\nAmendment Eight. Excessive bail shall not be required, nor excessive fines imposed, nor cruel and unusual punishments inflicted.\n\nAmendment Nine. The enumeration in the Constitution, of certain rights, shall not be construed to deny or disparage others retained by the people.\n\nAmendment Ten. The powers not delegated to the United States by the Constitution, nor prohibited by it to the States, are reserved to the States respectively, or to the people.", @@ -107,7 +107,7 @@ "height": 768, "num_inference_steps": 20, "weights_dtype": "{int8}", - "host_ram_gb": 100 + "host_ram_gb": 110 } } }, From ca83da674fda36f4b663ad005f278fccc126ac23 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Sat, 14 Nov 2026 02:36:41 -0600 Subject: [PATCH 012/412] feat(bench): #1346 - face-crop sharpness/saturation/SFace windows and face strip for the burn probe Co-Authored-By: Claude Opus 5.5 --- bench/face_windows.py | 88 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 bench/face_windows.py diff --git a/bench/face_windows.py b/bench/face_windows.py new file mode 100644 index 000000000..0f4d6a850 --- /dev/null +++ b/bench/face_windows.py @@ -0,0 +1,88 @@ +"""Face-crop sharpness / saturation / identity per 10 s window, and a face strip. + +usage: python -I bench/face_windows.py
- {#if isBackendSelect(key)} + {#if isPresetSelect(key)} + {@const current = shown(key)} + + {:else if isBackendSelect(key)} {@const current = shown(key)} @@ -302,6 +315,12 @@ grid-column: 1 / -1; } } + .findings .bad { + color: var(--bad); + } + .findings .warn { + color: var(--warn); + } .addvar { justify-self: start; } diff --git a/ui/src/lib/findings.ts b/ui/src/lib/findings.ts new file mode 100644 index 000000000..d4bc2e833 --- /dev/null +++ b/ui/src/lib/findings.ts @@ -0,0 +1,68 @@ +import type { ValidationResult } from './types' + +/** One thing a validate answer said: an error (`bad`, a Run would be + * refused) or a warning (`warn`), as text the page prints and never parses + * further. */ +export type Finding = { tone: 'bad' | 'warn'; text: string } + +/** The findings a form field shows under itself, by variable name, and the + * rest, for the general list. */ +export type PlacedFindings = { + byVariable: Record + general: Finding[] +} + +// `arguments.` or `variables.`, the name as +// validate_variable_name() allows it, then whatever follows it ([i], .key) +const VARIABLE_PATH = /^(?:arguments|variables)\.([A-Za-z_][A-Za-z0-9_-]*)(.*)$/ +// A warning is "path: message" or a bare message; only a variable path +// prefix is read off it - a bare message may hold ": " itself +const VARIABLE_WARNING = + /^((?:arguments|variables)\.[A-Za-z_][A-Za-z0-9_-]*\S*): ([\s\S]*)$/ + +/** Split a validate answer into what goes under a field the form shows and + * what goes in the general list. A finding is placed only by its + * `arguments.` / `variables.` path prefix; the UI derives + * nothing else from it and filters nothing out (docs/ARCHITECTURE.md). */ +export function placeFindings( + result: ValidationResult | null, + shown: Iterable, +): PlacedFindings { + const names = new Set(shown) + const placed: PlacedFindings = { byVariable: {}, general: [] } + if (!result) return placed + + const place = ( + tone: Finding['tone'], + path: string | null, + message: string, + whole: string, + ) => { + const match = path ? VARIABLE_PATH.exec(path) : null + if (match && names.has(match[1])) { + // what follows the name (an [i] into a list, a key) stays with the + // message, so a field holding a list still says which entry + const rest = match[2].replace(/^\./, '') + const text = rest ? `${rest}: ${message}` : message + ;(placed.byVariable[match[1]] ??= []).push({ tone, text }) + } else { + placed.general.push({ tone, text: whole }) + } + } + + const errors = result.errors ?? [] + for (const error of errors) { + const path = error.path ?? null + place('bad', path, error.message, `${path ?? 'root'}: ${error.message}`) + } + // A refusal with no finding list still says why, in `error` + if (!result.valid && !errors.length && result.error) { + placed.general.push({ tone: 'bad', text: result.error }) + } + for (const warning of result.warnings ?? []) { + const match = VARIABLE_WARNING.exec(warning) + if (match) place('warn', match[1], match[2], warning) + else placed.general.push({ tone: 'warn', text: warning }) + } + return placed +} diff --git a/ui/src/lib/pages/WorkflowPage.svelte b/ui/src/lib/pages/WorkflowPage.svelte index 16bcaae0c..e6e4ce958 100644 --- a/ui/src/lib/pages/WorkflowPage.svelte +++ b/ui/src/lib/pages/WorkflowPage.svelte @@ -17,8 +17,15 @@ import { notify } from '../toast' import { observedText, observedTitle } from '../observed' import { confirmDialog } from '../confirm.svelte' - import type { GalleryFile, WorkflowDefinition } from '../types' + import type { + GalleryFile, + ValidationResult, + WorkflowDefinition, + } from '../types' import ClampedText from '../ui/ClampedText.svelte' + import { onDestroy } from 'svelte' + import { describePlan } from '../plan' + import { placeFindings } from '../findings' let { name }: { name: string } = $props() @@ -92,6 +99,128 @@ const variables = $derived(Object.entries(workflow?.variables ?? {})) + /** The arguments a Run sends: the overrides with every blank dropped, so + * a blank field leaves the workflow's own default in place. Validate asks + * about exactly these, so its answer predicts the Run click. */ + function runArguments(): Record { + const args: Record = {} + for (const [key, value] of Object.entries(overrides)) { + if (value !== '') args[key] = value + } + return args + } + + // The check beside Run: validate on load and after each pause in the + // editing, with `sizes=false` so typing never asks the hub; once the form + // has sat idle a while, one more check with sizes fills in download GB. + // It only informs - Run stays enabled, and the server stays the gate. + /** The quiet after the last change before checking again. */ + const CHECK_AFTER_MS = 600 + /** The idle time before the one check that asks the hub for sizes. */ + const SIZES_AFTER_MS = 3000 + + let validation = $state(null) + /** A check the server refused outright (an unknown name, a 400). */ + let checkError = $state('') + let checking = $state(false) + // Not state: bookkeeping for which answer is still wanted + let checkTimer: ReturnType | undefined + let sizesTimer: ReturnType | undefined + let checkController: AbortController | null = null + /** Bumped by every change: an answer from before the latest is dropped. */ + let generation = 0 + /** The latest call applied within this generation - a quick answer that + * lands after the sizes one does not overwrite it. */ + let appliedCall = 0 + let callCount = 0 + let checkedFor = '' + + function stopChecks() { + clearTimeout(checkTimer) + clearTimeout(sizesTimer) + checkController?.abort() + checkController = null + } + + function scheduleChecks(delay: number) { + stopChecks() + generation += 1 + appliedCall = 0 + checkController = new AbortController() + checkTimer = setTimeout(() => check(false), delay) + sizesTimer = setTimeout(() => check(true), SIZES_AFTER_MS) + } + + async function check(sizes: boolean) { + const mine = generation + const call = ++callCount + const signal = checkController?.signal + checking = true + try { + const answer = await api.validate( + { workflow_path: name, arguments: runArguments(), sizes }, + signal, + ) + if (mine !== generation || call < appliedCall) return + appliedCall = call + validation = answer + checkError = '' + } catch (e) { + if (mine !== generation || call < appliedCall) return + if (e instanceof DOMException && e.name === 'AbortError') return + appliedCall = call + validation = null + checkError = e instanceof Error ? e.message : String(e) + } finally { + if (mine === generation) checking = false + } + } + + $effect(() => { + if (!workflow) { + // Another workflow is loading: nothing asked about the last one is + // wanted any more + stopChecks() + generation += 1 + checkedFor = '' + checking = false + return + } + // Reading every override is what makes this re-run on each change + const asked = JSON.stringify(runArguments()) + const key = `${name}\n${asked}` + if (key === checkedFor) return + const first = !checkedFor.startsWith(`${name}\n`) + checkedFor = key + if (first) { + validation = null + checkError = '' + } + scheduleChecks(first ? 0 : CHECK_AFTER_MS) + }) + + onDestroy(stopChecks) + + const placed = $derived( + placeFindings( + validation, + variables.map(([key]) => key), + ), + ) + const planLines = $derived( + validation?.plan ? describePlan(validation.plan) : [], + ) + const verdict = $derived.by(() => { + if (checkError) return { tone: 'bad', text: 'could not check this run' } + if (!validation) return null + if (!validation.valid) + return { tone: 'bad', text: 'a run would be refused' } + if (validation.warnings.length) { + return { tone: 'warn', text: 'a run would be admitted, with warnings' } + } + return { tone: 'good', text: 'a run would be admitted' } + }) + function newFrom() { if (!workflow) return sessionStorage.setItem('dw-editor-import', JSON.stringify(workflow)) @@ -124,15 +253,11 @@ submitting = true error = '' try { - const args: Record = {} - for (const [key, value] of Object.entries(overrides)) { - if (value !== '') args[key] = value - } const job = await api.submitJob({ // By name, not by composed path: the server resolves a name across // every source it can read, so an example runs where it lives workflow_path: name, - arguments: args, + arguments: runArguments(), }) goWs('jobs', job.id) } catch (e) { @@ -198,6 +323,37 @@ {#if error}

{error}

{/if} {#if workflow} + +
+
+ {#if verdict} + {verdict.text} + {/if} + {#if checking}checking…{/if} +
+ {#if planLines.length} +
    + {#each planLines as line, i (i)} +
  • {line.text}
  • + {/each} +
+ {/if} + {#if checkError || placed.general.length} +
    + {#if checkError}
  • {checkError}
  • {/if} + {#each placed.general as finding, i (i)} +
  • {finding.text}
  • + {/each} +
+ {/if} +
+ {#if workflow.description}
@@ -253,6 +409,7 @@ requiredVariables={requiredVariables(workflow)} constraints={constraintHints(workflow)} presets={workflow.presets} + findings={placed.byVariable} />
{:else} @@ -366,6 +523,46 @@ .error { color: var(--bad); } + /* The check beside Run: the verdict, then the plan in mono (figures the + engine resolves), then what validate said that names no field */ + .check { + margin-bottom: var(--space-4); + font-size: var(--t-sm); + } + .verdict { + display: flex; + gap: var(--space-3); + align-items: baseline; + } + .good { + color: var(--good); + } + .warn { + color: var(--warn); + } + .bad { + color: var(--bad); + } + .plan { + list-style: none; + margin: var(--space-2) 0 0; + padding: 0; + font-family: var(--font-mono); + font-size: var(--t-xs); + color: var(--muted); + display: flex; + flex-wrap: wrap; + gap: 0.2rem var(--space-3); + } + .plan .warn { + color: var(--warn); + } + .findings { + list-style: none; + margin: var(--space-2) 0 0; + padding: 0; + overflow-wrap: anywhere; + } .desc { margin: 0 0 var(--space-4); } diff --git a/ui/src/lib/pages/WorkflowPage.test.ts b/ui/src/lib/pages/WorkflowPage.test.ts new file mode 100644 index 000000000..7a97c677c --- /dev/null +++ b/ui/src/lib/pages/WorkflowPage.test.ts @@ -0,0 +1,286 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/svelte' +import { tick } from 'svelte' +import WorkflowPage from './WorkflowPage.svelte' +import { api } from '../api' +import { notify } from '../toast' +import type { ValidationResult } from '../types' + +// Monaco cannot boot in jsdom, and this page only mounts it on "show JSON" +vi.mock('../editor/JsonEditor.svelte', async () => ({ + default: (await import('./JsonEditorStub.svelte')).default, +})) + +vi.mock('../toast', () => ({ + notify: { error: vi.fn(), success: vi.fn(), dismiss: vi.fn() }, +})) + +const valid: ValidationResult = { + valid: true, + error: null, + errors: [], + warnings: [], + plan: { + fingerprint: 'sha256:abc', + steps: 1, + list_entries: {}, + cached_steps: 0, + downloads_required: [], + estimate: { + minutes: 2, + basis: 'catalog', + device: 'mps', + measured_on: 'card', + partial: false, + }, + }, +} as unknown as ValidationResult + +vi.mock('../api', () => ({ + api: { + getWorkflow: vi.fn(), + listWorkflows: vi.fn().mockResolvedValue({ + workflows: [], + details: {}, + libraries: [], + shadowed: [], + }), + gallery: vi.fn().mockResolvedValue({ files: [] }), + listPrompts: vi.fn().mockResolvedValue({ prompts: [], details: {} }), + validate: vi.fn(), + submitJob: vi.fn(), + workflowDownloadUrl: vi.fn().mockReturnValue('/download'), + galleryThumbnailUrl: vi.fn().mockReturnValue('/thumb'), + }, +})) + +const definition = { + id: 'TextToImage', + variables: { prompt: 'a cat', num_images_per_prompt: 1, seed: 0 }, + steps: [{ name: 'generate', pipeline: {} }], +} + +/** Let pending promises and the renders they cause land, moving the fake + * clock by `ms` first. */ +async function advance(ms = 0) { + await vi.advanceTimersByTimeAsync(ms) + await tick() +} + +const field = (name: string) => + document.getElementById(`var-${name}`) as HTMLTextAreaElement + +async function type(name: string, value: string) { + await fireEvent.input(field(name), { target: { value } }) +} + +const validateCalls = () => vi.mocked(api.validate).mock.calls + +async function openPage() { + render(WorkflowPage, { name: 'templates/text-to-image' }) + await advance() + await advance() +} + +beforeEach(() => { + vi.useFakeTimers() + vi.mocked(api.getWorkflow).mockResolvedValue({ + definition, + origin: 'examples', + writable: false, + } as never) + vi.mocked(api.validate).mockReset() + vi.mocked(api.validate).mockResolvedValue(valid) + vi.mocked(api.submitJob).mockReset() + vi.mocked(notify.error).mockReset() +}) + +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +describe('WorkflowPage run check', () => { + it('validates on load by name, without sizes, and shows the plan', async () => { + await openPage() + expect(validateCalls()).toHaveLength(1) + expect(validateCalls()[0][0]).toEqual({ + workflow_path: 'templates/text-to-image', + arguments: {}, + sizes: false, + }) + const plan = screen.getByLabelText('what a run will do') + expect(plan.textContent).toContain('~2 min on mps') + expect(screen.getByText('a run would be admitted')).toBeTruthy() + }) + + it('asks about exactly the arguments Run sends, blanks dropped', async () => { + vi.mocked(api.submitJob).mockResolvedValue({ id: 'job-1' } as never) + await openPage() + await type('prompt', 'a dog') + await type('seed', '') + await advance(600) + const asked = validateCalls().at(-1)![0] as { arguments: unknown } + expect(asked.arguments).toEqual({ prompt: 'a dog' }) + + await fireEvent.click(screen.getByRole('button', { name: /Run/ })) + await advance() + expect(vi.mocked(api.submitJob).mock.calls[0][0]).toEqual({ + workflow_path: 'templates/text-to-image', + arguments: asked.arguments, + }) + }) + + it('checks once per pause, and asks for sizes only after 3 s idle', async () => { + await openPage() + vi.mocked(api.validate).mockClear() + for (const value of ['a', 'a d', 'a do', 'a dog']) { + await type('prompt', value) + await advance(200) + } + expect(validateCalls()).toHaveLength(0) + await advance(400) + expect(validateCalls()).toHaveLength(1) + expect(validateCalls()[0][0]).toMatchObject({ sizes: false }) + await advance(1500) + expect(validateCalls()).toHaveLength(1) + await advance(1100) + expect(validateCalls()).toHaveLength(2) + expect(validateCalls()[1][0]).toMatchObject({ + sizes: true, + arguments: { prompt: 'a dog' }, + }) + }) + + it('drops an answer from before the latest change, a late sizes one too', async () => { + const refusal = { + ...valid, + valid: false, + plan: undefined, + errors: [{ path: 'arguments.seed', message: 'stale refusal' }], + } as unknown as ValidationResult + let answerSizes: (result: ValidationResult) => void = () => {} + await openPage() + // the sizes check for the load fires, and hangs + vi.mocked(api.validate).mockImplementationOnce( + () => new Promise((resolve) => (answerSizes = resolve)), + ) + await advance(3000) + expect(validateCalls().at(-1)![0]).toMatchObject({ sizes: true }) + // the user changes a value before it answers + await type('seed', '7') + await advance(600) + // it answers now, after the change: not wanted + answerSizes(refusal) + await advance() + expect(screen.queryByText(/stale refusal/)).toBeNull() + expect(screen.getByText('a run would be admitted')).toBeTruthy() + // and the signal it was handed was aborted + const sizesCall = validateCalls().find( + (c) => (c[0] as { sizes?: boolean }).sizes === true, + )! + expect((sizesCall[1] as AbortSignal).aborted).toBe(true) + }) + + it('puts an arguments.x error under field x and the rest in the general list', async () => { + vi.mocked(api.validate).mockResolvedValue({ + valid: false, + error: 'refused', + errors: [ + { + path: 'arguments.num_images_per_prompt', + message: 'must be at most 8', + }, + { path: 'model_name', message: 'unknown model' }, + ], + warnings: [ + 'variables.seed[0]: a list where one value belongs', + 'cost estimate withheld: not priced from templates/x', + ], + } as unknown as ValidationResult) + await openPage() + + const underCount = document.querySelector( + '[data-findings-for="num_images_per_prompt"]', + )! + expect(underCount.textContent).toContain('must be at most 8') + const underSeed = document.querySelector('[data-findings-for="seed"]')! + expect(underSeed.textContent).toContain( + '[0]: a list where one value belongs', + ) + + const general = screen.getByLabelText('findings') + expect(general.textContent).toContain('model_name: unknown model') + expect(general.textContent).toContain( + 'cost estimate withheld: not priced from templates/x', + ) + expect(general.textContent).not.toContain('must be at most 8') + expect(general.querySelector('.bad')!.textContent).toContain('model_name') + expect(general.querySelector('.warn')!.textContent).toContain('withheld') + expect(screen.getByText('a run would be refused')).toBeTruthy() + }) + + it('clears a field error once the value is fixed', async () => { + vi.mocked(api.validate).mockResolvedValueOnce(valid) + await openPage() + vi.mocked(api.validate).mockResolvedValueOnce({ + valid: false, + error: 'refused', + errors: [{ path: 'arguments.seed', message: 'not an integer' }], + warnings: [], + } as unknown as ValidationResult) + await type('seed', 'x') + await advance(600) + expect( + document.querySelector('[data-findings-for="seed"]')!.textContent, + ).toContain('not an integer') + await type('seed', '3') + await advance(600) + expect(document.querySelector('[data-findings-for="seed"]')).toBeNull() + }) + + it('keeps Run enabled with errors present, and a refused Run still toasts', async () => { + vi.mocked(api.validate).mockResolvedValue({ + valid: false, + error: 'refused', + errors: [{ path: 'arguments.seed', message: 'not an integer' }], + warnings: [], + } as unknown as ValidationResult) + vi.mocked(api.submitJob).mockRejectedValue( + new Error('seed: not an integer'), + ) + await openPage() + const runButton = screen.getByRole('button', { name: /Run/ }) + expect((runButton as HTMLButtonElement).disabled).toBe(false) + await fireEvent.click(runButton) + await advance() + expect(notify.error).toHaveBeenCalledWith('seed: not an integer') + }) + + it('keeps Run enabled while a check is in flight', async () => { + vi.mocked(api.validate).mockImplementation(() => new Promise(() => {})) + await openPage() + const runButton = screen.getByRole('button', { name: /Run/ }) + expect((runButton as HTMLButtonElement).disabled).toBe(false) + }) + + it('renders hostile finding text as text', async () => { + vi.mocked(api.validate).mockResolvedValue({ + ...valid, + warnings: [' warned'], + } as unknown as ValidationResult) + await openPage() + const general = screen.getByLabelText('findings') + expect(general.textContent).toContain('') + expect(general.querySelector('img')).toBeNull() + }) + + it('names a check the server refused outright in the general list', async () => { + vi.mocked(api.validate).mockRejectedValue(new Error('unknown workflow')) + await openPage() + expect(screen.getByLabelText('findings').textContent).toContain( + 'unknown workflow', + ) + }) +}) From 0295282618a4b60a5bcf85f9bbdb11c7a858f0a8 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 06:42:11 -0600 Subject: [PATCH 254/412] feat(ui): #1468 - spell the validate route once, so the contract scan reads its POST Co-Authored-By: Claude Opus 5.5 --- ui/src/lib/api.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 9400fd4ac..23e605ec6 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -143,7 +143,7 @@ function archiveFrom(path: string) { }) } -/** What `/api/validate` is asked: exactly one of an inline `workflow` or a +/** What the validate route is asked: exactly one of an inline `workflow` or a * `workflow_path` (a catalog name), the `arguments` a run would carry, and * `sizes: false` to skip asking the hub how large a missing model is. */ export type ValidateRequest = { @@ -424,10 +424,9 @@ export const api = { ? input : { workflow: input } const { sizes, ...body } = asked - const path = - sizes === false - ? appendQuery('/api/validate', 'sizes', 'false') - : '/api/validate' + // one literal, so tests/test_ui_twins.py reads the route with its POST + const route = '/api/validate' + const path = sizes === false ? appendQuery(route, 'sizes', 'false') : route return request(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, From b56f3fc2864e3311df8508be11719a1de15b1be9 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 06:58:53 -0600 Subject: [PATCH 255/412] feat(ui): #1473 - job rows show their reason; a restart banner reruns its batch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - the jobs list puts a failed or cancelled row's reason on its own muted, ellipsized line under the workflow name, the full text in its title - a banner per server restart whose tombstones no loaded row reruns, newest first, hidden under a status filter that hides cancelled rows; Rerun… previews the batch route with {} (never from the poll), lists what would queue with each estimate and a total and what is skipped, and queues only on confirm with acknowledged_cost; an empty preview says so with Close only and hides that banner for the session - api.rerunRestartBatch, the RestartBatchRerun alias, the route in UI_READ_ROUTES; plan.ts gains describeEstimate / describeEstimateTotal - the confirm dialog gains a single-button alert mode, and its message scrolls past 60vh - the e2e fixture seeds two restart tombstones; a Playwright spec opens the preview and cancels - SERVER.md jobs bullet, ARCHITECTURE.md consent row, release note Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 2 +- docs/RELEASING.md | 6 + docs/SERVER.md | 2 +- tests/test_api_contract.py | 1 + ui/e2e/restart-banner.spec.ts | 32 +++++ ui/e2e/serve_fixture.py | 35 ++++- ui/src/app.css | 4 + ui/src/lib/api.ts | 16 +++ ui/src/lib/confirm.svelte.ts | 6 +- ui/src/lib/pages/JobsPage.svelte | 202 ++++++++++++++++++--------- ui/src/lib/pages/JobsPage.test.ts | 212 ++++++++++++++++++++++++++++- ui/src/lib/plan.test.ts | 61 ++++++++- ui/src/lib/plan.ts | 76 +++++++++-- ui/src/lib/restartBatches.ts | 103 ++++++++++++++ ui/src/lib/types.ts | 1 + ui/src/lib/ui/ConfirmDialog.svelte | 8 +- 16 files changed, 678 insertions(+), 89 deletions(-) create mode 100644 ui/e2e/restart-banner.spec.ts create mode 100644 ui/src/lib/restartBatches.ts diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a3a2e3abf..8e00bc3ef 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -213,7 +213,7 @@ one to open. | Tool surface | `dw_mcp/server.py`, `dw_mcp/tools_*.py` | Only these modules import the MCP SDK, and each tool body is a one-line call into a handler. | `tests/test_mcp_server.py::test_the_wiring_table_covers_every_registered_tool`, `tests/test_mcp_server.py::test_the_stated_tool_count_is_the_registered_one` | | Surface text budget | the tool docstrings in `dw_mcp/tools_*.py`, the instructions in `dw_mcp/server.py` | The instructions and each tool description stay at or under 2,048 characters, and the whole surface stays within its token budget. | `tests/test_mcp_server.py`: `SURFACE_BUDGET`, `CLIENT_TEXT_LIMIT`; `tests/test_mcp_server.py::test_no_text_the_agent_reads_is_cut_off_by_the_client`, `tests/test_mcp_server.py::test_the_tool_surface_fits_the_budget` | | Guide pointers in resident text | the tool docstrings in `dw_mcp/tools_*.py`, the instructions in `dw_mcp/server.py`, each plugin `SKILL.md` and its `references/` | Every `get_guide(...)` / guide-section pointer opens a real section through `dw/server/guides.py`'s `get_guide`, and the tools that point at a guide keep their pointer when text is trimmed to fit the budget. | `tests/test_guide_pointers.py` (`TOOLS_THAT_POINT`) | -| Spending needs consent | each handler behind a tool that takes `acknowledged_cost` (`dw_mcp/diagnose.py`, `models.py`, `prompts.py`, `workspaces.py`) | Every tool that takes `acknowledged_cost` refuses until it is set; `delete_workspace`'s refusal is the server's 409. `rerun_job(restart_batch=true)` passes through without it, and the server owns that gate: `POST /api/jobs/{id}/rerun-restart-batch` (`JobManager.rerun_restart_batch`) answers a preview that queues nothing. | `tests/test_mcp_twins.py::test_every_tool_that_takes_acknowledged_cost_refuses_without_it`, `tests/test_restart_tombstones.py::test_mcp_rerun_job_previews_queues_then_skips_a_restart_batch` | +| Spending needs consent | each handler behind a tool that takes `acknowledged_cost` (`dw_mcp/diagnose.py`, `models.py`, `prompts.py`, `workspaces.py`) | Every tool that takes `acknowledged_cost` refuses until it is set; `delete_workspace`'s refusal is the server's 409. `rerun_job(restart_batch=true)` passes through without it, and the server owns that gate: `POST /api/jobs/{id}/rerun-restart-batch` (`JobManager.rerun_restart_batch`) answers a preview that queues nothing. The jobs page's restart banner is the route's second caller and keeps the same order: a click previews, and only a confirm sends `acknowledged_cost` (`ui/src/lib/restartBatches.ts`). | `tests/test_mcp_twins.py::test_every_tool_that_takes_acknowledged_cost_refuses_without_it`, `tests/test_restart_tombstones.py::test_mcp_rerun_job_previews_queues_then_skips_a_restart_batch`, `ui/src/lib/pages/JobsPage.test.ts` | | Copies of engine rules | the constants and word lists in `dw_mcp/` and `dw/run.py` | `dw_mcp` cannot import its owners, so each copy equals its owner; a copy that needs no twin is deleted, not pinned. | `tests/test_mcp_twins.py` | | The CLI is a client of the server | `dw/run.py` | `dw.run` queues on `dw.serve` through `dw_mcp.client`, so `dw` imports `dw_mcp` and never the reverse. | `tests/test_mcp_server.py::TestStartupWeight::test_the_server_starts_without_importing_the_engine`, `tests/test_mcp_twins.py` | | Inline images | `dw/server/inline_media.py` | Fitting an image to a longest side and halving it under a base64 budget happens on the server, for `/image` and `/frames` alike; `dw_mcp` forwards the size and budget and imports no Pillow. | `tests/test_server_gallery_image.py`, `tests/test_mcp_server.py::TestStartupWeight::test_the_server_starts_without_importing_the_engine` | diff --git a/docs/RELEASING.md b/docs/RELEASING.md index dadc4ca26..341113b4d 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -57,6 +57,12 @@ GitHub generates notes from commits at tag time. The sections below are the hand without a `get_job` per row. A restart tombstone also carries `restart_batch`, the key its batch groups by, for `rerun_job(restart_batch=true)`. Both are optional and additive. +- **The jobs page shows the reason, and offers a restart's jobs back + (#1449).** Each failed or cancelled row shows its reason under the + workflow name. Jobs a server restart cancelled raise a banner per restart, + "N jobs were cancelled by a server restart", whose **Rerun…** previews what + would be queued, with each estimate and a total, and queues only on + confirm. - **diffusers floor raised to 0.43.0 (#1315).** `pyproject.toml` now requires `diffusers>=0.43.0` (was `>=0.42.0`), the release develop's code needs. The Models page / REST "revert to a known-good release" now diff --git a/docs/SERVER.md b/docs/SERVER.md index 180976e7f..2db55a2de 100644 --- a/docs/SERVER.md +++ b/docs/SERVER.md @@ -203,7 +203,7 @@ icon, a finish-alert toggle, the theme toggle, and links to these docs and not a restart tombstone, or one closed before #1245 recorded the instance, is a 400, and a bound acknowledgement is refused; each server holds a lock under `servers/` beside the database for its life, so a second server - sharing the database leaves a live sibling's jobs alone), filterable by status; a waiting job + sharing the database leaves a live sibling's jobs alone), filterable by status. A failed or cancelled row shows its `reason` on a muted line under the workflow name, cut to one line with the full text on hover. When loaded rows hold restart tombstones (`restart_batch`) that no loaded row's `rerun_of` names, a banner per batch, newest first, says "N jobs were cancelled by a server restart" with a **Rerun…** button (hidden under a status filter that hides cancelled rows). Only the click calls the batch route - the poll never does: its preview lists what would be queued with each estimate and a total, and what is skipped with why; confirming resends with `acknowledged_cost: true`, cancelling queues nothing, and a preview with nothing left to rerun says so and hides that banner for the session (`ui/src/lib/restartBatches.ts`). A waiting job shows its place in line, can be moved, and shows `waiting_for` while held (for host RAM, or because every card is busy): the jobs list adds a short reason (`· host RAM` / `· cards busy`) to the queued row with the full text on hover, and the job page's hover matches the hold. The job page also refetches on `queue_wait` and on a live `warning`, and shows a warn-tone stall line (`no event for 4m in loading`) from the latest `phase_stall` until another event arrives. A job's page streams step progress, denoise ticks, the phase between them (loading, decoding, saving; a model download shows its bytes and rate), its log, and its results as they diff --git a/tests/test_api_contract.py b/tests/test_api_contract.py index 7f7aca78d..7581af81b 100644 --- a/tests/test_api_contract.py +++ b/tests/test_api_contract.py @@ -164,6 +164,7 @@ def test_the_committed_document_is_current(): ("delete", "/api/jobs/{job_id}/run"), ("get", "/api/jobs/{job_id}/workflow"), ("post", "/api/jobs/{job_id}/rerun"), + ("post", "/api/jobs/{job_id}/rerun-restart-batch"), ("post", "/api/jobs/{job_id}/export"), ("post", "/api/jobs/{job_id}/move"), ("post", "/api/jobs/{job_id}/cancel"), diff --git a/ui/e2e/restart-banner.spec.ts b/ui/e2e/restart-banner.spec.ts new file mode 100644 index 000000000..fd6e14c42 --- /dev/null +++ b/ui/e2e/restart-banner.spec.ts @@ -0,0 +1,32 @@ +import { expect, test } from '@playwright/test' + +// The fixture seeds two jobs a dead server's restart cancelled before they +// started, sharing its instance id (#1473). The page offers them back as one +// batch; the click previews what a rerun would queue, and cancelling queues +// nothing. +test('a restart banner previews the batch it offers to rerun', async ({ + page, +}) => { + await page.goto('/#/ws/default/jobs') + const banner = page.locator('.restart') + await expect(banner).toHaveCount(1) + await expect(banner).toContainText( + '2 jobs were cancelled by a server restart', + ) + // each tombstone's row carries the reason under its name + await expect( + page.locator('.reason', { hasText: 'server restart:' }), + ).toHaveCount(2) + + await banner.getByRole('button', { name: 'Rerun…' }).click() + const dialog = page.getByRole('alertdialog') + await expect(dialog).toBeVisible() + // both members are listed - to queue, or skipped with a reason + await expect(dialog).toContainText('e2erestart01') + await expect(dialog).toContainText('e2erestart02') + await dialog.getByRole('button', { name: 'Cancel' }).click() + await expect(dialog).toHaveCount(0) + // nothing was queued: the banner still stands and no rerun row appeared + await expect(banner).toHaveCount(1) + await expect(page.locator('[title^="a rerun of"]')).toHaveCount(0) +}) diff --git a/ui/e2e/serve_fixture.py b/ui/e2e/serve_fixture.py index b6886da25..cc4885fed 100644 --- a/ui/e2e/serve_fixture.py +++ b/ui/e2e/serve_fixture.py @@ -20,7 +20,9 @@ import os import base64 +import json import shutil +import sqlite3 import sys import tempfile @@ -52,7 +54,38 @@ with open(os.path.join(run_dir, "still.png"), "wb") as handle: handle.write(ONE_PIXEL_PNG) -os.environ["DIFFUSERS_HELPER_ROOT"] = os.path.join(scratch, "helper") +helper = os.path.join(scratch, "helper") +os.environ["DIFFUSERS_HELPER_ROOT"] = helper + +# Two jobs a dead server's restart cancelled before they started: the +# tombstones the jobs page offers to rerun as one batch (#1473). They share +# the dead server's instance id, which is what groups them. The schema is the +# server's own, created through JobHistory, so the rows carry every column a +# real tombstone has. +sys.path.insert(0, root) +from dw.server.job_history import JobHistory # noqa: E402 +from dw.server.job_record import RESTART_PREFIX # noqa: E402 + +os.makedirs(helper, exist_ok=True) +history_db = os.path.join(helper, "jobs.sqlite") +JobHistory(history_db) +template = os.path.join(scratch, "workflows", "templates", "text-to-image.json") +with sqlite3.connect(history_db) as connection: + for index, job_id in enumerate(("e2erestart01", "e2erestart02")): + connection.execute( + "INSERT INTO jobs (id, workflow, status, created_at, finished_at," + " arguments, spec, error, events, workspace, server_instance)" + " VALUES (?, ?, 'cancelled', ?, ?, '{}', ?, ?, '[]', 'default', ?)", + ( + job_id, + "text-to-image", + 1767225600.0 + index, + 1767225660.0, + json.dumps({"workflow_path": template, "workspace": "default"}), + f"{RESTART_PREFIX} queued, never started", + "e2e-dead-server", + ), + ) os.chdir(root) os.execv( diff --git a/ui/src/app.css b/ui/src/app.css index 33f805135..314c2c75d 100644 --- a/ui/src/app.css +++ b/ui/src/app.css @@ -581,6 +581,10 @@ button.frame:hover { .ui-message { margin: 0 0 var(--space-4); white-space: pre-line; + /* a long message - a batch's every member - scrolls inside the sheet + rather than pushing its buttons off the screen */ + max-height: 60vh; + overflow-y: auto; } .ui-actions { display: flex; diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 23e605ec6..f933508e2 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -32,6 +32,7 @@ import type { PromptDefinition, PromptList, PromptSaved, + RestartBatchRerun, ServerInfo, StoredPrompt, TaskList, @@ -222,6 +223,21 @@ export const api = { : { new_seed: newSeed }, ), }), + /** Rerun every job one dead server's restart cancelled, naming any one of + * them. Without `acknowledged` it is a priced preview - `would_queue` and + * `skipped` - and queues nothing; with it the batch is queued. Every + * member is priced, so only a click calls this, never a poll. Unscoped: + * a batch can span workspaces and the route needs no workspace. */ + rerunRestartBatch: (id: string, acknowledged = false) => + request( + `/api/jobs/${id}/rerun-restart-batch`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(acknowledged ? { acknowledged_cost: true } : {}), + }, + { scope: false }, + ), listTasks: () => request('/api/tasks'), listBuiltinWorkflows: () => request('/api/builtin-workflows'), diff --git a/ui/src/lib/confirm.svelte.ts b/ui/src/lib/confirm.svelte.ts index 3bd2e4ebd..277e7e700 100644 --- a/ui/src/lib/confirm.svelte.ts +++ b/ui/src/lib/confirm.svelte.ts @@ -9,6 +9,8 @@ type ConfirmState = { message: string confirmLabel: string cancelLabel: string + // A notice with one button: nothing to choose between, so no Cancel + alert: boolean } export const confirmState = $state({ @@ -16,6 +18,7 @@ export const confirmState = $state({ message: '', confirmLabel: 'OK', cancelLabel: 'Cancel', + alert: false, }) // At most one confirm is ever in flight - a second call while one is open @@ -24,12 +27,13 @@ let resolver: ((value: boolean) => void) | null = null export function confirmDialog( message: string, - options?: { confirmLabel?: string; cancelLabel?: string }, + options?: { confirmLabel?: string; cancelLabel?: string; alert?: boolean }, ): Promise { confirmState.open = true confirmState.message = message confirmState.confirmLabel = options?.confirmLabel ?? 'OK' confirmState.cancelLabel = options?.cancelLabel ?? 'Cancel' + confirmState.alert = options?.alert ?? false return new Promise((resolve) => { resolver = resolve }) diff --git a/ui/src/lib/pages/JobsPage.svelte b/ui/src/lib/pages/JobsPage.svelte index a0fb2a731..6d01c82d0 100644 --- a/ui/src/lib/pages/JobsPage.svelte +++ b/ui/src/lib/pages/JobsPage.svelte @@ -12,6 +12,11 @@ import { wsHref } from '../routes' import { hashQuery, setHashQuery } from '../router.svelte' import { loadWorkspaces, workspace } from '../workspace.svelte' + import { + rerunRestartBatchWithConfirm, + restartBanners, + type RestartBanner, + } from '../restartBatches' let { scope = 'workspace' }: { scope?: 'workspace' | 'all' } = $props() @@ -85,6 +90,32 @@ }, 3000) }) + // Batches a preview found nothing left to rerun in: their banner stays + // hidden for the rest of the session, in memory only - the client's + // count is an estimate and the preview corrected it + let dismissedBatches = $state(new Set()) + let previewing = $state('') + // All of a scope's rows, not the name-filtered ones: a batch spans + // workflows. A status filter that hides cancelled rows hides it too + const banners = $derived( + statusFilter && statusFilter !== 'cancelled' + ? [] + : restartBanners(jobs, dismissedBatches), + ) + + // Only a click previews: the preview prices every member of the batch, + // which the 3 s poll must never pay for + async function rerunBatch(banner: RestartBanner) { + previewing = banner.batch + try { + const outcome = await rerunRestartBatchWithConfirm(banner.id) + if (outcome === 'empty') + dismissedBatches = new Set([...dismissedBatches, banner.batch]) + } finally { + previewing = '' + } + } + const queuedCount = $derived( jobs.filter((job) => job.queue_position !== undefined).length, ) @@ -157,6 +188,20 @@ {#if error}

Could not reach the server: {error}

{/if} +{#each banners as banner (banner.batch)} +
+ {`${banner.count} ${banner.count === 1 ? 'job was' : 'jobs were'} cancelled by a server restart`} + +
+{/each} + {#if jobs.length === 0 && !filtered} {#snippet icon()}{/snippet} @@ -180,71 +225,77 @@ : ''} > {job.status} - - {job.workflow} - {#if job.run_version} - v{job.run_version} - {/if} - {#if job.rerun_of} - rerun - {/if} - {#if scope === 'all' && (workspace.names?.length ?? 0) > 1} - {job.workspace} - {/if} - {#if job.device} - {job.device} - {/if} - {#if job.acknowledged === 'bound'} - acknowledged - {/if} - {#if job.queue_position !== undefined} - #{job.queue_position + 1} - {#if queuedCount > 1} - - {#if job.queue_position > 0} - - - {/if} - {#if job.queue_position < queuedCount - 1} - - {/if} - + + + {job.workflow} + {#if job.run_version} + v{job.run_version} + {/if} + {#if job.rerun_of} + rerun + {/if} + {#if scope === 'all' && (workspace.names?.length ?? 0) > 1} + {job.workspace} {/if} + {#if job.device} + {job.device} + {/if} + {#if job.acknowledged === 'bound'} + acknowledged + {/if} + {#if job.queue_position !== undefined} + #{job.queue_position + 1} + {#if queuedCount > 1} + + {#if job.queue_position > 0} + + + {/if} + {#if job.queue_position < queuedCount - 1} + + {/if} + + {/if} + {/if} + + {#if job.reason} + {job.reason} {/if} {#if job.status === 'queued'} @@ -333,6 +384,29 @@ .row.historical { opacity: 0.72; } + /* The name and, under it, why a failed or cancelled job ended - each its + own element, so a later line beside the reason is a sibling */ + .namecol { + display: flex; + flex-direction: column; + gap: 0.15rem; + min-width: 0; + } + .reason { + font-size: var(--t-xs); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .restart { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + padding: 0.55rem 0.8rem; + margin-bottom: 0.6rem; + box-shadow: inset 3px 0 0 var(--warn); + } /* A workflow name is what the engine resolved to run this job */ .name { font-family: var(--font-mono); diff --git a/ui/src/lib/pages/JobsPage.test.ts b/ui/src/lib/pages/JobsPage.test.ts index 676dfbda8..5072e9756 100644 --- a/ui/src/lib/pages/JobsPage.test.ts +++ b/ui/src/lib/pages/JobsPage.test.ts @@ -10,9 +10,14 @@ import JobsPage from './JobsPage.svelte' import { formatExact } from '../format' import type { JobSummary } from '../types' -const data = vi.hoisted(() => ({ jobs: [] as unknown[] })) +const data = vi.hoisted(() => ({ + jobs: [] as unknown[], + rerunRestartBatch: vi.fn(), + confirm: vi.fn(), +})) vi.mock('../api', () => ({ api: { + rerunRestartBatch: data.rerunRestartBatch, listJobs: () => Promise.resolve({ jobs: [...data.jobs], total: data.jobs.length }), // The listing names the default workspace, as the server's always does: @@ -24,9 +29,14 @@ vi.mock('../api', () => ({ }), }, })) +vi.mock('../confirm.svelte', () => ({ confirmDialog: data.confirm })) vi.mock('../toast', () => ({ notify: { error: vi.fn(), success: vi.fn() } })) -afterEach(cleanup) +afterEach(() => { + cleanup() + data.rerunRestartBatch.mockReset() + data.confirm.mockReset() +}) const summary = (over: Partial): JobSummary => ({ id: 'j', @@ -186,3 +196,201 @@ it('adds the hold reason to a queued row that has waiting_for', async () => { ) expect(container.textContent?.match(/·/g)).toHaveLength(2) }) + +it("puts a row's reason on its own line, with the full text in its title", async () => { + const reason = 'server restart: queued, never started (a long tail of text)' + data.jobs = [ + summary({ id: 'c1', workflow: 'gone', status: 'cancelled', reason }), + summary({ id: 'ok', workflow: 'fine' }), + ] + const { container } = render(JobsPage) + await waitFor(() => expect(screen.getByText('gone')).toBeTruthy()) + const line = container.querySelector('.reason') as HTMLElement + expect(line.textContent).toBe(reason) + expect(line.title).toBe(reason) + // its own element, a sibling of the name, not text inside it + expect(line.closest('.name')).toBeNull() + expect(container.querySelectorAll('.reason')).toHaveLength(1) +}) + +const tombstone = (id: string, batch: string, created = 1) => + summary({ + id, + workflow: 'w-' + id, + status: 'cancelled', + reason: 'server restart: queued, never started', + restart_batch: batch, + created_at: created, + }) + +const banners = (container: HTMLElement) => + [...container.querySelectorAll('.restart')] as HTMLElement[] + +it('shows a restart banner for tombstones nothing has rerun', async () => { + data.jobs = [tombstone('t1', 'dead-a'), tombstone('t2', 'dead-a')] + const { container } = render(JobsPage) + await waitFor(() => expect(banners(container)).toHaveLength(1)) + expect(banners(container)[0].textContent).toContain( + '2 jobs were cancelled by a server restart', + ) + expect(screen.getByText('Rerun…')).toBeTruthy() +}) + +it('hides the banner once every tombstone has a rerun row', async () => { + data.jobs = [ + tombstone('t1', 'dead-a'), + tombstone('t2', 'dead-a'), + summary({ id: 'n1', workflow: 'again-1', rerun_of: 't1' }), + summary({ id: 'n2', workflow: 'again-2', rerun_of: 't2' }), + ] + const { container } = render(JobsPage) + await waitFor(() => expect(screen.getByText('again-2')).toBeTruthy()) + expect(banners(container)).toHaveLength(0) +}) + +it('shows no banner with no tombstones', async () => { + data.jobs = [ + summary({ id: 'c1', workflow: 'user-cancel', status: 'cancelled' }), + summary({ id: 'ok', workflow: 'fine' }), + ] + const { container } = render(JobsPage) + await waitFor(() => expect(screen.getByText('fine')).toBeTruthy()) + expect(banners(container)).toHaveLength(0) +}) + +it('shows one banner per batch, newest first', async () => { + data.jobs = [ + tombstone('old1', 'dead-old', 1), + tombstone('new1', 'dead-new', 10), + tombstone('new2', 'dead-new', 11), + ] + const { container } = render(JobsPage) + await waitFor(() => expect(banners(container)).toHaveLength(2)) + expect(banners(container).map((b) => b.dataset.batch)).toEqual([ + 'dead-new', + 'dead-old', + ]) + expect(banners(container)[0].textContent).toContain('2 jobs were') + expect(banners(container)[1].textContent).toContain('1 job was') +}) + +it('hides the banner under a status filter that hides cancelled rows', async () => { + location.hash = '#/ws/default/jobs?status=failed' + data.jobs = [ + tombstone('t1', 'dead-a'), + summary({ id: 'f1', workflow: 'broke', status: 'failed' }), + ] + const { container } = render(JobsPage) + await waitFor(() => expect(screen.getByText('broke')).toBeTruthy()) + expect(banners(container)).toHaveLength(0) + location.hash = '' +}) + +const preview = { + server_instance: 'dead-a', + queued: [], + would_queue: [ + { + id: 't1', + workflow: 'w-t1', + workspace: 'default', + estimate: { + basis: 'observed', + minutes: 2, + device: 'mps', + measured_on: 'Apple M2', + }, + }, + { id: 't2', workflow: 'w-t2', workspace: 'default', estimate: null }, + ], + skipped: [{ id: 't3', reason: 'its workspace is gone' }], +} + +it('previews on click with {} once, and the poll never calls the route', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }) + try { + data.jobs = [tombstone('t1', 'dead-a'), tombstone('t2', 'dead-a')] + data.rerunRestartBatch.mockResolvedValue(preview) + data.confirm.mockResolvedValue(false) + const { container } = render(JobsPage) + await waitFor(() => expect(banners(container)).toHaveLength(1)) + // several poll ticks with the banner up: no preview + await vi.advanceTimersByTimeAsync(10_000) + expect(data.rerunRestartBatch).not.toHaveBeenCalled() + await fireEvent.click(screen.getByText('Rerun…')) + await waitFor(() => expect(data.confirm).toHaveBeenCalledTimes(1)) + expect(data.rerunRestartBatch).toHaveBeenCalledTimes(1) + // any member names its batch; the call carries no acknowledgement + const [member, ...rest] = data.rerunRestartBatch.mock.calls[0] + expect(['t1', 't2']).toContain(member) + expect(rest).toEqual([]) + const message = data.confirm.mock.calls[0][0] as string + expect(message).toContain('w-t1 (t1, default) - ~2 min on mps') + expect(message).toContain('w-t2 (t2, default) - no estimate') + expect(message).toContain('total ~2 min, plus 1 with no figure') + expect(message).toContain('t3: its workspace is gone') + await vi.advanceTimersByTimeAsync(10_000) + expect(data.rerunRestartBatch).toHaveBeenCalledTimes(1) + } finally { + vi.useRealTimers() + } +}) + +it('confirming sends acknowledged_cost: true; cancelling sends nothing more', async () => { + data.jobs = [tombstone('t1', 'dead-a'), tombstone('t2', 'dead-a')] + data.rerunRestartBatch.mockResolvedValue(preview) + data.confirm.mockResolvedValue(false) + const { container } = render(JobsPage) + await waitFor(() => expect(banners(container)).toHaveLength(1)) + await fireEvent.click(screen.getByText('Rerun…')) + await waitFor(() => expect(data.confirm).toHaveBeenCalledTimes(1)) + // cancel: only the preview went out + expect(data.rerunRestartBatch).toHaveBeenCalledTimes(1) + const member = data.rerunRestartBatch.mock.calls[0][0] + expect(data.rerunRestartBatch.mock.calls).toEqual([[member]]) + + data.rerunRestartBatch.mockReset() + data.rerunRestartBatch.mockResolvedValueOnce(preview).mockResolvedValueOnce({ + ...preview, + would_queue: [], + queued: [ + { id: 'n1', rerun_of: 't1', workflow: 'w-t1', workspace: 'default' }, + { id: 'n2', rerun_of: 't2', workflow: 'w-t2', workspace: 'default' }, + ], + }) + data.confirm.mockResolvedValue(true) + await waitFor(() => + expect((screen.getByText('Rerun…') as HTMLButtonElement).disabled).toBe( + false, + ), + ) + await fireEvent.click(screen.getByText('Rerun…')) + await waitFor(() => expect(data.rerunRestartBatch).toHaveBeenCalledTimes(2)) + expect(data.rerunRestartBatch.mock.calls).toEqual([[member], [member, true]]) + const { notify } = await import('../toast') + await waitFor(() => + expect(notify.success).toHaveBeenCalledWith( + 'Queued 2; skipped 1: t3 (its workspace is gone)', + ), + ) +}) + +it('an empty preview says so, with Close only, and hides the banner', async () => { + data.jobs = [tombstone('t1', 'dead-a')] + data.rerunRestartBatch.mockResolvedValue({ + server_instance: 'dead-a', + queued: [], + would_queue: [], + skipped: [{ id: 't1', reason: 'already rerun as n9' }], + }) + data.confirm.mockResolvedValue(true) + const { container } = render(JobsPage) + await waitFor(() => expect(banners(container)).toHaveLength(1)) + await fireEvent.click(screen.getByText('Rerun…')) + await waitFor(() => expect(banners(container)).toHaveLength(0)) + const [message, options] = data.confirm.mock.calls[0] + expect(message).toContain('Nothing is left to rerun') + expect(options).toMatchObject({ confirmLabel: 'Close', alert: true }) + // only the preview: nothing was queued + expect(data.rerunRestartBatch.mock.calls).toEqual([['t1']]) +}) diff --git a/ui/src/lib/plan.test.ts b/ui/src/lib/plan.test.ts index 784d43ef4..e98209143 100644 --- a/ui/src/lib/plan.test.ts +++ b/ui/src/lib/plan.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { describePlan } from './plan' +import { describeEstimate, describeEstimateTotal, describePlan } from './plan' import type { Plan } from './types' const base: Plan = { @@ -347,7 +347,11 @@ describe('describePlan', () => { }) const [, reason] = describePlan({ ...base, - estimate: { ...unknown, inherited_from: undefined, unpriced_reason: 'no run here' }, + estimate: { + ...unknown, + inherited_from: undefined, + unpriced_reason: 'no run here', + }, }) expect(reason.text).toBe(`no figure - no run here - for ${card}`) const [, bare] = describePlan({ @@ -400,3 +404,56 @@ describe('describePlan', () => { }) }) }) + +describe('describeEstimate', () => { + it('reads one estimate as the plan figure does', () => { + expect(describeEstimate(base.estimate)).toEqual({ + text: '~42 min on cuda - measured on RTX 3090', + tone: 'plain', + }) + }) + + it('says an absent estimate is not a free one', () => { + expect(describeEstimate(null)).toEqual({ + text: 'no estimate', + tone: 'warn', + }) + }) + + it('an unpriced estimate keeps its reason', () => { + expect( + describeEstimate({ + ...base.estimate, + minutes: null, + basis: 'unknown', + unpriced_reason: 'no runs yet', + }).text, + ).toBe('no figure - no runs yet') + }) +}) + +describe('describeEstimateTotal', () => { + it('sums the priced minutes', () => { + expect( + describeEstimateTotal([ + base.estimate, + { ...base.estimate, minutes: 0.25 }, + ]), + ).toEqual({ text: 'total ~42.3 min', tone: 'plain' }) + }) + + it('says how many had no figure, so the total does not read as complete', () => { + expect( + describeEstimateTotal([ + base.estimate, + null, + { ...base.estimate, minutes: null, basis: 'unknown' }, + ]), + ).toEqual({ text: 'total ~42 min, plus 2 with no figure', tone: 'warn' }) + }) + + it('with nothing priced has no figure', () => { + expect(describeEstimateTotal([null]).text).toBe('total: no figure') + expect(describeEstimateTotal([]).text).toBe('total: nothing to run') + }) +}) diff --git a/ui/src/lib/plan.ts b/ui/src/lib/plan.ts index 8de68bd60..286224993 100644 --- a/ui/src/lib/plan.ts +++ b/ui/src/lib/plan.ts @@ -1,4 +1,9 @@ -import type { Plan, PlanHostMemory, RequiredDownload } from './types' +import type { + Plan, + PlanEstimate, + PlanHostMemory, + RequiredDownload, +} from './types' /** One line of a plan, read for a person: what it says and how loudly. * `warn` marks a figure that is not a quote (no cost block, a figure from @@ -27,7 +32,7 @@ export function describePlan(plan: Plan): PlanLine[] { tone: 'plain', }) - lines.push(figure(plan)) + lines.push(figure(plan.estimate, plan.list_entries)) if (plan.host_memory) lines.push(hostMemory(plan.host_memory)) @@ -99,20 +104,23 @@ function qualifiers(estimate: Plan['estimate']) { } } -function figure(plan: Plan): PlanLine { - const line = rawFigure(plan) - const { basis, minutes } = plan.estimate +function figure( + estimate: PlanEstimate, + listEntries: Plan['list_entries'], +): PlanLine { + const line = rawFigure(estimate, listEntries) + const { basis, minutes } = estimate // the lines that say no "on X" name the card the run dispatches to last, // so their own wording reads as it does without one const forCard = basis === 'unknown' || minutes === null || basis === 'inherited' - ? dispatchCard(plan.estimate) + ? dispatchCard(estimate) : '' if (basis === 'unknown' || minutes === null) { return { text: `${line.text}${forCard}`, tone: line.tone } } - const text = `${line.text}${tempered(plan.estimate)}` - return plan.estimate.low_confidence + const text = `${line.text}${tempered(estimate)}` + return estimate.low_confidence ? { text: `${text}, low confidence${forCard}`, tone: 'warn' } : { text: `${text}${forCard}`, tone: line.tone } } @@ -124,12 +132,15 @@ function dispatchCard(estimate: Plan['estimate']): string { return priced_for && priced_for !== device ? ` - for ${priced_for}` : '' } -function rawFigure(plan: Plan): PlanLine { - const { minutes, basis, device, priced_for } = plan.estimate - if (basis === 'unknown' || minutes === null) return unpriced(plan.estimate) +function rawFigure( + estimate: PlanEstimate, + listEntries: Plan['list_entries'], +): PlanLine { + const { minutes, basis, device, priced_for } = estimate + if (basis === 'unknown' || minutes === null) return unpriced(estimate) // the card the run dispatches to, when it says more than the backend const on = priced_for && priced_for !== device ? priced_for : device - const { card, along, missing } = qualifiers(plan.estimate) + const { card, along, missing } = qualifiers(estimate) if (basis === 'other_device') { return { text: `no figure for ${on} - ${minutes} min was ${card}${along}${missing}`, @@ -139,11 +150,11 @@ function rawFigure(plan: Plan): PlanLine { // another workflow's runs of the same pipeline priced this one (#797) if (basis === 'inherited') { return { - text: `~${minutes} min, inherited from ${plan.estimate.inherited_from ?? 'a template'}${along}${missing}`, + text: `~${minutes} min, inherited from ${estimate.inherited_from ?? 'a template'}${along}${missing}`, tone: 'plain', } } - const forList = Object.entries(plan.list_entries) + const forList = Object.entries(listEntries) .map(([name, count]) => `${count} ${name}`) .join(', ') // `derived` is the stored total stretched over a list the caller @@ -188,3 +199,40 @@ function unpriced(estimate: Plan['estimate']): PlanLine { } return { text: 'no measured cost', tone: 'warn' } } + +/** One estimate on its own, read for a person - the figure line a plan + * shows, for a caller that holds only the `PlanEstimate` (a restart batch's + * preview prices each member this way, #1473). Null - no plan was built - + * says so rather than reading as free. */ +export function describeEstimate(estimate: PlanEstimate | null): PlanLine { + if (!estimate) return { text: 'no estimate', tone: 'warn' } + return figure(estimate, {}) +} + +/** The sum of several estimates' minutes, with how many had no figure, so a + * total over a batch never reads as complete when part of it is unpriced. */ +export function describeEstimateTotal( + estimates: (PlanEstimate | null)[], +): PlanLine { + let minutes = 0 + let priced = 0 + for (const estimate of estimates) { + if (estimate && estimate.basis !== 'unknown' && estimate.minutes !== null) { + minutes += estimate.minutes + priced += 1 + } + } + const missing = estimates.length - priced + const unpricedNote = missing ? `, plus ${missing} with no figure` : '' + if (!priced) { + return { + text: estimates.length ? 'total: no figure' : 'total: nothing to run', + tone: estimates.length ? 'warn' : 'plain', + } + } + const total = Math.round(minutes * 10) / 10 + return { + text: `total ~${total} min${unpricedNote}`, + tone: missing ? 'warn' : 'plain', + } +} diff --git a/ui/src/lib/restartBatches.ts b/ui/src/lib/restartBatches.ts new file mode 100644 index 000000000..160599c37 --- /dev/null +++ b/ui/src/lib/restartBatches.ts @@ -0,0 +1,103 @@ +import { api } from './api' +import { confirmDialog } from './confirm.svelte' +import { describeEstimate, describeEstimateTotal } from './plan' +import { notify } from './toast' +import type { JobSummary } from './types' + +/** One server restart's worth of cancelled jobs that look not yet rerun: + * the batch key (`restart_batch`, the dead server's instance), one member + * id the batch route takes, and how many members have no rerun in view. */ +export interface RestartBanner { + batch: string + id: string + count: number + newest: number +} + +/** The banners the loaded rows call for, newest batch first, one per batch + * (#1473). A tombstone counts unless some loaded row's `rerun_of` names it. + * This is an estimate - the list is capped and a rerun may be in a + * workspace since deleted - so the batch route's preview is the authority, + * and `dismissed` holds the batches a preview found nothing left in. */ +export function restartBanners( + jobs: JobSummary[], + dismissed: ReadonlySet = new Set(), +): RestartBanner[] { + const rerun = new Set( + jobs.map((job) => job.rerun_of).filter((id): id is string => !!id), + ) + const banners = new Map() + for (const job of jobs) { + const batch = job.restart_batch + if (!batch || job.status !== 'cancelled' || rerun.has(job.id)) continue + if (dismissed.has(batch)) continue + const created = job.created_at ?? 0 + const banner = banners.get(batch) + if (banner) { + banner.count += 1 + banner.newest = Math.max(banner.newest, created) + } else { + banners.set(batch, { batch, id: job.id, count: 1, newest: created }) + } + } + return [...banners.values()].sort((a, b) => b.newest - a.newest) +} + +const plural = (n: number, one: string, many: string) => + `${n} ${n === 1 ? one : many}` + +/** Preview the batch `id` belongs to, show what a rerun would queue with + * each estimate and a total, and queue it only on confirm. Answers 'empty' + * when the preview found nothing left to rerun - the caller hides that + * batch's banner - 'queued' after a confirmed rerun, and 'cancelled' when + * nothing was queued (a cancel, or a failed call, already reported). */ +export async function rerunRestartBatchWithConfirm( + id: string, +): Promise<'queued' | 'cancelled' | 'empty'> { + let preview + try { + preview = await api.rerunRestartBatch(id) + } catch (e) { + notify.error(e instanceof Error ? e.message : String(e)) + return 'cancelled' + } + const would = preview.would_queue ?? [] + const skipped = preview.skipped.map( + (entry) => `• ${entry.id}: ${entry.reason}`, + ) + const skippedBlock = skipped.length + ? `\n\nSkipped:\n${skipped.join('\n')}` + : '' + if (!would.length) { + await confirmDialog( + `Nothing is left to rerun from this server restart.${skippedBlock}`, + { confirmLabel: 'Close', alert: true }, + ) + return 'empty' + } + const lines = would.map( + (entry) => + `• ${entry.workflow ?? '(no workflow)'} (${entry.id}, ${entry.workspace}) - ${describeEstimate(entry.estimate).text}`, + ) + const total = describeEstimateTotal(would.map((entry) => entry.estimate)) + const message = + `Rerun ${plural(would.length, 'job', 'jobs')} a server restart cancelled?` + + `\n\nWould queue:\n${lines.join('\n')}\n${total.text}${skippedBlock}` + if ( + !(await confirmDialog(message, { confirmLabel: `Rerun ${would.length}` })) + ) + return 'cancelled' + try { + const answer = await api.rerunRestartBatch(id, true) + const skippedNote = answer.skipped.length + ? `; skipped ${answer.skipped.length}: ${answer.skipped + .map((entry) => `${entry.id} (${entry.reason})`) + .join(', ')}` + : '' + notify.success(`Queued ${answer.queued.length}${skippedNote}`) + } catch (e) { + notify.error(e instanceof Error ? e.message : String(e)) + return 'cancelled' + } + return 'queued' +} diff --git a/ui/src/lib/types.ts b/ui/src/lib/types.ts index 42407655f..5a3b87132 100644 --- a/ui/src/lib/types.ts +++ b/ui/src/lib/types.ts @@ -30,6 +30,7 @@ export type AcknowledgedCost = Schemas['AcknowledgedCost'] export type JobProgress = Schemas['JobProgress'] export type JobList = Schemas['JobList'] export type JobWorkflow = Schemas['JobWorkflow'] +export type RestartBatchRerun = Schemas['RestartBatchRerun'] export type JobExport = Schemas['JobExport'] export type JobMoved = Schemas['JobMoved'] export type JobCancelled = Schemas['JobCancelled'] diff --git a/ui/src/lib/ui/ConfirmDialog.svelte b/ui/src/lib/ui/ConfirmDialog.svelte index 00bdc465a..d02f02465 100644 --- a/ui/src/lib/ui/ConfirmDialog.svelte +++ b/ui/src/lib/ui/ConfirmDialog.svelte @@ -27,9 +27,11 @@ {confirmState.message}
- {confirmState.cancelLabel} + {#if !confirmState.alert} + {confirmState.cancelLabel} + {/if} resolveConfirm(true)}> {confirmState.confirmLabel} From 37f8ee1ed8603b1ca15268beff8e1e332aad74fa Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 07:04:10 -0600 Subject: [PATCH 256/412] fix(server): #1492 - a plain rerun keeps the original's drawn seed Co-Authored-By: Claude Sonnet 5.5 --- dw/server/job_record.py | 2 +- tests/test_rerun_plain_seed.py | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 tests/test_rerun_plain_seed.py diff --git a/dw/server/job_record.py b/dw/server/job_record.py index 978f6d172..1b8f7fbec 100644 --- a/dw/server/job_record.py +++ b/dw/server/job_record.py @@ -123,7 +123,7 @@ def rerun_arguments(arguments, overrides, new_seed, variable, realized): arguments = {**arguments, **overrides} warnings = [] draws_fresh = variable is not None and overrides.get(variable, 1) is None - if overrides and not new_seed and not draws_fresh: + if not new_seed and not draws_fresh: arguments, warnings = keep_drawn_seed(arguments, variable, realized()) if new_seed: if variable in overrides: diff --git a/tests/test_rerun_plain_seed.py b/tests/test_rerun_plain_seed.py new file mode 100644 index 000000000..65e260f2d --- /dev/null +++ b/tests/test_rerun_plain_seed.py @@ -0,0 +1,24 @@ +"""#1492: a plain rerun keeps the seed the original drew, as one with overrides does.""" + +from dw.server.job_record import RERUN_SEED_UNKNOWN, rerun_arguments + + +def test_plain_rerun_keeps_drawn_seed(): + args, warnings = rerun_arguments( + {"prompt": "a"}, None, False, "seed", lambda: {"seed": 123} + ) + assert args == {"prompt": "a", "seed": 123} + assert warnings == [] + + +def test_plain_rerun_warns_when_seed_unknown(): + args, warnings = rerun_arguments({"prompt": "a"}, None, False, "seed", lambda: {}) + assert "seed" not in args + assert warnings and warnings[0].startswith(RERUN_SEED_UNKNOWN) + + +def test_new_seed_still_draws_fresh(): + args, warnings = rerun_arguments( + {"prompt": "a"}, None, True, "seed", lambda: {"seed": 123} + ) + assert args["seed"] != 123 and warnings == [] From 6fde2e5d8b6bf0efffae03b0f430c10f5ae436f8 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 07:23:15 -0600 Subject: [PATCH 257/412] feat(chain): #1474 - measures on chain shot records, typed for REST Every checked segment's shot records its kept attempt's measures, each against the ceiling in force: {value, ceiling, bound, warn_only, failed}. audio_dbfs stays top-level and is mirrored; words is its similarity against words_similarity_min. Check off records no key. ManifestEntry types shots as ShotRecord (extra allowed); OpenAPI and UI types are regenerated. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 2 +- docs/WORKFLOW_GUIDE.md | 9 +- dw/pipeline_processors/chain.py | 6 + dw/pipeline_processors/chain_check.py | 46 ++++++++ dw/server/api_models.py | 68 ++++++++++- dw/shots.py | 6 + tests/test_chain_check.py | 64 +++++++++++ tests/test_chain_reroll.py | 118 +++++++++++++++++++ ui/src/lib/generated/api-schema.ts | 103 ++++++++++++++++- ui/src/lib/generated/openapi.json | 158 +++++++++++++++++++++++++- 10 files changed, 575 insertions(+), 5 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8e00bc3ef..f032a9057 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -81,7 +81,7 @@ one to open. | Stills beside video (#1375) | `dw/result.py`: `_is_still_beside_video`, called from `Result.save_artifact` | Inside a dict result saved under a video content type, an entry that is one PIL image is written as `-.png`, never as a one-frame video (`track_people`'s `contact_sheet`). A step whose whole result is one image under a video type still writes the one-frame video it always did; under an image type nothing changes. | `tests/test_person_track.py::TestSaving::test_a_pil_image_under_a_video_type_is_written_as_png`, `tests/test_person_track.py::TestSaving::test_the_rule_applies_only_to_a_video_content_type` | | Reading a JSON record back | `dw/locations.py`: `load_json_record` | A task reads a saved JSON record (`fit_to_model`'s, `crop_face_track`'s) only through `load_json_record`: the path is confined like any media path, then the extension must be `.json`, then the size is checked against `MAX_JSON_SIZE`, and only then is it parsed. `fit._read_fit` and `face_track._read_track` call it, never `open`. | `tests/test_locations.py::TestLoadJsonRecord::test_traversal_out_of_the_roots_is_refused`, `tests/test_locations.py::TestLoadJsonRecord::test_a_non_json_extension_is_refused`, `tests/test_locations.py::TestLoadJsonRecord::test_an_oversized_file_is_refused_before_it_is_read`, `tests/test_fit_to_model.py::TestRestore::test_fit_path_with_traversal_is_refused` | | Shots in a joined video | `dw/shots.py` | Every `AudioVideo` constructor decides what to do with `shots`, and the sample spans are measured from the joined waveform. | `tests/test_shots.py::test_every_audio_video_constructor_site_is_decided`, `tests/test_shots.py::TestConcatVideosShots::test_an_overrun_track_is_measured_not_derived` | -| Chain per-segment check and re-roll | `dw/pipeline_processors/chain_check.py`: `check_segment`, `SegmentCheck`, `best_attempt`, `reroll_seed`; the words measure is `chain_check.check_words` with the seam-head rule `_seam_head`, `_opens_mid_line` (a passed segment missing its opening words: `line_opening_missing`, which re-rolls via `words_opening`, #1308), `WORDS_SIMILARITY_MIN` (the ceiling for the chain `check`'s `words_similarity_min`, default null = off, #1298), `WORDS_FINDINGS`, `SEAM_TAIL_WORDS`; the identity measure is `chain_check.with_face_drop` (`face_drop` against `face_base`, segment 1's frame 0 and its median match from frame 1 on, measured once), warn-only, behind the seam `_face_scores` (`face_drift.face_similarities`, which runs YuNet/SFace on the sampled frames only), ceiling `face_drop_max` default null = record only, recorded on the shot's `check`; a checked chain's face weights are in the plan's `downloads_required` (`dw/plan_downloads.py`: `_chain_check_weights`); lip sync is not a chain measure (ruling R9, `bench/records/narrated.md`) and `lip_sync_min` is an unknown key; the keys' rule is `dw/pipeline_processors/chain_rules.py`: `chain_check_problem` (torch-free, beside the look hold's `chain_look_hold_problem`); whether the audio is held, the floor and whether segment 1 is checked are `dw/pipeline_processors/chain_config.py`: `chain_holds_audio`, `chain_audio_floor`, `chain_checks_segment_1`, `chain_checks_words`, `segment_line` (the expected line from the chain's `lines`, else the `` of the prompt) (pure: the run's `ChainConfig` and the cost estimate both ask them); the attempt loop is `dw/pipeline_processors/chain.py`: `_checked_attempt`, `_render_attempt` | A checked segment is measured on the arithmetic `analyze_seams` uses (`dw/tasks/assess.py`: `seam_measures`, `frame_measures`) and `dw/texture_bands.py`, never a copy of it. Every attempt renders from the same `_ChainState`; nothing of an attempt (frames, audio join, shot, spill, look-hold state, segment 1's anchor or keystone) reaches the timeline until it is kept, and a re-roll runs on its own generator at `reroll_seed`, leaving the step's generator where attempt 0 left it. Segment 1 has no seam and is checked for the audio floor only (`audio_dbfs` against `audio_dbfs_min`, default -70; generated audio only, held audio is skipped); `check_segment`'s `hard_cut` exemption is not passed by `run_chain`. The words measure (#1262) compares through `script_check.check` unchanged, on one line and no shots, and its seam-head rule takes the heard words from the Script check owners (`normalize_words(numbers=False)` + `fold_numbers`) and the head from `script_check.align`, never its own alignment; Whisper is `transcribe_audio`'s cached model, levelled by `script_take.level_for_transcription`. The words measure runs only when `words_similarity_min` is set, on every segment with a line, and never when the audio is held. Absent `check` is off and absent `retries` is 0. The worst case is quoted by `dw/cost_scaling.py`: `_worst_case_retries`, N(1 + retries) renders for N segments of a chain that generates its audio, else 1 + (N - 1)(1 + retries), plus `cost_scaling.words_check_term` (one Whisper CPU pass per worst-case attempt. A failed words check on a segment past the first in a `guide` chain, one with a head trim, transcribes its untrimmed audio once more, to name `line_clipped_at_head` (`chain.py`: `_segment_words`; `chain_check.py`: `_clipped_at_head`, #1300); that second pass is not priced, as it runs only on a failure, on a model the first pass warmed, inside the worst case's margin); on every basis, the curated row's and, through `dw/plan.py` `_with_worst_case`, an observed or inherited history's too. | `tests/test_chain.py::TestCheckAndReroll::test_a_failed_segment_is_rerolled_with_a_new_seed_from_the_same_carry`, `tests/test_chain.py::TestCheckAndReroll::test_budget_exhausted_keeps_the_best_attempt_and_warns`, `tests/test_chain.py::TestCheckAndReroll::test_absent_check_is_todays_chain`, `tests/test_chain_check.py::test_the_estimate_quotes_the_worst_case_retries`, `tests/test_chain_check.py::test_an_inherited_estimate_quotes_the_worst_case_retries`, `tests/test_chain_check.py::test_the_estimate_and_the_run_agree_on_segment_1`, `tests/test_chain_check.py::TestAudioFloor::test_held_audio_is_never_measured`, `tests/test_chain.py::TestAudioFloorReroll::test_a_silent_segment_1_is_rerolled`, `tests/test_chain.py::TestAudioFloorReroll::test_a_silent_segment_2_only_warns_with_check_off`, `tests/test_chain_words.py::test_seam_head_word_of_previous_line_is_dropped`, `tests/test_chain_words.py::test_seam_head_number_folded_across_chunks_is_dropped`, `tests/test_chain_words.py::test_invented_head_word_is_kept`, `tests/test_chain_words.py::test_line_clipped_at_end_fails`, `tests/test_chain_words.py::test_line_clipped_at_head_names_a_line_opened_in_the_trimmed_head`, `tests/test_chain_words.py::test_no_head_finding_when_the_line_opens_after_the_trim`, `tests/test_chain_words.py::test_passed_segment_missing_its_opening_words_is_reported`, `tests/test_chain_reroll.py::test_opening_missing_rerolls_while_retries_remain`, `tests/test_chain_check_face_sync.py::test_face_drop_max_sets_a_failing_ceiling_without_reroll`, `tests/test_chain_check_face_sync.py::test_a_model_that_cannot_load_records_none`, `tests/test_chain_check_face_sync.py::test_face_base_excludes_frame_0`, `tests/test_chain_check_face_sync.py::test_faceless_segment_1_logs_once`, `tests/test_chain_check_face_sync.py::test_checked_chain_lists_face_weights_in_downloads`, `tests/test_chain_check_face_sync.py::test_lip_sync_is_not_a_chain_measure` | +| Chain per-segment check and re-roll | `dw/pipeline_processors/chain_check.py`: `check_segment`, `SegmentCheck`, `best_attempt`, `reroll_seed`; the words measure is `chain_check.check_words` with the seam-head rule `_seam_head`, `_opens_mid_line` (a passed segment missing its opening words: `line_opening_missing`, which re-rolls via `words_opening`, #1308), `WORDS_SIMILARITY_MIN` (the ceiling for the chain `check`'s `words_similarity_min`, default null = off, #1298), `WORDS_FINDINGS`, `SEAM_TAIL_WORDS`; the identity measure is `chain_check.with_face_drop` (`face_drop` against `face_base`, segment 1's frame 0 and its median match from frame 1 on, measured once), warn-only, behind the seam `_face_scores` (`face_drift.face_similarities`, which runs YuNet/SFace on the sampled frames only), ceiling `face_drop_max` default null = record only, recorded on the shot's `check`; a checked chain's face weights are in the plan's `downloads_required` (`dw/plan_downloads.py`: `_chain_check_weights`); lip sync is not a chain measure (ruling R9, `bench/records/narrated.md`) and `lip_sync_min` is an unknown key; the keys' rule is `dw/pipeline_processors/chain_rules.py`: `chain_check_problem` (torch-free, beside the look hold's `chain_look_hold_problem`); whether the audio is held, the floor and whether segment 1 is checked are `dw/pipeline_processors/chain_config.py`: `chain_holds_audio`, `chain_audio_floor`, `chain_checks_segment_1`, `chain_checks_words`, `segment_line` (the expected line from the chain's `lines`, else the `` of the prompt) (pure: the run's `ChainConfig` and the cost estimate both ask them); the attempt loop is `dw/pipeline_processors/chain.py`: `_checked_attempt`, `_render_attempt`; the kept attempt's `measures` on its shot are `chain_check.measures_record` (`MEASURE_BOUNDS`, #1474), typed for REST as `dw/server/api_models.py`: `ShotRecord`, `ShotMeasure` | A checked segment is measured on the arithmetic `analyze_seams` uses (`dw/tasks/assess.py`: `seam_measures`, `frame_measures`) and `dw/texture_bands.py`, never a copy of it. Every attempt renders from the same `_ChainState`; nothing of an attempt (frames, audio join, shot, spill, look-hold state, segment 1's anchor or keystone) reaches the timeline until it is kept, and a re-roll runs on its own generator at `reroll_seed`, leaving the step's generator where attempt 0 left it. Segment 1 has no seam and is checked for the audio floor only (`audio_dbfs` against `audio_dbfs_min`, default -70; generated audio only, held audio is skipped); `check_segment`'s `hard_cut` exemption is not passed by `run_chain`. The words measure (#1262) compares through `script_check.check` unchanged, on one line and no shots, and its seam-head rule takes the heard words from the Script check owners (`normalize_words(numbers=False)` + `fold_numbers`) and the head from `script_check.align`, never its own alignment; Whisper is `transcribe_audio`'s cached model, levelled by `script_take.level_for_transcription`. The words measure runs only when `words_similarity_min` is set, on every segment with a line, and never when the audio is held. Absent `check` is off and absent `retries` is 0. The worst case is quoted by `dw/cost_scaling.py`: `_worst_case_retries`, N(1 + retries) renders for N segments of a chain that generates its audio, else 1 + (N - 1)(1 + retries), plus `cost_scaling.words_check_term` (one Whisper CPU pass per worst-case attempt. A failed words check on a segment past the first in a `guide` chain, one with a head trim, transcribes its untrimmed audio once more, to name `line_clipped_at_head` (`chain.py`: `_segment_words`; `chain_check.py`: `_clipped_at_head`, #1300); that second pass is not priced, as it runs only on a failure, on a model the first pass warmed, inside the worst case's margin); on every basis, the curated row's and, through `dw/plan.py` `_with_worst_case`, an observed or inherited history's too. | `tests/test_chain.py::TestCheckAndReroll::test_a_failed_segment_is_rerolled_with_a_new_seed_from_the_same_carry`, `tests/test_chain.py::TestCheckAndReroll::test_budget_exhausted_keeps_the_best_attempt_and_warns`, `tests/test_chain.py::TestCheckAndReroll::test_absent_check_is_todays_chain`, `tests/test_chain_check.py::test_the_estimate_quotes_the_worst_case_retries`, `tests/test_chain_check.py::test_an_inherited_estimate_quotes_the_worst_case_retries`, `tests/test_chain_check.py::test_the_estimate_and_the_run_agree_on_segment_1`, `tests/test_chain_check.py::TestAudioFloor::test_held_audio_is_never_measured`, `tests/test_chain.py::TestAudioFloorReroll::test_a_silent_segment_1_is_rerolled`, `tests/test_chain.py::TestAudioFloorReroll::test_a_silent_segment_2_only_warns_with_check_off`, `tests/test_chain_words.py::test_seam_head_word_of_previous_line_is_dropped`, `tests/test_chain_words.py::test_seam_head_number_folded_across_chunks_is_dropped`, `tests/test_chain_words.py::test_invented_head_word_is_kept`, `tests/test_chain_words.py::test_line_clipped_at_end_fails`, `tests/test_chain_words.py::test_line_clipped_at_head_names_a_line_opened_in_the_trimmed_head`, `tests/test_chain_words.py::test_no_head_finding_when_the_line_opens_after_the_trim`, `tests/test_chain_words.py::test_passed_segment_missing_its_opening_words_is_reported`, `tests/test_chain_reroll.py::test_opening_missing_rerolls_while_retries_remain`, `tests/test_chain_check_face_sync.py::test_face_drop_max_sets_a_failing_ceiling_without_reroll`, `tests/test_chain_check_face_sync.py::test_a_model_that_cannot_load_records_none`, `tests/test_chain_check_face_sync.py::test_face_base_excludes_frame_0`, `tests/test_chain_check_face_sync.py::test_faceless_segment_1_logs_once`, `tests/test_chain_check_face_sync.py::test_checked_chain_lists_face_weights_in_downloads`, `tests/test_chain_check_face_sync.py::test_lip_sync_is_not_a_chain_measure`, `tests/test_chain_reroll.py::test_a_passing_segment_records_its_measures_with_their_ceilings`, `tests/test_chain_reroll.py::test_a_chain_manifest_entry_round_trips_through_the_api_model` | | Chain length and audio-source rules | `dw/pipeline_processors/chain_rules.py`: `chain_length_problem` (exactly one of `segments`, `match_audio`, `duration_seconds`) and `match_audio_source_problem` (a `match_audio` step names a `hold_audio` track or a `references` list); the run asks them in `dw/pipeline_processors/chain_config.py`: `_chain_length`, `_plan_from_audio`, `_find_audio_reference`; validate asks the same two in `dw/step_value_checks.py`: `chain_length_errors`, after variable substitution | One predicate and one message per rule: the run and validate never restate either. The run alone counts the audio entries in `references`, on the resolved references. | `tests/test_chain.py` (the `match_audio` and `chained-segments` cases), `tests/test_validation.py` registry order | | Chain frame snap for a length-planned chain | `dw/pipeline_processors/chain_rules.py`: `chain_needs_frame_snap`; `dw/pipeline_processors/chain_config.py`: `derive_frame_snaps`, called from `dw/workflow.py`: `Workflow._expand` before substitution; validate's warning is `dw/guides.py`: `frame_snap_warnings` | A `duration_seconds` or `match_audio` chain with no `frame_snap` takes its `num_frames` variable's modulus constraint as `constraint:` before variables substitute, and the run logs it; one it cannot derive is a validate warning at `chain.frame_snap`, never a silent off-grid last segment. | `tests/test_chain_duration.py::TestDerivedFrameSnap::test_a_block_with_no_frame_snap_derives_it_and_says_so`, `tests/test_chain_duration.py::TestDerivedFrameSnap::test_validate_warns_on_a_length_planned_chain_it_cannot_snap` | | Chain look hold | `dw/pipeline_processors/chain_look.py`: `LookHold`, `pickup_grade`, `ease_creep`, `ease_texture`, `precompensate`, `is_cut`; built per chain in `dw/pipeline_processors/chain.py` | A finished segment's frames are corrected before its carry is taken, so the next segment reads the corrected frame. A pickup the quantile gap calls a cut (`is_cut`) or a flat frame is never graded, and creep is only eased down, never brightened. Absent `look_hold` is today's chain. Numpy and torch only. | `tests/test_chain.py::TestLookHold::test_look_hold_off_is_todays_chain`, `tests/test_chain.py::TestLookHold::test_look_hold_pulls_a_later_segment_onto_the_carried_frame`, `tests/test_chain_look.py::test_pickup_grade_skips_a_cut_and_a_flat_frame` | diff --git a/docs/WORKFLOW_GUIDE.md b/docs/WORKFLOW_GUIDE.md index aba9df87e..a28fc01d0 100644 --- a/docs/WORKFLOW_GUIDE.md +++ b/docs/WORKFLOW_GUIDE.md @@ -3034,7 +3034,14 @@ frames and audio are the ones stitched, and the seam is crossfaded against them. Each shot of a checked chain records `attempts`; a re-rolled one records the `seed` its kept attempt ran at, and one that failed every attempt records `check_failed` (the -measures its kept attempt failed). The job gets one `warning` (`kind: +measures its kept attempt failed). Every checked shot also records `measures`, one +entry per measure its kept attempt took, passing or not: `{"value", "ceiling", "bound", +"warn_only", "failed"}`. `ceiling` is the one in force (the workflow's override, else the +default; `null` when the measure has none, as `face_drop` by default), `bound` is `"max"` +for a ceiling and `"min"` for a floor (`audio_dbfs`, which also stays a top-level key, and +`words`, whose value is its similarity against `words_similarity_min`), and `failed` is the +check's verdict - read it, not value against ceiling, since `texture_ratio` fails both +ways. Segment 1 records only what it measured, and check off records no `measures`. The job gets one `warning` (`kind: "chain_check_failed"`) per such segment, naming the measures, their values and the kept attempt, and the job log names each re-roll. When `words` failed, the warning also carries `heard`, `similarity` and `findings` (`values.words` is the similarity); when every diff --git a/dw/pipeline_processors/chain.py b/dw/pipeline_processors/chain.py index 2f20e4d13..10c415b7f 100644 --- a/dw/pipeline_processors/chain.py +++ b/dw/pipeline_processors/chain.py @@ -65,6 +65,7 @@ face_record, failures_text as _failures, measure_frames, + measures_record, reroll_seed, shown_value as _shown_value, texture_base, @@ -640,6 +641,8 @@ def _record_check(shot, segment, config, checked): to) has one attempt.""" if checked is None: shot["attempts"] = 1 + # The check is on but measured nothing here (#1474) + shot["measures"] = {} return shot["attempts"] = checked["attempts"] result, kept = checked["result"], checked["kept"] @@ -650,6 +653,9 @@ def _record_check(shot, segment, config, checked): if "words" in result.measures: # The kept attempt's words, null for a segment with no line (#1262) shot["words"] = result.measures["words"] + # Every measure the kept attempt computed, against the ceiling in force, + # passing or not, so a caller can read how close it came (#1474) + shot["measures"] = measures_record(result, config.check) if result.passed: return # Texture alone ends the loop on attempt 1 without trying the budget diff --git a/dw/pipeline_processors/chain_check.py b/dw/pipeline_processors/chain_check.py index 43782846e..a9cedf82d 100644 --- a/dw/pipeline_processors/chain_check.py +++ b/dw/pipeline_processors/chain_check.py @@ -39,6 +39,7 @@ import logging import math +import numbers from dataclasses import dataclass, field import numpy @@ -395,6 +396,51 @@ def face_record(result): return {name: result.measures.get(name) for name in FACE_RECORD} +# Each recorded measure's bound in the SegmentCheck (#1474): the field its +# ceiling is read from and whether the value must stay under it ("max") or +# over it ("min"). texture_ratio_max bounds the ratio both ways, so a texture +# value under 1/ceiling fails too: `failed` is the verdict, not value-vs-ceiling +MEASURE_BOUNDS = { + "jump_ratio": ("jump_ratio_max", "max"), + "look_ratio": ("look_ratio_max", "max"), + "texture_ratio": ("texture_ratio_max", "max"), + "cut_ratio": ("cut_ratio_max", "max"), + "audio_dbfs": ("audio_dbfs_min", "min"), + "words": ("words_similarity_min", "min"), + "face_drop": ("face_drop_max", "max"), +} + + +def measures_record(result, check): + """The kept attempt's measures for its shot's `measures` (#1474): one + entry per measure in MEASURES the CheckResult computed - a number, or for + `words` its similarity - as {value, ceiling, bound, warn_only, failed}. + The ceiling is the SegmentCheck's in force (null where it sets none); + `failed` is whether the check failed that measure. A measure it did not + compute (None, or a skipped seam) has no entry.""" + record = {} + for name in MEASURES: + value = result.measures.get(name) + if name == "words": + value = value.get("similarity") if isinstance(value, dict) else None + if ( + isinstance(value, bool) + or not isinstance(value, numbers.Real) + or not math.isfinite(value) + ): + continue + setting, bound = MEASURE_BOUNDS[name] + ceiling = getattr(check, setting) + record[name] = { + "value": float(value), + "ceiling": None if ceiling is None else float(ceiling), + "bound": bound, + "warn_only": name in WARN_ONLY, + "failed": name in result.failed, + } + return record + + def shown_value(result, name): """A failed measure's value as a failure names it: the words measure by its similarity, every other by its number.""" diff --git a/dw/server/api_models.py b/dw/server/api_models.py index 17d87df8d..329ac70ae 100644 --- a/dw/server/api_models.py +++ b/dw/server/api_models.py @@ -491,14 +491,80 @@ class StepTiming(ApiModel): cache: dict[str, Any] = sometimes("Skip counts, on a step that set a `cache`.") +class ShotMeasure(ApiModel): + """One measure a chain's check computed for a segment's kept attempt + (#1474), against the ceiling in force.""" + + value: float = Field( + description="The measure; for `words`, the heard words' similarity to the line." + ) + ceiling: float | None = Field( + description="The bound the check held it to - the workflow's own when it " + "set one - or null where the check sets none (measured, never failed)." + ) + bound: Literal["max", "min"] = Field( + description="`max`: the value must stay at or under the ceiling; `min`: " + "at or over it. `texture_ratio` is bounded both ways, so `failed`, not " + "value against ceiling, is the verdict." + ) + warn_only: bool = Field( + description="A failure is warned and recorded but never re-rolled." + ) + failed: bool = Field(description="The check failed this measure.") + + +class ShotRecord(ApiModel): + """One shot of a joined video: where an input landed in it, and for a + chain's segment what its check recorded (`dw/shots.py` lists every key). + Open even in strict mode: a join may add detail of its own.""" + + model_config = ConfigDict(extra="allow") + + name: str + start_frame: int + num_frames: int + start_sample: int | None = Field( + default=None, description="Null when the video has no track the join built." + ) + num_samples: int | None = Field( + default=None, description="Null when the video has no track the join built." + ) + planned_segments: int = sometimes( + "On a chain's shot: the segment count its plan asked for." + ) + segment_file: str = sometimes( + "On a chain's shot under save_segments and keep_segments: its segment's file." + ) + resumed: bool = sometimes( + "On a chain's shot: the segment was copied from an earlier run (resume_from)." + ) + attempts: int = sometimes("On a chain's shot: renders its check tried.") + check_failed: list[str] = sometimes( + "On a checked chain shot whose every attempt failed: the measures the " + "kept one failed." + ) + audio_dbfs: float = sometimes( + "On a chain's shot with generated audio: its kept audio's level." + ) + measures: dict[str, ShotMeasure] = sometimes( + "On a chain's shot with the check on: every measure the kept attempt " + "computed, by name. Absent with the check off, on a resumed segment, " + "and on a job recorded before the field existed." + ) + + class ManifestEntry(ApiModel): """One step's saved files. Open even in strict mode: the worker adds - per-step detail (`selected`, `shots`, ...) the UI does not read.""" + per-step detail (`selected`, ...) beyond the keys typed here.""" model_config = ConfigDict(extra="allow") step: str files: list[str] + shots: list[ShotRecord] | None = sometimes( + "Where each input landed in the step's joined video (dw/shots.py); " + "null or absent on a step that joined none." + ) subfolder: str = sometimes( "The in-run subfolder the step's `result.subfolder` chose - " "`final`, `intermediate`, any relative path - `''` when it chose none. " diff --git a/dw/shots.py b/dw/shots.py index e0b4d4604..d50126907 100644 --- a/dw/shots.py +++ b/dw/shots.py @@ -47,6 +47,12 @@ included), beside the take - how `chain_repair_cut` finds them (#1169) - `planned_segments` - every shot of a chain's take carries its plan's segment count, which a probe's take (`stop_after`) falls short of +- `measures` - every checked segment's shot of a chain with `check` on carries + its kept attempt's measures, `{name: {value, ceiling, bound, warn_only, + failed}}`: the ceiling in force (null when none), `bound` "max" or "min" + (`audio_dbfs`, mirrored from its top-level key, and `words`, its similarity + against `words_similarity_min`), and `failed` the check's verdict. Segment 1 + carries only what it measured; check off, or a resumed shot, has no key (#1474) Every other `AudioVideo` constructor either carries the list (same frames), rescales it (`interpolate_frames`), re-measures the sample side for a new diff --git a/tests/test_chain_check.py b/tests/test_chain_check.py index bd068beb5..8aaa5eeb6 100644 --- a/tests/test_chain_check.py +++ b/tests/test_chain_check.py @@ -1013,3 +1013,67 @@ def test_the_warning_check_is_registered(self): from dw import validation assert "chain_lines_warnings" in [c.name for c in validation.WARNING_CHECKS] + + +# measures_record (#1474): the kept attempt's measures for its shot + + +def test_measures_record_marks_texture_and_face_drop_warn_only(): + from dw.pipeline_processors.chain_check import measures_record + + result = CheckResult( + False, + { + "jump_ratio": 1.2, + "frame_delta": 3.0, + "texture_ratio": 0.4, + "face_drop": 0.31, + }, + ["texture_ratio", "face_drop"], + ) + record = measures_record(result, SegmentCheck(face_drop_max=0.2)) + # Only MEASURES names: frame_delta is a working number, not a measure + assert set(record) == {"jump_ratio", "texture_ratio", "face_drop"} + assert record["texture_ratio"] == { + "value": 0.4, + "ceiling": TEXTURE_RATIO_MAX, + "bound": "max", + "warn_only": True, + "failed": True, + } + assert record["face_drop"]["warn_only"] is True + assert record["face_drop"]["ceiling"] == 0.2 + assert record["jump_ratio"]["warn_only"] is False + + +def test_measures_record_gives_null_for_a_measure_with_no_ceiling(): + from dw.pipeline_processors.chain_check import measures_record + + result = CheckResult(True, {"face_drop": 0.05, "cut_ratio": 1.1}, []) + record = measures_record(result, SegmentCheck(cut_ratio_max=None)) + assert record["face_drop"]["ceiling"] is None # FACE_DROP_DEFAULT + assert record["cut_ratio"]["ceiling"] is None + + +def test_measures_record_reads_words_by_similarity_against_its_minimum(): + from dw.pipeline_processors.chain_check import measures_record + + words = {"heard": "hi", "similarity": 0.72, "findings": [], "passed": False} + result = with_words(CheckResult(True, {"jump_ratio": 1.0}, []), words) + record = measures_record(result, SegmentCheck(words_similarity_min=0.8)) + assert record["words"] == { + "value": 0.72, + "ceiling": 0.8, + "bound": "min", + "warn_only": False, + "failed": True, + } + + +def test_measures_record_leaves_out_what_was_not_measured(): + from dw.pipeline_processors.chain_check import measures_record + + skipped = CheckResult(True, {"skipped": "no frames", "audio_dbfs": None}, []) + assert measures_record(skipped, SegmentCheck()) == {} + no_line = with_words(CheckResult(True, {"face_drop": None}, []), None) + assert measures_record(no_line, SegmentCheck()) == {} diff --git a/tests/test_chain_reroll.py b/tests/test_chain_reroll.py index 884702ca5..c03c6141b 100644 --- a/tests/test_chain_reroll.py +++ b/tests/test_chain_reroll.py @@ -482,3 +482,121 @@ def test_lines_of_the_wrong_length_are_refused_by_the_config(): # an empty list is a count mismatch, named with both numbers (#1262 bounce) with pytest.raises(ValueError, match=r"0 line\(s\) for 3"): ChainConfig(_chain(lines=[]), {}) + + +# The kept attempt's measures on every checked segment's shot (#1474), through +# the run: passing or not, each against the ceiling in force + + +def _shots(bad_calls=(), **overrides): + result = run_chain( + FakePipeline(_output(set(bad_calls))), + _chain(**overrides), + {"num_frames": 8, "seed": 5}, + ) + return result.shots + + +def test_a_passing_segment_records_its_measures_with_their_ceilings(): + from dw.pipeline_processors.chain_check import ( + AUDIO_DBFS_MIN, + CUT_RATIO_MAX, + JUMP_RATIO_MAX, + LOOK_RATIO_MAX, + ) + + shot = _shots()[1] + assert "check_failed" not in shot + measures = shot["measures"] + assert {"jump_ratio", "look_ratio", "cut_ratio", "audio_dbfs"} <= set(measures) + ceilings = { + "jump_ratio": JUMP_RATIO_MAX, + "look_ratio": LOOK_RATIO_MAX, + "cut_ratio": CUT_RATIO_MAX, + "audio_dbfs": AUDIO_DBFS_MIN, + } + for name, ceiling in ceilings.items(): + entry = measures[name] + assert set(entry) == {"value", "ceiling", "bound", "warn_only", "failed"} + assert isinstance(entry["value"], float) + assert entry["ceiling"] == ceiling + assert entry["failed"] is False + assert entry["warn_only"] is False + assert measures["jump_ratio"]["bound"] == "max" + + +def test_an_overridden_ceiling_shows_the_workflows_value(): + measures = _shots(check={"jump_ratio_max": 3.25})[1]["measures"] + assert measures["jump_ratio"]["ceiling"] == 3.25 + assert measures["look_ratio"]["ceiling"] == 5.5 + + +def test_a_failed_measure_agrees_with_check_failed(): + shot = _shots({1, 2})[1] + assert shot["check_failed"] + failed = {name for name, entry in shot["measures"].items() if entry["failed"]} + assert failed == set(shot["check_failed"]) + + +def test_check_off_records_no_measures_and_leaves_the_shot_as_it_was(): + shots = _shots(check=False, retries=0) + assert shots and all("measures" not in shot for shot in shots) + assert all("check" not in shot for shot in shots) + + +def test_segment_1_carries_only_what_it_measured(): + measures = _shots()[0]["measures"] + # No seam before it: only its audio floor is held + assert set(measures) == {"audio_dbfs"} + + +def test_audio_dbfs_stays_top_level_and_is_mirrored_as_a_floor(): + for shot in _shots(): + mirrored = shot["measures"]["audio_dbfs"] + assert shot["audio_dbfs"] == mirrored["value"] + assert mirrored["bound"] == "min" + assert mirrored["ceiling"] == -70.0 + + +def test_a_null_floor_records_a_null_ceiling(): + shots = _shots(check={"audio_dbfs_min": None}) + entry = shots[1]["measures"]["audio_dbfs"] + assert entry["ceiling"] is None and entry["failed"] is False + + +def test_the_existing_shot_keys_are_unchanged(): + without = run_chain( + FakePipeline(_output({1, 2})), _chain(), {"num_frames": 8, "seed": 5} + ).shots + keys = [ + "name", + "start_frame", + "num_frames", + "start_sample", + "num_samples", + "attempts", + "check", + "check_failed", + "audio_dbfs", + "trim_frames", + "crossfade_ms", + "planned_segments", + ] + assert [k for k in without[1] if k != "measures"] == keys + assert without[1]["check"] == {"face_drop": None} + + +def test_a_chain_manifest_entry_round_trips_through_the_api_model(): + from dw.server.api_models import ManifestEntry + + shots = _shots({1, 2}, check={"jump_ratio_max": 3.25}) + entry = {"step": "chain", "files": ["take.mp4"], "shots": shots} + model = ManifestEntry.model_validate(entry) + dumped = model.model_dump(exclude_unset=True) + assert dumped == entry + assert model.shots[1].measures["jump_ratio"].ceiling == 3.25 + # A shot from before #1474, with no measures, still validates + old = {k: v for k, v in shots[1].items() if k != "measures"} + assert ManifestEntry.model_validate( + {"step": "chain", "files": [], "shots": [old]} + ).model_dump(exclude_unset=True)["shots"] == [old] diff --git a/ui/src/lib/generated/api-schema.ts b/ui/src/lib/generated/api-schema.ts index 05faa7885..7f8707efd 100644 --- a/ui/src/lib/generated/api-schema.ts +++ b/ui/src/lib/generated/api-schema.ts @@ -3061,7 +3061,7 @@ export interface components { /** * ManifestEntry * @description One step's saved files. Open even in strict mode: the worker adds - * per-step detail (`selected`, `shots`, ...) the UI does not read. + * per-step detail (`selected`, ...) beyond the keys typed here. */ ManifestEntry: { /** Files */ @@ -3082,6 +3082,11 @@ export interface components { * @enum {string} */ role?: "final" | "intermediate"; + /** + * Shots + * @description Where each input landed in the step's joined video (dw/shots.py); null or absent on a step that joined none. + */ + shots?: components["schemas"]["ShotRecord"][] | null; /** Step */ step: string; /** @@ -3793,6 +3798,102 @@ export interface components { */ shadowed_by: "workspace" | "common" | "examples" | "builtin"; }; + /** + * ShotMeasure + * @description One measure a chain's check computed for a segment's kept attempt + * (#1474), against the ceiling in force. + */ + ShotMeasure: { + /** + * Bound + * @description `max`: the value must stay at or under the ceiling; `min`: at or over it. `texture_ratio` is bounded both ways, so `failed`, not value against ceiling, is the verdict. + * @enum {string} + */ + bound: "max" | "min"; + /** + * Ceiling + * @description The bound the check held it to - the workflow's own when it set one - or null where the check sets none (measured, never failed). + */ + ceiling: number | null; + /** + * Failed + * @description The check failed this measure. + */ + failed: boolean; + /** + * Value + * @description The measure; for `words`, the heard words' similarity to the line. + */ + value: number; + /** + * Warn Only + * @description A failure is warned and recorded but never re-rolled. + */ + warn_only: boolean; + }; + /** + * ShotRecord + * @description One shot of a joined video: where an input landed in it, and for a + * chain's segment what its check recorded (`dw/shots.py` lists every key). + * Open even in strict mode: a join may add detail of its own. + */ + ShotRecord: { + /** + * Attempts + * @description On a chain's shot: renders its check tried. + */ + attempts?: number; + /** + * Audio Dbfs + * @description On a chain's shot with generated audio: its kept audio's level. + */ + audio_dbfs?: number; + /** + * Check Failed + * @description On a checked chain shot whose every attempt failed: the measures the kept one failed. + */ + check_failed?: string[]; + /** + * Measures + * @description On a chain's shot with the check on: every measure the kept attempt computed, by name. Absent with the check off, on a resumed segment, and on a job recorded before the field existed. + */ + measures?: { + [key: string]: components["schemas"]["ShotMeasure"]; + }; + /** Name */ + name: string; + /** Num Frames */ + num_frames: number; + /** + * Num Samples + * @description Null when the video has no track the join built. + */ + num_samples?: number | null; + /** + * Planned Segments + * @description On a chain's shot: the segment count its plan asked for. + */ + planned_segments?: number; + /** + * Resumed + * @description On a chain's shot: the segment was copied from an earlier run (resume_from). + */ + resumed?: boolean; + /** + * Segment File + * @description On a chain's shot under save_segments and keep_segments: its segment's file. + */ + segment_file?: string; + /** Start Frame */ + start_frame: number; + /** + * Start Sample + * @description Null when the video has no track the join built. + */ + start_sample?: number | null; + } & { + [key: string]: unknown; + }; /** StarRequest */ StarRequest: { /** diff --git a/ui/src/lib/generated/openapi.json b/ui/src/lib/generated/openapi.json index 747a0ad89..2cb4103e5 100644 --- a/ui/src/lib/generated/openapi.json +++ b/ui/src/lib/generated/openapi.json @@ -2753,7 +2753,7 @@ }, "ManifestEntry": { "additionalProperties": true, - "description": "One step's saved files. Open even in strict mode: the worker adds\nper-step detail (`selected`, `shots`, ...) the UI does not read.", + "description": "One step's saved files. Open even in strict mode: the worker adds\nper-step detail (`selected`, ...) beyond the keys typed here.", "properties": { "files": { "items": { @@ -2781,6 +2781,21 @@ "title": "Role", "type": "string" }, + "shots": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/ShotRecord" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "description": "Where each input landed in the step's joined video (dw/shots.py); null or absent on a step that joined none.", + "title": "Shots" + }, "step": { "title": "Step", "type": "string" @@ -4616,6 +4631,147 @@ "title": "ShadowedEntry", "type": "object" }, + "ShotMeasure": { + "additionalProperties": false, + "description": "One measure a chain's check computed for a segment's kept attempt\n(#1474), against the ceiling in force.", + "properties": { + "bound": { + "description": "`max`: the value must stay at or under the ceiling; `min`: at or over it. `texture_ratio` is bounded both ways, so `failed`, not value against ceiling, is the verdict.", + "enum": [ + "max", + "min" + ], + "title": "Bound", + "type": "string" + }, + "ceiling": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "description": "The bound the check held it to - the workflow's own when it set one - or null where the check sets none (measured, never failed).", + "title": "Ceiling" + }, + "failed": { + "description": "The check failed this measure.", + "title": "Failed", + "type": "boolean" + }, + "value": { + "description": "The measure; for `words`, the heard words' similarity to the line.", + "title": "Value", + "type": "number" + }, + "warn_only": { + "description": "A failure is warned and recorded but never re-rolled.", + "title": "Warn Only", + "type": "boolean" + } + }, + "required": [ + "value", + "ceiling", + "bound", + "warn_only", + "failed" + ], + "title": "ShotMeasure", + "type": "object" + }, + "ShotRecord": { + "additionalProperties": true, + "description": "One shot of a joined video: where an input landed in it, and for a\nchain's segment what its check recorded (`dw/shots.py` lists every key).\nOpen even in strict mode: a join may add detail of its own.", + "properties": { + "attempts": { + "description": "On a chain's shot: renders its check tried.", + "title": "Attempts", + "type": "integer" + }, + "audio_dbfs": { + "description": "On a chain's shot with generated audio: its kept audio's level.", + "title": "Audio Dbfs", + "type": "number" + }, + "check_failed": { + "description": "On a checked chain shot whose every attempt failed: the measures the kept one failed.", + "items": { + "type": "string" + }, + "title": "Check Failed", + "type": "array" + }, + "measures": { + "additionalProperties": { + "$ref": "#/components/schemas/ShotMeasure" + }, + "description": "On a chain's shot with the check on: every measure the kept attempt computed, by name. Absent with the check off, on a resumed segment, and on a job recorded before the field existed.", + "title": "Measures", + "type": "object" + }, + "name": { + "title": "Name", + "type": "string" + }, + "num_frames": { + "title": "Num Frames", + "type": "integer" + }, + "num_samples": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Null when the video has no track the join built.", + "title": "Num Samples" + }, + "planned_segments": { + "description": "On a chain's shot: the segment count its plan asked for.", + "title": "Planned Segments", + "type": "integer" + }, + "resumed": { + "description": "On a chain's shot: the segment was copied from an earlier run (resume_from).", + "title": "Resumed", + "type": "boolean" + }, + "segment_file": { + "description": "On a chain's shot under save_segments and keep_segments: its segment's file.", + "title": "Segment File", + "type": "string" + }, + "start_frame": { + "title": "Start Frame", + "type": "integer" + }, + "start_sample": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Null when the video has no track the join built.", + "title": "Start Sample" + } + }, + "required": [ + "name", + "start_frame", + "num_frames" + ], + "title": "ShotRecord", + "type": "object" + }, "StarRequest": { "properties": { "name": { From 9bdded11f6e086cac0b83d747d61e8ae0b665b02 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 07:59:41 -0600 Subject: [PATCH 258/412] feat(bench): #1465 - LongCat-Avatar 1.6 INT8 probe record: fits with block streaming, fails the 30 s gate Co-Authored-By: Claude Opus 5.5 --- bench/longcat_avatar_probe.py | 562 ++++++++++++++++++++++++++++++++ bench/records/longcat-avatar.md | 169 ++++++++++ bench/records/narrated.md | 6 + 3 files changed, 737 insertions(+) create mode 100644 bench/longcat_avatar_probe.py create mode 100644 bench/records/longcat-avatar.md diff --git a/bench/longcat_avatar_probe.py b/bench/longcat_avatar_probe.py new file mode 100644 index 000000000..d37981d6b --- /dev/null +++ b/bench/longcat_avatar_probe.py @@ -0,0 +1,562 @@ +"""LongCat-Video-Avatar 1.6 INT8 fit/take driver for #1465 (outside dw). + +Mirrors LongCat-Video/run_demo_avatar_single_audio_to_video.py (commit 58eb336e) with +the vendor modules unmodified, plus sequential placement so it fits one 24 GB card: +UMT5 runs on the GPU once to encode the prompt, then stays on the CPU; Whisper runs on +the GPU for the audio embedding, then is freed; then the INT8 DiT, both mix LoRAs and +the VAE go to the GPU for the windows. With --offload blocks (what fitted: the record, +`bench/records/longcat-avatar.md`) dit.blocks stay pinned on the CPU and each block is +swapped onto the GPU only for its own forward. Prints RECORD lines for the bench record. + +usage: python -I probe.py --image kf00.jpg --audio narration.wav --seconds 30 --out take + --offload blocks --prompt "a woman speaking to camera" +""" + +import argparse +import datetime +import gc +import json +import math +import os +import subprocess +import sys +import threading +import time +import types +from pathlib import Path + +os.environ.setdefault("RANK", "0") +os.environ.setdefault("WORLD_SIZE", "1") +os.environ.setdefault("MASTER_ADDR", "127.0.0.1") +os.environ.setdefault("MASTER_PORT", "29517") + +import numpy as np +import PIL.Image +import psutil +import soundfile as sf +import torch +import torch.distributed as dist + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE / "LongCat-Video")) + +from audio_separator.separator import Separator # noqa: E402 +from diffusers.utils import load_image # noqa: E402 +from transformers import AutoTokenizer, UMT5EncoderModel # noqa: E402 + +from longcat_video.audio_process import ( # noqa: E402 + get_audio_encoder, + get_audio_feature_extractor, +) +from longcat_video.audio_process.vocal_separator import separate_vocals # noqa: E402 +from longcat_video.context_parallel import context_parallel_util # noqa: E402 +from longcat_video.modules.autoencoder_kl_wan import AutoencoderKLWan # noqa: E402 +from longcat_video.modules.quantization import load_quantized_dit # noqa: E402 +from longcat_video.modules.scheduling_flow_match_euler_discrete import ( # noqa: E402 + FlowMatchEulerDiscreteScheduler, +) +from longcat_video.pipeline_longcat_video_avatar import ( # noqa: E402 + LongCatVideoAvatarPipeline, +) + +FFMPEG = str( + next( + (HERE / "venv/lib/python3.10/site-packages/imageio_ffmpeg/binaries").glob( + "ffmpeg-*" + ) + ) +) +NEG = ( + "Close-up, Bright tones, overexposed, static, blurred details, subtitles, style, works, " + "paintings, images, static, overall gray, worst quality, low quality, JPEG compression " + "residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, " + "deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, " + "three legs, many people in the background, walking backwards" +) +GB = 1024**3 + + +def record(**kv): + print("RECORD " + json.dumps(kv), flush=True) + + +class Monitor(threading.Thread): + """Peak host RSS (this process and children) and nvidia-smi used on GPU 0; enforces + the RSS and extra-window stop lines.""" + + def __init__(self, rss_stop_gb, window_stop_s): + super().__init__(daemon=True) + self.rss_stop_gb, self.window_stop_s = rss_stop_gb, window_stop_s + self.peak_rss = 0 + self.peak_smi = 0 + self.window = None # (index, start) of the running extra window + self.proc = psutil.Process() + + def rss(self): + total = self.proc.memory_info().rss + for c in self.proc.children(recursive=True): + try: + total += c.memory_info().rss + except psutil.Error: + pass + return total + + def mem(self): + """This process's RSS split into anonymous and file-backed (mmap'd weights).""" + kv = {} + with open("/proc/self/status") as fh: + for line in fh: + k, _, v = line.partition(":") + if k in ("VmRSS", "RssAnon", "RssFile"): + kv[k] = round(int(v.split()[0]) / 1024**2, 1) + kids = [ + (c.name(), round(c.memory_info().rss / GB, 1)) + for c in self.proc.children(recursive=True) + if c.is_running() + ] + return {"rss_gb": kv, "children": kids} + + def smi(self): + out = subprocess.run( + [ + "nvidia-smi", + "--query-gpu=memory.used", + "--format=csv,noheader,nounits", + "-i", + os.environ.get("CUDA_VISIBLE_DEVICES", "0").split(",")[0], + ], + capture_output=True, + text=True, + check=False, + ).stdout.strip() + return int(out) if out.isdigit() else 0 + + def run(self): + while True: + r = self.rss() + self.peak_rss = max(self.peak_rss, r) + self.peak_smi = max(self.peak_smi, self.smi()) + if r / GB > self.rss_stop_gb: + record( + stop="host RSS over limit", rss_gb=round(r / GB, 1), **self.mem() + ) + os._exit(3) + if self.window is not None: + idx, start = self.window + if time.time() - start > self.window_stop_s: + record( + stop="extra window over limit", + window=idx, + seconds=round(time.time() - start), + ) + os._exit(4) + time.sleep(1.0) + + +def stream_blocks(dit, dev, resident): + """The most aggressive offload: everything but dit.blocks on the GPU, the first + `resident` blocks too, and every other block's tensors kept pinned on the CPU and + swapped onto the GPU only for its own forward.""" + for name, child in dit.named_children(): + if name != "blocks": + child.to(dev) + for p in dit.parameters(recurse=False): + p.data = p.data.to(dev) + for b in dit.buffers(recurse=False): + b.data = b.data.to(dev) + for i, block in enumerate(dit.blocks): + if i < resident: + block.to(dev) + continue + tensors = list(block.parameters()) + list(block.buffers()) + pinned = [t.data.pin_memory() for t in tensors] + for t, c in zip(tensors, pinned): + t.data = c + + def pre(_m, _a, _kw=None, tensors=tensors, pinned=pinned): + for t, c in zip(tensors, pinned): + t.data = c.to(dev, non_blocking=True) + + def post(_m, _a, _o, tensors=tensors, pinned=pinned): + for t, c in zip(tensors, pinned): + t.data = c + + block.register_forward_pre_hook(pre) + block.register_forward_hook(post) + + +def write_video(frames, fps, wav, seconds, path): + """Encode RGB frames with the narration slice muxed on (libx264 crf 17, aac).""" + n, h, w, _ = frames.shape + cmd = [ + FFMPEG, + "-y", + "-loglevel", + "error", + "-f", + "rawvideo", + "-pix_fmt", + "rgb24", + "-s", + f"{w}x{h}", + "-r", + str(fps), + "-i", + "-", + "-i", + str(wav), + "-t", + f"{seconds:.3f}", + "-c:v", + "libx264", + "-crf", + "17", + "-pix_fmt", + "yuv420p", + "-c:a", + "aac", + "-b:a", + "192k", + "-shortest", + str(path), + ] + p = subprocess.Popen(cmd, stdin=subprocess.PIPE) + p.stdin.write(np.ascontiguousarray(frames).tobytes()) + p.stdin.close() + if p.wait() != 0: + raise RuntimeError("ffmpeg failed") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--image", required=True) + ap.add_argument("--audio", required=True) + ap.add_argument("--seconds", type=float, required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--prompt", default="a woman speaking to camera") + ap.add_argument("--seed", type=int, default=1) + ap.add_argument("--resolution", default="480p", choices=["480p"]) + ap.add_argument("--mix_steps", type=int, default=4) + ap.add_argument("--mix_alpha", type=float, default=1.0) + ap.add_argument("--offload", default="none", choices=["none", "blocks"]) + ap.add_argument("--resident_blocks", type=int, default=0) + ap.add_argument("--rss_stop_gb", type=float, default=90) + ap.add_argument("--window_stop_s", type=float, default=360) + args = ap.parse_args() + + ckpt = HERE / "weights/LongCat-Video-Avatar-1.6" + base = HERE / "weights/LongCat-Video" + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + model_type, fps, audio_stride = "avatar-v1.5", 25, 1 + num_frames, num_cond = 93, 13 + steps, tg, ag = 8, 1.0, 1.0 # use_distill for avatar-v1.5 + target = int(round(args.seconds * fps)) + segments = 1 + max(0, math.ceil((target - num_frames) / (num_frames - num_cond))) + record( + prompt=args.prompt, + seed=args.seed, + seconds=args.seconds, + segments=segments, + target_frames=target, + steps=steps, + mix_steps=args.mix_steps, + mix_alpha=args.mix_alpha, + offload=args.offload, + resident_blocks=args.resident_blocks, + ) + + mon = Monitor(args.rss_stop_gb, args.window_stop_s) + mon.start() + + # narration slice (the model's audio and the muxed track) + audio, sr = sf.read(args.audio, always_2d=True) + sl = out / "narration-slice.wav" + sf.write(sl, audio[: int(round(args.seconds * sr))], sr) + + torch.cuda.set_device(0) + dist.init_process_group(backend="nccl", timeout=datetime.timedelta(hours=24)) + context_parallel_util.init_context_parallel( + context_parallel_size=1, global_rank=0, world_size=1 + ) + cp_split_hw = context_parallel_util.get_optimal_split(1) + dev = torch.device("cuda:0") + t0 = time.time() + + tokenizer = AutoTokenizer.from_pretrained( + base, subfolder="tokenizer", torch_dtype=torch.bfloat16 + ) + text_encoder = UMT5EncoderModel.from_pretrained( + base, subfolder="text_encoder", torch_dtype=torch.bfloat16 + ) + vae = AutoencoderKLWan.from_pretrained( + base, subfolder="vae", torch_dtype=torch.bfloat16 + ) + scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained( + ckpt, subfolder="scheduler", torch_dtype=torch.bfloat16 + ) + pipe = LongCatVideoAvatarPipeline( + tokenizer=tokenizer, + text_encoder=text_encoder, + vae=vae, + scheduler=scheduler, + dit=None, + audio_encoder=None, + audio_feature_extractor=None, + model_type=model_type, + ) + pipe.device = dev + record(phase="umt5 loaded on cpu", seconds=round(time.time() - t0), **mon.mem()) + + # 1. UMT5 on the GPU once; the embeddings are cached for every window. Then only its + # config stays (generate_* read text_encoder.config.d_model): sequential loading keeps + # host RSS to one model at a time. + text_encoder.to(dev) + with torch.no_grad(): + pe, pm = pipe._get_t5_prompt_embeds( + prompt=[args.prompt], + num_videos_per_prompt=1, + max_sequence_length=512, + device=dev, + dtype=torch.bfloat16, + ) + ne, nm = pipe._get_t5_prompt_embeds( + prompt=[NEG], + num_videos_per_prompt=1, + max_sequence_length=512, + device=dev, + dtype=torch.bfloat16, + ) + pipe.text_encoder = types.SimpleNamespace( + config=text_encoder.config, dtype=torch.bfloat16 + ) + del text_encoder + gc.collect() + torch.cuda.empty_cache() + audio_encoder = get_audio_encoder(str(ckpt / "whisper-large-v3"), model_type) + pipe.audio_encoder = audio_encoder + pipe.audio_feature_extractor = get_audio_feature_extractor( + str(ckpt / "whisper-large-v3"), model_type + ) + + def encode_prompt( + prompt, negative_prompt=None, do_classifier_free_guidance=True, **_ + ): + if do_classifier_free_guidance: + return pe, pm, ne, nm + return pe, pm, None, None + + pipe.encode_prompt = encode_prompt + + # 2. vocal separation and Whisper on the GPU, then free them + tmp = out / "audio_temp" + sep = Separator( + output_dir=tmp / "vocals", + output_single_stem="vocals", + model_file_dir=str(ckpt / "vocal_separator"), + ) + if sep.onnx_execution_provider == ["CUDAExecutionProvider"]: + sep.onnx_execution_provider = [ + ( + "CUDAExecutionProvider", + {"device_id": 0, "cudnn_conv_algo_search": "HEURISTIC"}, + ) + ] + sep.load_model("Kim_Vocal_2.onnx") + gen_dur = num_frames / fps + (segments - 1) * (num_frames - num_cond) / fps + speech, asr = separate_vocals(sep, str(sl), duration=gen_dur + 1.0) + del sep + pad = math.ceil((gen_dur + 1.0 - len(speech) / asr) * asr) + if pad > 0: + speech = np.append(speech, [0.0] * pad) + audio_encoder.to(dev) + with torch.no_grad(): + full_emb = pipe.get_audio_embedding( + speech, + fps=fps * audio_stride, + device=dev, + sample_rate=asr, + model_type=model_type, + use_loudness_norm=False, + ) + if torch.isnan(full_emb).any(): + raise ValueError("broken audio embedding with nan values") + audio_encoder.to("cpu") + pipe.audio_encoder = None + del audio_encoder + gc.collect() + torch.cuda.empty_cache() + record( + phase="prompt and audio encoded", + seconds=round(time.time() - t0), + smi_peak_mib=mon.peak_smi, + **mon.mem(), + ) + + # 3. DiT + LoRAs + VAE on the GPU + dit = load_quantized_dit( + str(ckpt), subfolder="base_model_int8", cp_split_hw=cp_split_hw + ) + dit.load_lora( + str(ckpt / "loraA/lora.safetensors"), + "dmd", + multiplier=1.0, + lora_network_dim=128, + lora_network_alpha=64, + ) + dit.load_lora( + str(ckpt / "loraB/lora.safetensors"), + "opsd", + multiplier=1.0, + lora_network_dim=128, + lora_network_alpha=64, + ) + dit.enable_lora_mix("dmd", "opsd", args.mix_alpha, args.mix_steps) + record( + phase="dit loaded on cpu", + seconds=round(time.time() - t0), + dit_dtype=str(dit.dtype), + **mon.mem(), + ) + if dit.dtype != torch.bfloat16: + pe, ne = pe.to(dit.dtype), ne.to(dit.dtype) + pipe.dit = dit + if args.offload == "blocks": + stream_blocks(dit, dev, args.resident_blocks) + else: + dit.to(dev) + for lora_network in getattr(dit, "lora_dict", {}).values(): + for lora in lora_network.loras: + lora.to(dev) + vae.to(dev) + torch.cuda.synchronize() + record( + phase="dit on gpu", + allocated_gb=round(torch.cuda.memory_allocated() / GB, 2), + smi_mib=mon.smi(), + ) + + gen = torch.Generator(device=dev) + gen.manual_seed(args.seed) + idx = torch.arange(5) - 2 + + def emb_at(start): + c = torch.arange(start, start + audio_stride * num_frames, audio_stride) + c = torch.clamp(c.unsqueeze(1) + idx.unsqueeze(0), 0, full_emb.shape[0] - 1) + return full_emb[c][None, ...].to(dev) + + image = load_image(args.image) + times = [] + try: + torch.cuda.reset_peak_memory_stats() + ts = time.time() + output, latent = pipe.generate_ai2v( + image=image, + prompt=args.prompt, + negative_prompt=NEG, + resolution=args.resolution, + num_frames=num_frames, + num_inference_steps=steps, + text_guidance_scale=tg, + audio_guidance_scale=ag, + output_type="both", + generator=gen, + audio_emb=emb_at(0), + use_distill=True, + ) + torch.cuda.synchronize() + times.append(time.time() - ts) + frames = (output[0] * 255).astype(np.uint8) + h, w = frames.shape[1:3] + record( + window=1, + seconds=round(times[-1], 1), + max_allocated_gb=round(torch.cuda.max_memory_allocated() / GB, 2), + smi_peak_mib=mon.peak_smi, + rss_peak_gb=round(mon.peak_rss / GB, 1), + frame_size=f"{w}x{h}", + fps=fps, + ) + total = len(frames) + (segments - 1) * (num_frames - num_cond) + allf = np.empty((total, h, w, 3), np.uint8) + allf[: len(frames)] = frames + count = len(frames) + ref_latent = latent[:, :, :1].clone() + current = [PIL.Image.fromarray(f) for f in frames] + start = 0 + for seg in range(1, segments): + start += audio_stride * (num_frames - num_cond) + torch.cuda.reset_peak_memory_stats() + ts = time.time() + mon.window = (seg + 1, ts) + output, latent = pipe.generate_avc( + video=current, + video_latent=latent, + prompt=args.prompt, + negative_prompt=NEG, + height=h, + width=w, + num_frames=num_frames, + num_cond_frames=num_cond, + num_inference_steps=steps, + text_guidance_scale=tg, + audio_guidance_scale=ag, + generator=gen, + output_type="both", + use_kv_cache=args.mix_steps == 0, + offload_kv_cache=False, + enhance_hf=False, + audio_emb=emb_at(start), + ref_latent=ref_latent, + ref_img_index=10, + mask_frame_range=0, + use_distill=True, + ) + torch.cuda.synchronize() + mon.window = None + times.append(time.time() - ts) + new = (output[0] * 255).astype(np.uint8) + add = new[num_cond:] + allf[count : count + len(add)] = add + count += len(add) + current = [PIL.Image.fromarray(f) for f in new] + record( + window=seg + 1, + seconds=round(times[-1], 1), + max_allocated_gb=round(torch.cuda.max_memory_allocated() / GB, 2), + smi_peak_mib=mon.peak_smi, + rss_peak_gb=round(mon.peak_rss / GB, 1), + ) + except torch.cuda.OutOfMemoryError as e: + record( + stop="OOM at 480p", + windows_done=len(times), + max_allocated_gb=round(torch.cuda.max_memory_allocated() / GB, 2), + smi_peak_mib=mon.peak_smi, + error=str(e)[:300], + ) + sys.exit(2) + + allf = allf[: min(count, target)] + take = out / "take.mp4" + write_video(allf, fps, sl, args.seconds, take) + + PIL.Image.fromarray(allf[int(round(0.5 * fps))]).save(out / "ref-0.5s.png") + record( + done=str(take), + frames=len(allf), + seconds_out=round(len(allf) / fps, 2), + first_window_s=round(times[0], 1), + extra_window_mean_s=round(float(np.mean(times[1:])), 1) + if len(times) > 1 + else None, + extra_window_max_s=round(max(times[1:]), 1) if len(times) > 1 else None, + smi_peak_mib=mon.peak_smi, + rss_peak_gb=round(mon.peak_rss / GB, 1), + wall_s=round(time.time() - t0), + ) + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/bench/records/longcat-avatar.md b/bench/records/longcat-avatar.md new file mode 100644 index 000000000..8552969e2 --- /dev/null +++ b/bench/records/longcat-avatar.md @@ -0,0 +1,169 @@ +# LongCat-Video-Avatar 1.6 INT8 probe (2026-11-19, #1465 of #1443) - 30 s gate, seed 1 + +**Result: it fits one 24 GB 3090 only with the DiT's blocks streamed from pinned host +memory. At that offload, an extra window takes 255 s. The 30 s take fails the gate on +two of four thresholds: SFace to kf00, and 256 px Laplacian sharpness. The 86 s take +was not run.** + +Recorded by claude-opus-5-5 (anthropic). + +## Setup + +All of this ran outside dw, in `lem:~/spikes/longcat-avatar/`, on cuda:0 alone +(`CUDA_VISIBLE_DEVICES=0`), and only while dw-serve had no queued or running job. + +- **Preflight:** 626G free on `/` at 2026-11-19 12:00:46 UTC (`preflight-df.txt`), above + the 60 GB floor. After the download, 572G was free. Nothing was deleted. +- **Vendor code:** `meituan-longcat/LongCat-Video` at + `58eb336edc5c8c63389838727e40b8c18434e54e` (`LongCat-Video/`), unmodified. +- **Venv:** `venv/`, a fresh uv venv. + - Python 3.10.22, torch 2.6.0+cu124, diffusers 0.35.1, transformers 4.41.0. + - flash_attn 2.7.4.post1 came from the prebuilt wheel. No CUDA extension was built from + source, so the build-failure stop never came into play. + - setuptools 84.2.1 was added after the first demo run. triton imports it, and a uv + venv doesn't ship it. +- **Weights:** about 46 GB, downloaded with `hf download --include` (`dl.sh`), with HF_HOME + under the spike dir. + + | repo @ revision | part | size | + |---|---|---| + | `meituan-longcat/LongCat-Video-Avatar-1.6` @ `acfc6282…` | `base_model_int8` | 15G | + | | `loraA` (dmd) | 2.4G | + | | `loraB` (opsd) | 2.4G | + | | `whisper-large-v3` | 2.9G | + | | `vocal_separator` | 64M | + | | config, scheduler | <1M | + | `meituan-longcat/LongCat-Video` @ `03b55529…` | `text_encoder` (UMT5, fp32 on disk) | 22G | + | | `vae` | 485M | + | | `tokenizer` | 21M | + + The plan estimated about 36 GB. The difference is the fp32 UMT5. +- **Driver:** `bench/longcat_avatar_probe.py`, run as `probe.sh `, which + calls `venv/bin/python -I` under `/usr/bin/time -v` with + `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`. + - It mirrors the vendor's `run_demo_avatar_single_audio_to_video.py` using the vendor + modules: avatar-v1.6, INT8 DiT, distill, 8 steps, guidance 1.0/1.0, mix_steps 4 with + mix_alpha 1.0, 480p bucket, 93-frame windows, 13 conditioning frames, 25 fps. + - Its stops are: OOM, host RSS over 90 GB (summed over the process and its children), + and an extra window over 360 s. + +## Fit + +| run | placement | outcome | +|---|---|---| +| vendor demo (`demo.sh`, torchrun, vendor sample `single_example_1.json`) | the vendor's own: whole pipe `.to(cuda)` | **OOM at load**, in `pipe.to(cuda)`: 22.81 GiB allocated, nvidia-smi peak 24107 MiB; max RSS 85.6 GiB; 2:02 wall | +| probe 1, vendor sample 7 s | every model built on the CPU at once | **host-RSS stop** at 90.9 GB summed (time -v max RSS 85.7 GB); exit 3 before any window | +| probe 2, vendor sample 7 s | sequential: UMT5 on GPU to encode then freed; Whisper on GPU to embed then freed; INT8 DiT + LoRAs + VAE resident | **OOM in window 1**: the DiT on the GPU took 17.57 GB allocated (smi 18661 MiB); max allocated 22.4 GB when it tried to allocate 576 MiB more | +| **probe 3, vendor sample 7 s** | sequential, plus `--offload blocks`: `dit.blocks` pinned on the CPU, each block swapped onto the GPU for its own forward; the rest of the DiT, the LoRAs and the VAE resident | **fits.** 175 frames, 768x512, 25 fps | +| **30 s take on kf00** | same as probe 3 | **fits.** 750 frames, **832x480, 25 fps** (native) | + +Probe 3 is the most aggressive offload the plan's OOM stop refers to. It is the first that +fitted, so the stop did not fire. + +Measured on the kf00 30 s take (`probe-kf00-30s.log`): + +| | | +|---|---| +| peak VRAM | `max_memory_allocated` 10.25 GB; nvidia-smi peak 13473 MiB | +| host RSS | 80.2 GB max (time -v), 83.8 GB summed over the process tree. It sits close to the 90 GB stop because the pinned DiT and the CPU copies sit side by side during placement | +| prompt + audio phase | nvidia-smi peak 11.7 GB | +| load to first window | about 2 min: UMT5 loaded 18 s, encoded 35-45 s, DiT loaded 117-131 s | +| first window (93 frames, 3.72 s) | 255.9 s | +| each extra window (80 frames, 3.2 s) | 255.4 s mean, 255.6 s max (stop: 360 s) | +| 30 s take | 10 windows, 45:08 wall | + +On the vendor sample the windows ran 249.5 s, then 247.4 and 247.2 s. + +That rate is about 80 s of GPU per second of video. An 86 s take would be 27 windows, +about 1 h 55 min. + +The audio separator's onnxruntime CUDA provider failed to load (`libcudnn_adv.so.9` +missing) and ran on the CPU. It is not in the timed windows. + +## 30 s take + +- **Inputs:** + - the still: kf00 (`asset:uploads/bench/keyframes-v2/kf00.jpg`); + - the narration: the first 30.0 s of `asset:bench/constitution-narration-retimed.wav`; + - seed 1, 480p; + - prompt **"a woman speaking to camera"**. +- The narration slice is muxed onto the take as AAC. + +Measured with `bench/ks2v_gate.py --ref kf00 --crop256 --windows 0-10,20-30`, with both +takes in one run (`out/kf00-30s/gate.txt`). The H3 keeper is job 514b463a855f, run +`20261110-230854-abc647e9`. + +| at 0.5/5/10/15/20/25/29.5 s | H3 moving keystone s1 (keeper) | **LongCat-Avatar 1.6 INT8** | +|---|---|---| +| SFace to its own 0.5 s face | 1/.87/.93/.95/.92/.88/.94 | **1/.84/.89/.81/.88/.91/.90** | +| SFace to kf00 | .93/.86/.92/.95/.93/.87/.91 | **.93/.83/.89/.80/.90/.86/.89** | +| saturation | 105.3/104.8/107.1/100.1/110.0/109.3/107.3 | **94.8/93.0/91.5/87.6/98.7/89.9/95.2** | +| face-crop Laplacian, native scale | 312/208/210/308/343/304/260 | **560/174/379/372/700/438/251** | +| face-crop Laplacian, 256 px | 487/303/367/504/545/415/505 | **265/102/209/199/367/249/141** | +| still-mouth bins, 0-30 s | 0 of 60 | **0 of 62** | + +| 10 s windows (box crop: 256 px Laplacian / saturation / SFace to the 0.5 s face) | H3 keeper | **LongCat-Avatar** | +|---|---|---| +| 0-10 s | 448 / 101.6 / .94 | **273 / 93.9 / .89** | +| 20-30 s | 537 / 106.1 / .93 | **254 / 94.6 / .90** | + +The native-scale Laplacian runs high, but the 256 px figure runs low. At 832x480 the face +crop is small, so its native variance counts pixel-level edges. Scaled to the common +256 px, the face carries about half the H3 keeper's detail. + +## Gate (edges inclusive) + +| threshold | LongCat-Avatar at 30 s | | +|---|---|---| +| SFace to kf00 ≥ 0.88 at every sample | .83 at 5 s, .80 at 15 s, .86 at 25 s | **fails** | +| saturation rise from 0.5 s ≤ 5 | 94.8 → 98.7 at most, +3.9 | passes | +| 256 px Laplacian at 20-30 s ≥ 410 | 254 | **fails** | +| still-mouth bins over 0-30 s ≤ 3 | 0 of 62 | passes | + +**The gate fails, so the 86 s take was not run, as the plan says.** + +The H3 keeper itself reads .86 at 5 s and .87 at 25 s to kf00 on these samples, so the +SFace bar is tight. LongCat's 0.80 at 15 s is below anything the keeper reads, and its +sharpness miss is wide: 254 against 410. + +## Contact sheet + +`out/kf00-30s/kf00-30s-faces.jpg`: LongCat (row 1) beside the H3 keeper (row 2) at +0.5/15/29.5 s. `gate-faces.jpg` has the same at all seven samples. + +Reading the seven-sample sheet: +- **Identity:** the woman is recognisably the same throughout. The hair, earrings, scarf, + coat and plate hold. +- **Skin:** smoother and flatter than H3. The forehead and cheek folds the keeper keeps + are softened. +- **Colour:** the face sits darker and less saturated than H3's from the first frame + (94.8 against 105.3). +- **Eyes:** the lids get heavier at 5 s and 15 s, and these are the SFace dips. +- **Mouth:** very active and articulate, opening wide at 29.5 s. No still-mouth bins. +- **Camera:** static and frontal, since the still is all it gets. There is no moving + keystone. + +## Deviations from plan v2 + +- **setuptools** was added to the venv, because triton needs it. +- **Models loaded in sequence**, with UMT5 and Whisper freed after use, and **the DiT's + blocks streamed** (`--offload blocks`). The vendor's all-resident placement OOMs on 24 GB. +- **No separate 7 s fit on kf00.** The fit and timing ran on the vendor sample. The 30 s + kf00 take measures the same numbers on kf00 (above). +- **The audio separator ran on the CPU**, because onnxruntime-gpu lacks cuDNN 9 adv. +- **Downloads came to about 46 GB, against the planned 36 GB**, because of the fp32 UMT5. +- **Uploads were staged through the workspace directory.** `upload_asset` reads only + inside the workspace, so each file was copied into a temporary folder there, uploaded, + and the folder removed. +- **The RSS stop sums the process tree.** `time -v` max RSS reads about 4 GB lower. + +## Files on the server (workspace `constitution-walk-3`) + +- the take, with sound: `asset:uploads/bench/longcat-avatar/kf00-30s-s1.mp4`; +- the contact sheet: `asset:uploads/bench/longcat-avatar/kf00-30s-faces.jpg`; +- the seven-sample sheet: `asset:uploads/bench/longcat-avatar/kf00-30s-gate-faces.jpg`; +- the 0.5 s reference frame: `asset:uploads/bench/longcat-avatar/kf00-30s-ref-0.5s.png`. + +The vendor-sample fit output is `lem:~/spikes/longcat-avatar/out/vendor-7s/take.mp4`. +The venv, the weights (about 46 GB) and the logs stay in `lem:~/spikes/longcat-avatar/`. +Deleting them is Don's call. diff --git a/bench/records/narrated.md b/bench/records/narrated.md index 6636e7a2f..be030b4e6 100644 --- a/bench/records/narrated.md +++ b/bench/records/narrated.md @@ -1092,3 +1092,9 @@ Pro over the same 20 s. The earrings, scarf and background hold in every row. Pro at 4-bit is softer than Lite distilled at the start (114 against 159 at 0.5 s) and loses identity faster. Whether 4-bit SDNQ caused this or Pro does it anyway isn't isolated: an unquantized Pro (21B) needs about 42 GB for its transformer alone. + +## LongCat-Video-Avatar 1.6 INT8 (2026-11-19, #1465) + +It fits a 3090 only with block streaming, at 255 s per extra window. It fails the 30 s +gate on SFace to kf00 (0.80 at 15 s) and on 256 px sharpness (254 against 410 at +20-30 s). See `bench/records/longcat-avatar.md`. From edc17db52d385b2dbae3695039adb19191ae1767 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 08:01:33 -0600 Subject: [PATCH 259/412] fix(deploy): #1493 - tolerate the process gap in a healthy systemd restart Co-Authored-By: Claude Sonnet 5.5 --- scripts/deploy.sh | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/scripts/deploy.sh b/scripts/deploy.sh index ac32c10f7..3b2fd4247 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -247,6 +247,12 @@ say "started; log: $LOG" fi # 5. wait for health +# A restart has a window where the old process is gone and the new one is not +# yet found (the old one can take ~5 s to stop), so a missing process counts +# only after it stays missing for GONE_GRACE seconds, or at once if systemd +# reports the unit failed. +GONE_GRACE=30 +gone=0 for i in $(seq 1 120); do h="$(health || true)" if echo "$h" | grep -q '"status":"ok"'; then @@ -254,7 +260,14 @@ for i in $(seq 1 120); do say "deployed $branch @ $(git rev-parse --short HEAD)" exit 0 fi - server_running || { say "dw.serve exited during startup; last log lines ($LOG_HINT):"; tail_log; exit 1; } + if server_running; then + gone=0 + else + gone=$((gone + 1)) + if [ "$gone" -ge "$GONE_GRACE" ] || systemctl --user is-failed --quiet dw-serve 2>/dev/null; then + say "dw.serve exited during startup; last log lines ($LOG_HINT):"; tail_log; exit 1 + fi + fi sleep 1 done say "no healthy answer within 120 s; last log lines ($LOG_HINT):"; tail_log; exit 1 From f502ab25adc11d5b65375dca5cf3d31fd5e8f33a Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 08:05:39 -0600 Subject: [PATCH 260/412] feat(bench): #1394 - record Don's verdict: gate failed, stop Co-Authored-By: Claude Opus 5.5 --- bench/records/narrated.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/bench/records/narrated.md b/bench/records/narrated.md index 2dbc446af..c3dd7cb81 100644 --- a/bench/records/narrated.md +++ b/bench/records/narrated.md @@ -1095,9 +1095,9 @@ isolated: an unquantized Pro (21B) needs about 42 GB for its transformer alone. ## Keystone attention: step 1, the block-numbering check (#1391 stage B, #1394) -Status: **step 1 and the early gate.** Don ruled on 2026-11-18 that step 2 doesn't -run, the gate does, and the full arms wait for his ruling on the gate (see *Keystone -attention: early gate* below). +Status: **closed, gate failed.** Don ruled on 2026-11-18 that step 2 doesn't run and +the gate does. The gate failed, and on 2026-11-19, after viewing both takes, he stopped +the bench there: no full arms (see *Keystone attention: early gate* below). The method is roycho87's brightened-keystone test (#1391 issuecomment-6922271175), after NerdNotes test 19 (CC BY-SA 4.0, concepts only). See `docs/ATTRIBUTIONS.md`. @@ -1271,3 +1271,10 @@ How to read it: going back to step 2 with a narrower set of groups, which is Don's call. - A positive result here would still be a dense-attention result, while the shipped templates run sparse (Q5). + +### Don's verdict (2026-11-19) + +**Gate failed. Stop here.** Don watched both takes and saw no clear win. Neither step 2 +with narrower groups nor the full arms runs, and no more lem time goes to this. Stage A's +`experimental_keystone_attention` stays experimental and behind the flag. The chain key +and the moving-shot arm stay cut (plan v4's non-goals): nothing here brings them back. From 10691e8fdf6b5c26e1e30f3827c9b38e67a1def3 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 08:13:49 -0600 Subject: [PATCH 261/412] feat(ui): #1477 - findings and Assess in the gallery detail The detail panel lists the metadata reply's level findings (warn first, the server's words, a timed one's place as m:ss.s). On a video or audio file, Assess GETs /api/gallery/{name}/assess and replaces the list with its reply, under a muted line of the rules applied and each probe that did not apply. Results are held for the page's life, by workspace and file; a refusal shows beneath the list it keeps. A still's button is disabled with the server's reason as its title. Local narrowed types per the plan's Q1 (no server response_model), so the twin guard lists the assess route as outside the contract. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 2 +- docs/SERVER.md | 10 ++ tests/test_ui_twins.py | 4 + ui/e2e/gallery-findings.spec.ts | 123 ++++++++++++++++++++++ ui/src/app.css | 10 ++ ui/src/lib/api.test.ts | 17 +++ ui/src/lib/api.ts | 6 ++ ui/src/lib/gallery/GalleryDetail.svelte | 42 +++++++- ui/src/lib/gallery/GalleryDetail.test.ts | 120 ++++++++++++++++++++- ui/src/lib/gallery/GalleryFindings.svelte | 94 +++++++++++++++++ ui/src/lib/gallery/assess.svelte.ts | 69 ++++++++++++ ui/src/lib/pages/GalleryPage.svelte | 15 ++- ui/src/lib/pages/GalleryPage.test.ts | 24 +++++ ui/src/lib/types.ts | 19 ++++ 14 files changed, 547 insertions(+), 8 deletions(-) create mode 100644 ui/e2e/gallery-findings.spec.ts create mode 100644 ui/src/lib/gallery/GalleryFindings.svelte create mode 100644 ui/src/lib/gallery/assess.svelte.ts diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f032a9057..a6db618c5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -219,7 +219,7 @@ one to open. | Inline images | `dw/server/inline_media.py` | Fitting an image to a longest side and halving it under a base64 budget happens on the server, for `/image` and `/frames` alike; `dw_mcp` forwards the size and budget and imports no Pillow. | `tests/test_server_gallery_image.py`, `tests/test_mcp_server.py::TestStartupWeight::test_the_server_starts_without_importing_the_engine` | | Workflow patch | `dw/library.py`: `merge_patch`; `dw/server/routes/library.py`: `patch_workflow` | A merge patch is applied on the server under the lock `PUT` takes; no client reads, merges and writes back. | `tests/test_server_library_path.py::TestPatchWorkflow::test_patch_merges_onto_the_stored_definition` | | Deleting a job's run | `dw/server/jobs.py`: `JobManager.run_location`; `dw/server/outputs.py`: `delete_run_directory` | The server resolves a job's run directory against the root the job ran in, and refuses a job still queued or running. | `tests/test_server_jobs.py::TestDeleteAJobsRun::test_a_running_job_is_409` | -| Level findings | `dw/server/assess.py`: `level_findings` | Gallery metadata reports level problems from `dw/audio_qc.py`'s thresholds; no client restates a threshold. The silent-by-design exemption to the near-silent rule is `dw/audio_qc.py`: `all_shots_silent_by_design`, used by this row and by the write-time warning. | `tests/test_server_assess.py::TestMetadataLevelFindings::test_level_findings_read_audio_qc_thresholds` | +| Level findings | `dw/server/assess.py`: `level_findings` | Gallery metadata reports level problems from `dw/audio_qc.py`'s thresholds; no client restates a threshold. The web UI shows them, and an Assess reply's findings, in the gallery detail as the server sends them (`ui/src/lib/gallery/GalleryFindings.svelte`), deriving no severity or threshold of its own. The silent-by-design exemption to the near-silent rule is `dw/audio_qc.py`: `all_shots_silent_by_design`, used by this row and by the write-time warning. | `tests/test_server_assess.py::TestMetadataLevelFindings::test_level_findings_read_audio_qc_thresholds`, `ui/src/lib/gallery/GalleryDetail.test.ts` | | API errors | `dw_mcp/client.py` | An API failure becomes a message a person can act on, here and nowhere else. | `tests/test_mcp_client.py::test_a_400_surfaces_the_servers_detail_verbatim` | ## UI diff --git a/docs/SERVER.md b/docs/SERVER.md index 2db55a2de..e6cfbce84 100644 --- a/docs/SERVER.md +++ b/docs/SERVER.md @@ -235,6 +235,16 @@ icon, a finish-alert toggle, the theme toggle, and links to these docs and zip, is deleted in bulk (anything that fails to delete stays selected), or, for two to four files, opens in Compare. + The panel's **Findings** list the level findings the metadata reply + carries (warn first, each with the server's words and, for a timed one, + its place as m:ss.s). On a video or audio file, **Assess** runs every + assessment probe through `GET /api/gallery/{name}/assess` - read-only, + nothing queued or stored - and replaces the list with its reply, under a + muted line naming the rules applied and each probe that did not apply, in + the server's reason. The result is held for the page's life, by workspace + and file; a refusal shows beneath the list it leaves in place. On a still + the button is disabled and its title says why. + ![A gallery file's detail panel: the poster, its run and settings, a note, Keep as asset and open as workflow](img/ui-gallery-detail.jpg) - **Compare** - two to four outputs side by side, with the arguments that diff --git a/tests/test_ui_twins.py b/tests/test_ui_twins.py index 53858b5dd..e93f10af3 100644 --- a/tests/test_ui_twins.py +++ b/tests/test_ui_twins.py @@ -255,6 +255,10 @@ def test_the_ui_offload_modes_are_the_schemas(): "/api/assets/archive", "/api/workflows/{}/download", "/api/prompts/{}/download", + # The assess reply varies with `probe`/`detail` and MCP reads keys a model + # would filter (`probes`), so it has no response_model; the UI's narrowed + # `AssessReply` in ui/src/lib/types.ts names this route (#1452 plan, Q1) + "/api/gallery/{}/assess", } # The raw workflow/prompt GETs serve the file verbatim; their PUT and DELETE # on the same path are in the contract diff --git a/ui/e2e/gallery-findings.spec.ts b/ui/e2e/gallery-findings.spec.ts new file mode 100644 index 000000000..29977da6e --- /dev/null +++ b/ui/e2e/gallery-findings.spec.ts @@ -0,0 +1,123 @@ +import { expect, test, type Page } from '@playwright/test' + +// The gallery detail's Findings and Assess (#1477), on a mocked gallery: one +// video whose metadata carries a level finding, and an Assess reply with one +// warn and one info finding and a probe that did not apply. Screenshots of +// the detail in both themes land in this spec's test-results folder. + +const NAME = 'clip/run-1/final/clip.mp4' + +const video = { + name: NAME, + folder: 'clip', + subfolder: 'final', + run_id: 'run-1', + version: 1, + url: `/outputs/${NAME}`, + kind: 'video', + size: 2048, + mtime: 1_700_000_000, + label: 'clip.mp4', + role: 'final', +} + +const nearSilent = { + rule: 'near_silent', + severity: 'warn', + at: null, + value: -62.1, + threshold: -50, + says: 'near-silent for a track meant to be heard; check the step that made it, or raise it with normalize_audio', +} + +const assessReply = { + name: NAME, + source: 'output', + kind: 'video', + shots_source: 'none', + findings: [ + nearSilent, + { + rule: 'seam_frame_jump', + severity: 'info', + at: 64.25, + value: 0.4, + threshold: 0.3, + says: 'the picture jumps at the cut', + }, + ], + rules_applied: ['full_scale', 'near_silent', 'shot_dead_air'], + rules_skipped: [], + not_applicable: { + analyze_seams: + 'no shot boundaries recorded for this file - analyze_seams needs two or more shots', + }, +} + +async function mockGallery(page: Page) { + const assessCalls: string[] = [] + await page.route('**/api/gallery?**', (route) => + route.fulfill({ + json: { + files: [video], + folders: ['clip'], + subfolders: ['final'], + limit: 200, + offset: 0, + total: 1, + workspace: 'default', + }, + }), + ) + await page.route('**/api/gallery/**/metadata**', (route) => + route.fulfill({ + json: { + name: NAME, + source: 'output', + run_id: 'run-1', + version: 1, + role: 'final', + job: null, + metadata: null, + media: null, + inputs: [], + findings: [nearSilent], + }, + }), + ) + await page.route('**/api/gallery/**/assess**', (route) => { + assessCalls.push(route.request().method()) + return route.fulfill({ json: assessReply }) + }) + // No media is served: the panel is what is being looked at + await page.route('**/outputs/**', (route) => route.fulfill({ status: 404 })) + return assessCalls +} + +for (const theme of ['light', 'dark'] as const) { + test(`findings and Assess in the gallery detail (${theme})`, async ({ + page, + }, testInfo) => { + await page.emulateMedia({ colorScheme: theme }) + const assessCalls = await mockGallery(page) + await page.goto('/#/ws/default/gallery') + await page.locator('button.cell').first().click() + + const findings = page.getByRole('region', { name: 'Findings' }) + // The metadata's level finding shows without a click + await expect(findings).toContainText('near-silent') + + const assess = page.getByRole('button', { name: 'Assess' }) + await expect(assess).toBeEnabled() + await assess.click() + await expect(findings.locator('li')).toHaveCount(2) + await expect(findings.locator('li').first()).toContainText('warn') + await expect(findings.locator('li').nth(1)).toContainText('1:04.3') + await expect(findings).toContainText('analyze_seams not applicable') + expect(assessCalls).toEqual(['GET']) + + await page.locator('.detail').screenshot({ + path: testInfo.outputPath(`gallery-findings-${theme}.png`), + }) + }) +} diff --git a/ui/src/app.css b/ui/src/app.css index 314c2c75d..85b18e3ae 100644 --- a/ui/src/app.css +++ b/ui/src/app.css @@ -13,6 +13,8 @@ * - `--select` (a cool blue) is the user's place: the open workspace, the * active nav section and the focus ring. It stays in the chrome - the * sidebar and focus - never in a surface behind an image. + * - `--finding-warn` / `--finding-info` mark an assessment finding's + * severity in the gallery detail: a place to look, not machine state. * - a workspace's own dot (`wsColor()` in src/lib/wsColor.ts) identifies * it in the sidebar and breadcrumb. It is identity, not state. * @@ -46,6 +48,8 @@ --good: #2f6b3f; --bad: #a33224; --warn: #a85b00; + --finding-warn: #a04400; + --finding-info: #3d6470; color-scheme: light; } @@ -65,6 +69,8 @@ --good: #6fbf87; --bad: #e3796a; --warn: #e8a33d; + --finding-warn: #f0a05a; + --finding-info: #8fb8c4; color-scheme: dark; } } @@ -83,6 +89,8 @@ --good: #6fbf87; --bad: #e3796a; --warn: #e8a33d; + --finding-warn: #f0a05a; + --finding-info: #8fb8c4; color-scheme: dark; } @@ -100,6 +108,8 @@ --good: #2f6b3f; --bad: #a33224; --warn: #a85b00; + --finding-warn: #a04400; + --finding-info: #3d6470; color-scheme: light; } diff --git a/ui/src/lib/api.test.ts b/ui/src/lib/api.test.ts index cfb7feb0f..0d7f1c897 100644 --- a/ui/src/lib/api.test.ts +++ b/ui/src/lib/api.test.ts @@ -126,6 +126,23 @@ describe('name encoding', () => { ) expect(calls[1][0]).toBe('/api/gallery/ltx/wf-gen.0-0.0%20copy.png') }) + + it("GETs a file's assess route, scoped to the picker's workspace", async () => { + const { workspace, DEFAULT_WORKSPACE } = await import('./workspace.svelte') + const calls = stubFetch({ ok: true, body: {} }) + await api.assess('ltx/run-1/final/clip one.mp4') + expect(calls[0][0]).toBe( + '/api/gallery/ltx/run-1/final/clip%20one.mp4/assess', + ) + expect(calls[0][1]?.method ?? 'GET').toBe('GET') + workspace.current = 'studio' + try { + await api.assess('a.mp4') + expect(calls[1][0]).toBe('/api/gallery/a.mp4/assess?workspace=studio') + } finally { + workspace.current = DEFAULT_WORKSPACE + } + }) }) describe('job listing', () => { diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index f933508e2..151d9289b 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -12,6 +12,7 @@ import type { EnhancerPresets, GalleryList, GalleryMetadata, + AssessReply, HealthInfo, JobCancelled, JobDetail, @@ -346,6 +347,11 @@ export const api = { undefined, { scope: workspace === undefined }, ), + /** Run every assessment probe that applies to one output, in the + * server's threadpool: a GET, scoped to the picker's workspace. It decodes + * the whole file, so only a click calls it, never a poll. */ + assess: (name: string) => + request(`/api/gallery/${encodePath(name)}/assess`), galleryThumbnailUrl, deleteOutput: (name: string) => request(`/api/gallery/${encodePath(name)}`, { diff --git a/ui/src/lib/gallery/GalleryDetail.svelte b/ui/src/lib/gallery/GalleryDetail.svelte index 416d25131..7e56b0e7e 100644 --- a/ui/src/lib/gallery/GalleryDetail.svelte +++ b/ui/src/lib/gallery/GalleryDetail.svelte @@ -1,12 +1,19 @@ + +
+ Findings + {#if rows.length} +
    + {#each rows as row, i (i)} +
  • + {row.severity} + {row.says} + {#if formatAt(row.at)} + {formatAt(row.at)} + {/if} +
  • + {/each} +
+ {:else} +
No findings
+ {/if} + {#if assessed?.reply} +
{measuredLine(assessed.reply)}
+ {/if} + {#if assessed?.error} + + {/if} +
+ + diff --git a/ui/src/lib/gallery/assess.svelte.ts b/ui/src/lib/gallery/assess.svelte.ts new file mode 100644 index 000000000..9c4f1ec92 --- /dev/null +++ b/ui/src/lib/gallery/assess.svelte.ts @@ -0,0 +1,69 @@ +import { SvelteMap } from 'svelte/reactivity' +import { api } from '../api' +import type { AssessReply } from '../types' + +/** One output's Assess: running, its reply, or the server's refusal. A + * failure keeps the reply before it, so the list shown stays the last one + * the server measured. */ +export type AssessState = { + running: boolean + reply: AssessReply | null + error: string | null +} + +/** Assess results by output, held for the page's life and never persisted - + * the route stores nothing either. Keyed by workspace and name, since the + * same name in another workspace is another file. */ +export class AssessCache { + #entries = new SvelteMap() + + static key = (workspace: string, name: string) => `${workspace}\u0000${name}` + + get(key: string): AssessState | undefined { + return this.#entries.get(key) + } + + /** Assess one output. A second click while one runs does nothing. */ + async run(key: string, name: string): Promise { + const before = this.#entries.get(key) + if (before?.running) return + const reply = before?.reply ?? null + this.#entries.set(key, { running: true, reply, error: null }) + try { + const next = await api.assess(name) + this.#entries.set(key, { running: false, reply: next, error: null }) + } catch (e) { + const error = e instanceof Error ? e.message : String(e) + this.#entries.set(key, { running: false, reply, error }) + } + } +} + +/** Warn rows first, otherwise in the server's order - what the server sends + * already is; the stable sort keeps a list from anywhere else honest. */ +export const warnFirst = (rows: T[]): T[] => + [...rows].sort( + (a, b) => Number(a.severity === 'info') - Number(b.severity === 'info'), + ) + +/** Seconds into the file as m:ss.s, or null when the finding has no place. */ +export function formatAt(at: unknown): string | null { + if (typeof at !== 'number' || !Number.isFinite(at) || at < 0) return null + const tenths = Math.round(at * 10) + const minutes = Math.floor(tenths / 600) + const seconds = (tenths % 600) / 10 + return `${minutes}:${seconds.toFixed(1).padStart(4, '0')}` +} + +/** The muted line under an assessed list: what was measured, and each probe + * that could not be, with the server's reason - so "no findings" reads + * apart from "nothing measured". */ +export function measuredLine(reply: AssessReply): string { + const applied = reply.rules_applied.length + ? `rules applied: ${reply.rules_applied.join(', ')}` + : 'no rules applied' + const skipped = Object.entries(reply.not_applicable ?? {}).map( + ([probe, why]) => `${probe} not applicable (${why})`, + ) + return [applied, ...skipped].join(' · ') +} diff --git a/ui/src/lib/pages/GalleryPage.svelte b/ui/src/lib/pages/GalleryPage.svelte index f0d0f9657..9b1127734 100644 --- a/ui/src/lib/pages/GalleryPage.svelte +++ b/ui/src/lib/pages/GalleryPage.svelte @@ -11,10 +11,16 @@ import { overlayOpen } from '../ui/layers.svelte' import { notify } from '../toast' import { confirmDialog } from '../confirm.svelte' - import type { GalleryFile, GalleryInput, OutputRole } from '../types' + import type { + GalleryFile, + GalleryInput, + LevelFinding, + OutputRole, + } from '../types' import { workspace } from '../workspace.svelte' import { go } from '../router.svelte' import GalleryDetail from '../gallery/GalleryDetail.svelte' + import { AssessCache } from '../gallery/assess.svelte' import RoleTag from '../gallery/RoleTag.svelte' let files = $state([]) @@ -38,6 +44,9 @@ }>({ note: null, runNote: null, source: null }) let sourceJob = $state<{ id: string; status: string } | null>(null) let role = $state(null) + // The selected file's level findings, and every Assess this page has run + let findings = $state([]) + const assessCache = new AssessCache() let inputs = $state([]) function loadListing() { @@ -166,6 +175,7 @@ sourceJob = null role = null inputs = [] + findings = [] noteInfo = { note: null, runNote: null, source: null } api .galleryMetadata(file.name) @@ -175,6 +185,7 @@ sourceJob = r.job role = r.role ?? file.role ?? null inputs = r.inputs ?? [] + findings = r.findings ?? [] noteInfo = { note: r.note ?? null, runNote: r.run_note ?? null, @@ -425,6 +436,8 @@ {sourceJob} {role} {inputs} + {findings} + {assessCache} note={noteInfo.note} runNote={noteInfo.runNote} noteSource={noteInfo.source} diff --git a/ui/src/lib/pages/GalleryPage.test.ts b/ui/src/lib/pages/GalleryPage.test.ts index a0ebb630c..e67fe8c1d 100644 --- a/ui/src/lib/pages/GalleryPage.test.ts +++ b/ui/src/lib/pages/GalleryPage.test.ts @@ -69,6 +69,7 @@ vi.mock('../api', () => ({ setStarred: (name: string, starred: boolean) => setStarred(name, starred), archiveOutputs: (names: string[]) => archiveOutputs(names), galleryMetadata: (name: string) => galleryMetadata(name), + assess: () => new Promise(() => {}), }, })) @@ -605,3 +606,26 @@ it('unstarring the open file under Starred steps on from its place', async () => await fireEvent.keyDown(window, { key: 'ArrowRight' }) expect(galleryMetadata).toHaveBeenLastCalledWith('b.png') }) + +it("shows the open file's level findings from its metadata", async () => { + galleryMetadata.mockResolvedValue({ + metadata: {}, + job: null, + inputs: [], + role: null, + findings: [ + { + rule: 'near_silent', + severity: 'warn', + at: null, + value: -62, + threshold: -50, + says: 'near-silent for a track meant to be heard', + }, + ], + }) + await renderGallery() + await openFile('a.png') + const region = await screen.findByRole('region', { name: 'Findings' }) + await waitFor(() => expect(region.textContent).toContain('near-silent')) +}) diff --git a/ui/src/lib/types.ts b/ui/src/lib/types.ts index 5a3b87132..cc91d72c2 100644 --- a/ui/src/lib/types.ts +++ b/ui/src/lib/types.ts @@ -63,6 +63,9 @@ export type GalleryFile = Schemas['GalleryFile'] export type GalleryList = Schemas['GalleryList'] export type GalleryMetadata = Schemas['GalleryMetadata'] export type GalleryInput = Schemas['GalleryInput'] +// One finding, as GET /api/gallery/{name}/metadata (`findings`) and +// /assess send it (dw/assessment_rules.py `finding()`) +export type LevelFinding = Schemas['LevelFinding'] /** A file's role in its run, as the server states it. */ export type OutputRole = NonNullable export type OutputDeleted = Schemas['OutputDeleted'] @@ -165,3 +168,19 @@ export interface StoredPrompt { /** An asset a nearer library hides: same shape as `AssetFile` except there * is no `url` - that URL would serve the shadowing file, not this one - and * `shadowed_by` names the origin that won. */ + +/** GET /api/gallery/{name}/assess, the default (no `probe`) answer + * (dw/server/assess.py). The route has no response model, so this is a + * local narrowing; a later `response_model` replaces it. `at` is seconds + * into the file, or null for a whole-file finding. */ +export interface AssessReply { + name: string + source: 'output' | 'asset' + kind: string | null + shots_source?: string + findings: Array + rules_applied: string[] + rules_skipped?: Array<{ probe: string; [key: string]: unknown }> + /** Each probe the file cannot feed, with why: {probe: reason} */ + not_applicable: Record +} From 1e9796a97d725a2f5f6028a8b21c584390c9fef6 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 08:18:46 -0600 Subject: [PATCH 262/412] docs(proposals): #1441 - close out H3 hybrid ref probe Design record for the fl2va/ref2va hybrid probe (stage #1463): built locally from cached weights, misses the SFace floor (0.788 vs 0.855); quality verdict left to Don. todo.md gains the shipped entry. Co-Authored-By: Claude Opus 5.5 --- .../complete/h3-hybrid-ref-probe-complete.md | 124 ++++++++++++++++++ docs/proposals/todo.md | 9 ++ 2 files changed, 133 insertions(+) create mode 100644 docs/proposals/complete/h3-hybrid-ref-probe-complete.md diff --git a/docs/proposals/complete/h3-hybrid-ref-probe-complete.md b/docs/proposals/complete/h3-hybrid-ref-probe-complete.md new file mode 100644 index 000000000..696e4e71a --- /dev/null +++ b/docs/proposals/complete/h3-hybrid-ref-probe-complete.md @@ -0,0 +1,124 @@ +# MiniMax-H3 fl2va/ref2va hybrid transformer probe (#1441) + +Written by model `claude-opus-5-5` via provider `anthropic` (close-out session, +2026-11-19). Don filed the idea on 2026-11-18 from +Adudeguyman/ComfyUI-Fantastic-MiniMaxH3-PromptBuilder's `REFMODS.md`, which +recommends `smhfacct/Minimax-H3-fl2va-ref2va-hybrid-models` over MiniMax's +ref2va weights. The claim was reference conditioning at fl2va quality. Plan v1 +is the plan comment on #1441. Don approved it at its defaults on 2026-11-18, +and it was built as one stage, #1463. The plan comment still holds the full Hub +sweep (provenance, licence, format). This file records what was measured and +what stayed cut. + +## Verdict: build smaller, a bench probe only + +- **The Hub files were not pulled.** There are four ComfyUI single-file int8 + merges, 21 GB each, built from unnamed "pruned int8-convrot" bases. diffusers' + `from_single_file` converter for `MiniMaxH3Transformer3DModel` refuses a + pruned checkpoint and has no int8 dequant, so loading them would have needed + a converter that dw would own. +- **The recipe is a tensor graft, so we built it ourselves** from the two bf16 + transformers lem already caches (`MiniMaxAI/MiniMax-H3` `transformer` and + `transformer_ref`). Without quantization noise, this tests the claim more + cleanly than the int8 files would. +- **The issue's main prize doesn't follow from a checkpoint.** References in a + guide chain are refused because a `references` step runs diffusers' Ref2VA + block graph, which has no anchor or chain steps. The fl2va turbo LoRA on a + reference shot is refused by partition name, not by weights. Neither is + unlocked by a hybrid in `transformer_ref`. +- **"MiniMax admitted faults"** is unsourced. The model card's "known + training-quality issue" has no link. + +## Plan history + +- **v1 (approved 2026-11-18).** + - Q1 [spend]: run stage A, b20-49 only, with the scratch deleted after the + record. + - Q2 [taste]: SFace sets the floor (within 0.02 of stock), and Don's look + decides quality. + - Q3 [trust]: no Hub download. + - Condition from the ruling: keep the `df` stop check on lem's model disk. + +## What was built + +### Stage A (#1463): graft b20-49 locally, bench one reference shot (bench only) + +Merges on `develop`: 6fcd3d17 (`feat/1441-A-h3-hybrid`, 03bce6a4 + 3d7c42ae), +then record-only follow-ups 8e0bf7a3 and c3d3365c (36e2f0a0). + +- **`bench/h3_hybrid_graft.py`:** reads both parents' shards per tensor, + lazily, asserts identical names and shapes, takes ref2va's `adaln_proj` for + the chosen blocks and fl2va everywhere else, and writes ref2va's + `config.json`. It prints a JSON tensor report. +- **`tests/test_bench_h3_hybrid_graft.py`:** covers block-range selection, + whole-number block matching, ref-only tensors being taken, fl-only and shape + mismatches being refused, and a two-shard safetensors round trip. +- **`bench/workflows/probe-1441-hybrid-ref.json`** and + **`probe-1441-stock-ref.json`:** the two arms differ only in + `load_components.pretrained_model_name_or_path.transformer_ref`. The server + can't reach `bench/` by path, so both arms were submitted inline. +- **`bench/records/h3-hybrid.md`:** method, disk, tensor report, jobs, wall + times, SFace, and a verdict line left blank for Don. + +### What was measured + +- **Parents.** The two parents' 638 tensor names and shapes are identical. The + card's claim holds: 60 tensors (`transformer_blocks.{20..49}.adaln_proj.linear. + {weight,bias}`) came from ref2va, and there are no ref-only tensors. The two + parents' `config.json` files are byte-identical. +- **Size.** Each parent and the graft are 66.3 GB in bf16. The plan's estimate + of ~40 GB was low. +- **Renders** (workspace `bench`, seed 1441, `cast/estela.jpg`, 124 frames at + 960x544, 9 steps, ref2va 8-step turbo, `{int4}`): + +| Arm | Job | Wall | Load | SFace median / min | +|---|---|---|---|---| +| stock ref2va | `7cd603a1922f` | 247.0 s | 5.3 s (cached) | 0.855 / 0.759 | +| hybrid b20-49 | `d5a6c03f9ee3` | 308.6 s | 48.8 s (uncached quantize) | 0.788 / 0.561 | + + The scoring jobs were `d7589d81e015` (stock) and `3a77473b74fa` (hybrid), + using `analyze_face_drift` with `samples_per_shot` 16. The tester's + independent re-score reproduced the hybrid's figures exactly. +- **Result.** The hybrid misses the SFace floor by 0.067, against 0.02 + allowed. b25-49 was not run: the plan ran it only if b20-49 showed a quality + gain, and that call is Don's. The record's verdict line is still blank for + him. +- **Unchanged.** An FL2V LoRA on the hybrid step is still refused by the same + rule as on stock. No catalog entry was added, `reference-to-video`'s defaults + are unchanged, and nothing was downloaded. The scratch graft was deleted. + +### Bounces + +Stage A was bounced three times before it verified on the fourth pass, all on +the record and not the code: +1. M-F445: the record wasn't quoted (disk, tensor report). +2. M-F444 and M-F445: the scoring settings and wall times weren't quoted. +3. M-F445: the `df` reading came after the graft. The plan's first step had + been missed. The graft was re-run with the `df` taken first, at 11:51 UTC + (scratch disk 671.8 GB free, model disk 137.6 GB free, against a bar of + 132.6 GB). A `torch.equal` check showed the rerun was tensor-identical to + the rendered graft, so the render was not repeated. + +Two engine bugs surfaced during verify and were fixed as their own issues: +- #1488: a local component path still listed its repo in + `plan.downloads_required`. +- #1489: a second LoRA with no `weight_name` slipped past the partition rule. + +Stage cost isn't recorded, because the stage comments don't name `usage:` +figures. + +## Cut, and what brings each back + +- **Hub download (smhfacct int8 files).** Comes back only if a local graft wins + and Don wants an int8 variant. A converter would then get its own plan. +- **Other block ranges (b25-49, b30-49).** Comes back if Don's look at the two + renders sees a quality gain. The rebuild is `--first 25` on the graft script, + about a minute. +- **Catalog entry or template.** Comes back if a hybrid holds the SFace floor + and wins Don's look. It would be a `workflows/models/` config of + `templates/minimax/reference-to-video` with the per-component override. +- **The fl2va turbo LoRA on a hybrid.** Comes back on the same win, as a + checkpoint-aware LoRA partition filed as its own feature. +- **References in a guide chain.** Comes back as its own feature, a new + dw-owned block sequence. The weights don't unlock it. Related: #980 + (FastH3 Omni, parked). diff --git a/docs/proposals/todo.md b/docs/proposals/todo.md index 834399ad2..c8a83a6cf 100644 --- a/docs/proposals/todo.md +++ b/docs/proposals/todo.md @@ -37,6 +37,15 @@ remaining deferred fix is recorded in ## Shipped since the ranking +- **H3 fl2va/ref2va hybrid probe** (#1441, stage #1463), closed 2026-11-19 + as a bench record. The smhfacct-style graft (fl2va weights, ref2va's + `adaln_proj` for blocks 20-49) was built locally from lem's cached + transformers, with no Hub download. Rendered against stock ref2va at seed + 1441, it misses the SFace floor: median 0.788 vs 0.855, a gap of 0.067 + with 0.02 allowed. The quality verdict is Don's look. The catalog entry, + the turbo LoRA on a hybrid, references in a guide chain and the Hub + files were cut, each with a trigger: + `complete/h3-hybrid-ref-probe-complete.md`. - **H3 stochastic sampling probe** (#1438, stage #1459), closed 2026-11-19 as a bench record, no gain. `MiniMaxH3Scheduler(stochastic_sampling=True)` (EasyFix's every-step re-noise) renders clean H3 turbo video, but its From b2d80f08bae2538474e00141d3c9f792051e3f2a Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 08:23:16 -0600 Subject: [PATCH 263/412] feat(ui): #1479 - curated cost states its basis and measured-at settings Card tooltip and run page print the listing's cost_basis in words and the card's preset-applied cost_drivers. docs/SERVER.md documents the card's cost_drivers map and the run-page line. Co-Authored-By: Claude Opus 5.5 --- docs/SERVER.md | 13 +++++- ui/src/lib/cost.test.ts | 62 ++++++++++++++++++++++++++ ui/src/lib/cost.ts | 54 ++++++++++++++++++++++ ui/src/lib/pages/WorkflowPage.svelte | 46 ++++++++++++++++--- ui/src/lib/pages/WorkflowPage.test.ts | 44 ++++++++++++++++++ ui/src/lib/pages/WorkflowsPage.svelte | 20 ++++----- ui/src/lib/pages/WorkflowsPage.test.ts | 34 ++++++++++++++ 7 files changed, 255 insertions(+), 18 deletions(-) create mode 100644 ui/src/lib/cost.test.ts create mode 100644 ui/src/lib/cost.ts diff --git a/docs/SERVER.md b/docs/SERVER.md index e6cfbce84..18c467a93 100644 --- a/docs/SERVER.md +++ b/docs/SERVER.md @@ -147,6 +147,13 @@ icon, a finish-alert toggle, the theme toggle, and links to these docs and chosen bundle's values as placeholders - only the selector is sent, so the server applies the bundle itself; in the editor the selector stays a text field with that line and its bundle names), the raw JSON on request, **Edit**, **Duplicate**, **Run** and delete. + Under the title, the card's curated figure says whose it is and the + settings it holds for - "a maintainer's figure: ~3 min · 22 GB VRAM, + measured on RTX 4090 at num_frames=121" (the card's `cost_drivers`, a list + as its entry count, an object as `{…}`, `null` as `unset`) - then this + server's observed time; a workflow with no `cost` shows no curated line. + The catalog card's tooltip carries the same "a maintainer's figure, + measured on … at …" line. The page checks a run as you edit: on load and 600 ms after the last change it posts `POST /api/validate?sizes=false` by name with exactly the arguments Run would send (blank fields dropped), and once more with sizes @@ -728,7 +735,11 @@ The editor's forms come from these; they are just as usable from scripts: the maintainer-measured `{device, name, vram_gb, minutes}` runs, or `null` when nobody has measured it - a list-driven workflow's `cost` entry may also carry a measured `per_entry` (`{variable, minutes, entries}`), the - cost of one entry of the list it was measured against. The response's + cost of one entry of the list it was measured against. A card's + `cost_drivers` is a map from each driver the workflow declares to its + default with any preset bundle applied - the settings the curated `cost` + was measured at, which for a preset template can differ from the raw + definition's `variables` (`GET /api/workflows/{name}`). The response's `cost_basis` says what that is - `curated`: figures a maintainer measured once and wrote into the workflow, never derived from this server's own job history, so `null` means nobody wrote one down rather than "this box has diff --git a/ui/src/lib/cost.test.ts b/ui/src/lib/cost.test.ts new file mode 100644 index 000000000..699d9921d --- /dev/null +++ b/ui/src/lib/cost.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'vitest' +import { costBasisWords, costMeasuredAt, costMeasuredOn } from './cost' + +describe('costMeasuredAt', () => { + it('prints a scalar as itself, in map order', () => { + expect(costMeasuredAt({ steps: 30, width: 1024, fast: true })).toBe( + 'steps=30, width=1024, fast=true', + ) + expect(costMeasuredAt({ weights_dtype: 'bf16' })).toBe('weights_dtype=bf16') + }) + + it('prints a list as its entry count', () => { + expect(costMeasuredAt({ shots: ['a', 'b', 'c'] })).toBe('shots=3 entries') + expect(costMeasuredAt({ shots: [] })).toBe('shots=0 entries') + }) + + it('prints null as unset', () => { + expect(costMeasuredAt({ image: null })).toBe('image=unset') + }) + + it('prints an object as {…}', () => { + expect(costMeasuredAt({ cache: { kind: 'fbc' } })).toBe('cache={…}') + }) + + it('cuts a value over 40 characters', () => { + const long = 'x'.repeat(41) + expect(costMeasuredAt({ p: long })).toBe(`p=${'x'.repeat(40)}…`) + expect(costMeasuredAt({ p: 'y'.repeat(40) })).toBe(`p=${'y'.repeat(40)}`) + }) + + it('is empty for an empty or missing map', () => { + expect(costMeasuredAt({})).toBe('') + expect(costMeasuredAt(undefined)).toBe('') + expect(costMeasuredAt(null)).toBe('') + }) +}) + +describe('costBasisWords', () => { + it("says curated as a maintainer's figure", () => { + expect(costBasisWords('curated')).toBe("a maintainer's figure") + }) + it('prints a basis it does not know raw', () => { + expect(costBasisWords('measured-in-ci')).toBe('measured-in-ci') + }) +}) + +describe('costMeasuredOn', () => { + const cost = [{ device: 'cuda', name: 'RTX 4090', vram_gb: 22, minutes: 3 }] + it('names the first entry and its settings', () => { + expect(costMeasuredOn(cost, { steps: 30 })).toBe( + 'measured on RTX 4090 at steps=30', + ) + }) + it('drops the at clause without drivers and falls back to the device', () => { + expect( + costMeasuredOn([{ device: 'mps', vram_gb: 1, minutes: 1 }], {}), + ).toBe('measured on mps') + }) + it('is empty with no cost', () => { + expect(costMeasuredOn(null, { steps: 30 })).toBe('') + }) +}) diff --git a/ui/src/lib/cost.ts b/ui/src/lib/cost.ts new file mode 100644 index 000000000..23cd2aa0f --- /dev/null +++ b/ui/src/lib/cost.ts @@ -0,0 +1,54 @@ +/** The curated cost figure said for a person: who made it and the settings + * it was measured at. Both read served fields and print them - the card's + * `cost_drivers` map (each driver's preset-applied default, from + * dw/server/catalog.py) and the listing's `cost_basis`. Nothing here knows + * which driver moves the figure: that is dw/cost_scaling.py's, and the + * per-run answer is validate's plan (docs/ARCHITECTURE.md, the UI row). */ +import { formatMinutes } from './format' +import type { WorkflowCost } from './types' + +const MAX_VALUE = 40 + +function driverValue(value: unknown): string { + if (value === null || value === undefined) return 'unset' + if (Array.isArray(value)) return `${value.length} entries` + if (typeof value === 'object') return '{…}' + const text = String(value) + return text.length > MAX_VALUE ? `${text.slice(0, MAX_VALUE)}…` : text +} + +/** `cost_drivers` as "name=value, …" in the map's order; '' for none. */ +export function costMeasuredAt( + drivers: Record | null | undefined, +): string { + if (!drivers) return '' + return Object.entries(drivers) + .map(([name, value]) => `${name}=${driverValue(value)}`) + .join(', ') +} + +/** `cost_basis` in words; a basis this UI does not know prints raw. */ +export function costBasisWords(basis: string | null | undefined): string { + if (basis === 'curated') return "a maintainer's figure" + return basis ?? '' +} + +/** "~3 min · 22 GB VRAM" for one measured entry. */ +export function costFigure(measured: WorkflowCost): string { + return `${formatMinutes(measured.minutes)} · ${Number( + measured.vram_gb.toFixed(1), + )} GB VRAM` +} + +/** "measured on [ at ]" for the first measured entry, or + * '' when the card has no cost. */ +export function costMeasuredOn( + cost: WorkflowCost[] | null | undefined, + drivers: Record | null | undefined, +): string { + const measured = cost?.[0] + if (!measured) return '' + const where = measured.name ?? measured.device + const at = costMeasuredAt(drivers) + return at ? `measured on ${where} at ${at}` : `measured on ${where}` +} diff --git a/ui/src/lib/pages/WorkflowPage.svelte b/ui/src/lib/pages/WorkflowPage.svelte index e6e4ce958..db526c378 100644 --- a/ui/src/lib/pages/WorkflowPage.svelte +++ b/ui/src/lib/pages/WorkflowPage.svelte @@ -16,6 +16,7 @@ import { loadPromptLibrary } from '../promptlib.svelte' import { notify } from '../toast' import { observedText, observedTitle } from '../observed' + import { costBasisWords, costFigure, costMeasuredOn } from '../cost' import { confirmDialog } from '../confirm.svelte' import type { GalleryFile, @@ -50,6 +51,10 @@ let proofs = $state([]) /** This server's own measured run time for the workflow, if it has one. */ let observed = $state | null>(null) + /** The maintainer's figure for this workflow, from the same catalog card: + * "a maintainer's figure: ~3 min · 22 GB VRAM, measured on at + * steps=30". Null when the card has no cost - never "unknown cost". */ + let curated = $state(null) $effect(() => { overrides = {} @@ -66,13 +71,20 @@ }) .catch((e) => (error = e.message)) observed = null + curated = null const wanted = name api .listWorkflows() .then((r) => { if (wanted !== name) return - observed = - (r.details?.[name]?.observed as Record) ?? null + const card = r.details?.[name] + observed = (card?.observed as Record) ?? null + const measured = card?.cost?.[0] + if (measured) { + const basis = costBasisWords(r.cost_basis) + const figure = `${costFigure(measured)}, ${costMeasuredOn(card.cost, card.cost_drivers)}` + curated = basis ? `${basis}: ${figure}` : figure + } }) .catch(() => {}) }) @@ -305,11 +317,6 @@ > Duplicate - {#if observedText(observed)} - {observedText(observed)} - {/if}
+ +{#if curated || observedText(observed)} +
+ {#if curated} +

+ {curated} + · other values re-price it in the plan +

+ {/if} + {#if observedText(observed)} +

+ {observedText(observed)} +

+ {/if} +
+{/if} + {#if error}

{error}

{/if} {#if workflow} @@ -520,6 +546,12 @@ .json { margin-top: var(--space-3); } + .costs { + margin: 0 0 var(--space-3); + } + .costs p { + margin: var(--space-1) 0; + } .error { color: var(--bad); } diff --git a/ui/src/lib/pages/WorkflowPage.test.ts b/ui/src/lib/pages/WorkflowPage.test.ts index 7a97c677c..d487ce875 100644 --- a/ui/src/lib/pages/WorkflowPage.test.ts +++ b/ui/src/lib/pages/WorkflowPage.test.ts @@ -284,3 +284,47 @@ describe('WorkflowPage run check', () => { ) }) }) + +describe('WorkflowPage curated cost', () => { + const card = (cost: unknown, observed: unknown = null) => ({ + workflows: ['templates/text-to-image'], + cost_basis: 'curated', + details: { + 'templates/text-to-image': { + cost, + // the card's preset-applied value, not the definition's 1 + cost_drivers: { num_images_per_prompt: 4 }, + observed, + }, + }, + libraries: [], + shadowed: [], + }) + + it("shows the maintainer's figure and its settings above the observed text", async () => { + vi.mocked(api.listWorkflows).mockResolvedValueOnce( + card([{ device: 'mps', name: 'M4 Max', vram_gb: 6.5, minutes: 2 }], { + warm_minutes: 1.5, + warm_runs: 2, + runs: 2, + }) as never, + ) + await openPage() + const line = screen.getByLabelText('curated cost') + expect(line.textContent).toContain( + "a maintainer's figure: ~2 min · 6.5 GB VRAM, measured on M4 Max at num_images_per_prompt=4", + ) + expect(line.textContent).toContain('other values re-price it in the plan') + const seen = screen.getByText('~1.5 min here') + expect( + line.compareDocumentPosition(seen) & Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy() + }) + + it('prints no curated line for a null cost', async () => { + vi.mocked(api.listWorkflows).mockResolvedValueOnce(card(null) as never) + await openPage() + expect(screen.queryByLabelText('curated cost')).toBeNull() + expect(document.body.textContent).not.toContain("maintainer's figure") + }) +}) diff --git a/ui/src/lib/pages/WorkflowsPage.svelte b/ui/src/lib/pages/WorkflowsPage.svelte index 2f1dd055e..e919baf7e 100644 --- a/ui/src/lib/pages/WorkflowsPage.svelte +++ b/ui/src/lib/pages/WorkflowsPage.svelte @@ -6,7 +6,7 @@ import FolderGroups from '../FolderGroups.svelte' import { leafOf } from '../grouping' import HintBar from '../HintBar.svelte' - import { formatMinutes } from '../format' + import { costBasisWords, costFigure, costMeasuredOn } from '../cost' import { observedText, observedTitle } from '../observed' import { latestProofs } from '../proofs' import { sharedHref, wsHref } from '../routes' @@ -27,6 +27,8 @@ let workflows = $state([]) let details = $state>({}) let workflowDir = $state('') + /** What the listing says a card's `cost` is - "curated" today. */ + let costBasis = $state('') let filter = $state('') let shape = $state('') let traits = $state([]) @@ -46,6 +48,7 @@ .then((result) => { workflows = result.workflows details = result.details ?? {} + costBasis = result.cost_basis workflowDir = writableRoot(result.libraries) loaded = true }) @@ -136,10 +139,7 @@ * has room for the numbers, not for the hardware they came from. */ const formatCost = (cost?: WorkflowCost[] | null) => { const measured = cost?.[0] - if (!measured) return '' - return `${formatMinutes(measured.minutes)} · ${Number( - measured.vram_gb.toFixed(1), - )} GB VRAM` + return measured ? costFigure(measured) : '' } /** Everything the card does not have room to print, so hovering it still @@ -148,11 +148,11 @@ const lines = [name] if (detail?.description) lines.push(detail.description) if (detail?.traits?.length) lines.push(detail.traits.join(', ')) - if (detail?.cost?.[0]) { - const measured = detail.cost[0] - const where = measured.name ?? measured.device - lines.push(`measured on ${where}`) - } + // Who made the figure and the settings it holds for: the card's own + // preset-applied driver values, never the raw definition's defaults + const measuredOn = costMeasuredOn(detail?.cost, detail?.cost_drivers) + const basis = costBasisWords(costBasis) + if (measuredOn) lines.push(basis ? `${basis}, ${measuredOn}` : measuredOn) const seen = observedTitle(detail?.observed) if (seen) lines.push(seen) if (detail?.writable === false) diff --git a/ui/src/lib/pages/WorkflowsPage.test.ts b/ui/src/lib/pages/WorkflowsPage.test.ts index 8fd885720..0affcf268 100644 --- a/ui/src/lib/pages/WorkflowsPage.test.ts +++ b/ui/src/lib/pages/WorkflowsPage.test.ts @@ -17,6 +17,7 @@ type Detail = Record const listing = vi.hoisted(() => ({ workflows: [] as string[], details: {} as Record, + cost_basis: 'curated' as string, })) const listWorkflows = vi.hoisted(() => @@ -36,6 +37,7 @@ const listWorkflows = vi.hoisted(() => shadowed: [], workflows: listing.workflows, details: listing.details, + cost_basis: listing.cost_basis, }), 0, ), @@ -68,6 +70,7 @@ beforeEach(() => { location.hash = '#/ws/default/workflows' window.dispatchEvent(new HashChangeEvent('hashchange')) listing.workflows = ['templates/tti', 'templates/shot', 'models/flux-dev'] + listing.cost_basis = 'curated' listing.details = { 'templates/tti': { kinds: ['image'], @@ -88,6 +91,7 @@ beforeEach(() => { shape: 'shot', traits: ['has-audio', 'image-conditioned'], cost: [{ device: 'cuda', name: 'RTX 4090', vram_gb: 22, minutes: 3 }], + cost_drivers: { num_frames: 121, images: ['a.png', 'b.png'] }, }, 'models/flux-dev': { kinds: ['image'], @@ -158,6 +162,36 @@ it('shows the measured cost and omits it when nothing was measured', async () => expect(card('tti')?.textContent).not.toContain('min') }) +it("says whose figure the cost is and the card's settings it was measured at", async () => { + await renderPage('tti') + // The "at" values are the card's cost_drivers - preset-applied - in map + // order, a list as its entry count + expect(card('shot')!.getAttribute('title')).toContain( + "a maintainer's figure, measured on RTX 4090 at num_frames=121, images=2 entries", + ) + // No drivers: no "at" clause; the device names the card when it has no name + const flux = card('flux-dev')!.getAttribute('title')! + expect(flux).toContain("a maintainer's figure, measured on mps") + expect(flux).not.toContain(' at ') + // A null cost has no cost line at all + expect(card('tti')!.getAttribute('title')).not.toContain('measured on') + // and the caption is unchanged + expect(screen.getByText('~3 min · 22 GB VRAM')).toBeTruthy() +}) + +it('prints a basis it does not know and a hostile driver value literally', async () => { + listing.cost_basis = 'estimated' + listing.details['templates/shot'] = { + ...listing.details['templates/shot'], + cost_drivers: { prompt: '' }, + } + await renderPage('tti') + expect(card('shot')!.getAttribute('title')).toContain( + 'estimated, measured on RTX 4090 at prompt=', + ) + expect(document.querySelector('img[src="x"]')).toBeNull() +}) + it('keeps a fractional measurement rather than rounding it away', async () => { listing.workflows = ['templates/half'] listing.details = { From dedcc2c913d98207afd9aff4188897fc52cc8da5 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 08:27:17 -0600 Subject: [PATCH 264/412] docs(proposals): #1391 - close out H3 keystone attention probe Design record in docs/proposals/complete/h3-keystone-attention-complete.md, todo.md entry, and the WORKFLOW_GUIDE experimental line now states the block numbering was checked (#1394) and the bench gave no clear win. Co-Authored-By: Claude Opus 5.5 --- docs/WORKFLOW_GUIDE.md | 2 +- .../h3-keystone-attention-complete.md | 177 ++++++++++++++++++ docs/proposals/todo.md | 9 + 3 files changed, 187 insertions(+), 1 deletion(-) create mode 100644 docs/proposals/complete/h3-keystone-attention-complete.md diff --git a/docs/WORKFLOW_GUIDE.md b/docs/WORKFLOW_GUIDE.md index a28fc01d0..0382ea1b7 100644 --- a/docs/WORKFLOW_GUIDE.md +++ b/docs/WORKFLOW_GUIDE.md @@ -2019,7 +2019,7 @@ larger, not smaller; on `chain-video-continuity` it held the subject's pose and better but darkened the chain and raised saturation faster (`docs/proposals/complete/h3-turbo-lead-in-complete.md`). -**Experimental**, refused unless `DW_EXPERIMENTAL_REFINE_WINDOWS=1`: `experimental_keystone_attention: {"balance": 20, "blocks": "31-33,36-44,47"}`, an H3 `fl2va` call argument with `image` and `guides`, re-splits on the named blocks the attention each query pays to the keyframe rows (from `image`) against the guide rows (from `guides`), keeping their sum. A `balance` above 1 moves it toward the keyframe and 1 is no change; `blocks` are comma-separated whole numbers and inclusive `a-b` ranges, numbered 0..N-1 down diffusers' `transformer_blocks` (0-49 on H3), taking diffusers' numbering as ComfyUI's (an assumption, #1391 Q3). Refused with `experimental_tst`, sparse attention, a capstone or gated guide rows; CUDA needs cuDNN or native flash attention (`dw/pipeline_processors/h3_keystone_attention.py`). +**Experimental**, refused unless `DW_EXPERIMENTAL_REFINE_WINDOWS=1`: `experimental_keystone_attention: {"balance": 20, "blocks": "31-33,36-44,47"}`, an H3 `fl2va` call argument with `image` and `guides`, re-splits on the named blocks the attention each query pays to the keyframe rows (from `image`) against the guide rows (from `guides`), keeping their sum. A `balance` above 1 moves it toward the keyframe and 1 is no change; `blocks` are comma-separated whole numbers and inclusive `a-b` ranges, numbered 0..N-1 down diffusers' `transformer_blocks` (0-49 on H3), the same numbering as ComfyUI's (checked on lem with a brightened keystone, #1394). On the narrated bench chain it visibly changed the take but gave no clear win, so no template uses it (`docs/proposals/complete/h3-keystone-attention-complete.md`). Refused with `experimental_tst`, sparse attention, a capstone or gated guide rows; CUDA needs cuDNN or native flash attention (`dw/pipeline_processors/h3_keystone_attention.py`). #### Chaining with a guide: `continuity: "guide"` diff --git a/docs/proposals/complete/h3-keystone-attention-complete.md b/docs/proposals/complete/h3-keystone-attention-complete.md new file mode 100644 index 000000000..9d34e3d4f --- /dev/null +++ b/docs/proposals/complete/h3-keystone-attention-complete.md @@ -0,0 +1,177 @@ +# MiniMax-H3 keystone attention probe (#1391) + +Written by model `claude-opus-5-5` via provider `anthropic` (close-out session, +2026-11-19). Don filed the idea on 2026-11-16 from roycho87/geiru_context_suite +1.1.x's Keystone Attention (GPL-3.0, concepts only, no code read) and the notes +behind it, roycho87/NerdNotes tests 19 and 20 (CC BY-SA 4.0). Those credit the idea +to ckinpdx's Carry Attention (ComfyUI-MMH3Tools). On a chained H3 clip with a +keystone, the probe re-splits the slice of attention that the keystone keys and the +carried-guide keys share, moving it toward the keystone on the late blocks. Plan v4 +is the plan comment on #1391, and it still holds the full sweep and the math. This +file records what was built, what was measured, and what stayed cut. The bench +record is `bench/records/narrated.md`, in the two *Keystone attention* sections. + +## Verdict: build smaller, a one-call probe + +- **An H3 fl2va call argument, not a chain key.** `experimental_keystone_attention` + sits behind `DW_EXPERIMENTAL_REFINE_WINDOWS=1`. In that call, "keystone" means the + `image` keyframe rows and "carried" means the `guides` rows. +- **The bench chain was built by hand.** Every segment's `image` is segment 1's + frame 0, which is where `keystone_slot: first` puts it. +- **Cut:** the `keystone: segment_1` chain key, and the `latent`, `{frame}` and + `last` slots. +- **Our drift isn't theirs.** The no-keystone narrated control `aed61997052a` held + luma (-0.5) but rose in saturation (+8.8) and face sharpness (+105). So the open + question was whether re-splitting the attention touches face sharpness. + +## Plan history + +- **v1 (approved 2026-11-16, at defaults).** + - Q1 [scope]: a call argument, not a chain key. + - Q2 [spend]: a gated two-arm bench. + - Q3 [none]: diffusers' block indices are taken as ComfyUI's. + - Q4 [none]: refused alongside TST, sparse attention, a capstone or gated guide + rows. +- **v2 (decompose).** Folded in the rulings and Don's lem scheduling: queue behind + #1385 and #1382, one H3 job at a time. +- **Don's 2026-11-16 amendment (Q6, from roycho87's comment on #1391, + issuecomment-6922271175).** Stage B opens with a numbering check (a brightened + keystone) and a face-sharpness group sweep (a sharpened keystone). +- **v3 (stage B build, approval withdrawn).** `seam-restore-control.json` runs sparse + on every segment, and stage A refuses sparse. Q5 [loosen]: both arms run dense, + and `aed61997052a` becomes a reference column that differs in two things. +- **v4 (decompose).** Recorded Q5 at its default and folded in Q6, which v2 and v3 + had missed. +- **Rulings during stage B (2026-11-18 and 19), each recorded on #1394:** + - run on lem's current diffusers, `e84bda1c`, not the control's `43e30028`; + - step 1 only, then back to Don, after lem went down during a dense run; + - no step 2: run the gate on roycho87's blocks; + - after viewing: gate failed, stop. + +## What was built + +### Stage A (#1393): the re-split processor (server) + +Merges on `develop`: 8e5d7338 (b22d38e1, 218a2db1), 14b5a468 (378de5cf, the +architecture-review fix), and ef128323 (1c099e94, the M-F379 fix). + +- **`dw/pipeline_processors/h3_keystone_attention.py`.** It takes the argument + (`balance` 20 and `blocks` `31-33,36-44,47` by default; N is read off the block + list) and runs the validate-time refusals. +- **Row publication.** The guide layout step (`h3_guide_steps.py`) publishes the + keyframe and guide row counts. +- **Install and math.** It installs on a subset of blocks per call, and the re-split + is exact. One LSE-returning main pass is made, plus one pass over the keystone keys + only and one over the carried keys only. Then pK' = S·b·pK/(b·pK+pC), and + O' = O + ΔpK·O_K + ΔpC·O_C. +- **The LSE op order follows torch's SDPA priority,** so `balance: 1` reproduces the + run without the argument. +- **Tests.** Unit tests (`tests/test_h3_keystone_attention.py`) check it against a + dense softmax reference, and test the parser and each refusal. The spikes are gated + at validate time. +- **Docs.** The `docs/ARCHITECTURE.md` row "H3 experimental attention processors (TST, + keystone attention)", one experimental line in `docs/WORKFLOW_GUIDE.md`, and the + `docs/ATTRIBUTIONS.md` entries: NerdNotes tests 19-20, geiru's Keystone Attention, + and ckinpdx's Carry Attention. + +**Bounces (3):** +1. The architecture review bounced it: the new module had no map row. +2. The first verify couldn't run, because lem served without the flag. `.env` was + then set and the server restarted. That is not counted against the build. +3. The tester failed M-F379: `balance: 1` differed from no argument by a MAD of 2.17. + The cause was a bf16 kernel mismatch, not the math: the main pass tried cuDNN + first, while H3's own processor dispatches SDPA, which runs flash first on + torch 2.14. It was fixed by following torch's SDPA priority order. + +It verified on 2026-11-18 against develop @ 940c51d0. + +### Stage B (#1394): numbering check, then the early gate (bench only) + +Merge on `develop`: 3af05299 (ef169c02, f9eda0f1, ce786481, f502ab25). + +- **Bench files.** `bench/workflows/keystone-attention-control.json` and + `keystone-attention.json`, with their `*-early.json` gate cuts; the probes + `keystone-probe-seg01.json`, `keystone-probe.json` and `keystone-probe-noarg.json`; + the measure `bench/keystone_luma.py`; and the arm file + `bench/arms/keystone-attention.json`. +- **Tests.** `tests/test_bench_keystone_attention.py` checks that the control is + `seam-restore-control` with exactly two changes, that the arm is the control plus + the argument, and that each early job is cut after seg02. +- **Attributions.** A `docs/ATTRIBUTIONS.md` line credits roycho87's comment and + NerdNotes test 19 for the block-finding method. +- **No bounces.** The stage was re-planned once before it was built (v3). + +## What was measured + +All runs used diffusers `0.44.0.dev0` @ `e84bda1c`, workspace `bench`, dense +attention, one H3 job at a time. + +**Step 1, the numbering check: it matches.** Each run renders segment 2 alone, at +seed 2, with segment 1's 22-frame tail as the guide and `balance` 20. The figure is +the mean luma of the new frames. + +| Job | Keystone | `blocks` | vs normal | +|---|---|---|---| +| `53e01c397101` | normal | none | - | +| `4444aa27a7dc` | bright ×1.3 | none | +0.13% | +| `b686b8a0a40b` | bright | `0-29` | +0.57% | +| `ad1e332586f1` | bright | `30-39` | **+8.39%** | + +That is roycho87's shape (+4.4% / +4.1% / +13.8%), so diffusers' indices 0-49 are +ComfyUI's `diffusion_model.blocks[i]`, and Q3's assumption now holds as measured. +Our plain keystone carries much less on its own (+0.13% against his +4.4%). On this +chain, the 22-frame carried guide seems to outweigh the single keyframe row. + +**Step 2 (the sharpness sweep) did not run.** It was cut by Don's ruling. + +**Early gate (seg01-02):** control `2817a04202ae` on cuda:0, attention +`29923da18475` on cuda:1. The two arms differ only in the argument on seg02. + +| Measure | Control | Attention | +|---|---|---| +| seg02 face-sharpness rise (seam + in-segment) | -16.9 | -7.7 | +| seg02 face sharpness, first 1 s → last 1 s | 103.6 → 92.0 | 127.1 → 101.3 | +| seam-1 `jump_ratio` | 1.09 | 1.19 (1.09x) | +| SFace, seg02 last 1 s | .907 | .894 | + +- **It fails on its letter.** The attention arm's "rise" is higher than the control's, + and the gate asked for no worse. The seam passes. +- **Neither arm creeps sharper.** Both fall through seg02. The gate's direction came + from #1325 and can't tell "creeps sharper" apart from "keeps more of the keystone's + detail". +- **The op acts.** seg02 opens nearer the keystone's sharpness, and pose and framing + shift (PSNR 17.7 dB against the control). But the face crops show no clear texture + or identity win. +- **The LSE op costs about +5% per pass.** That is an estimate across two cards, + corrected by the identical seg01, because `run_workflow` has no device pin. +- **Dense runs about 2x sparse per pass on this chain,** not the +22-28% `speed.md` + recorded for short clips. seg01 took 71 s per pass against 34 s, and seg02 86-100 s + against 47 s. + +**Don's verdict (2026-11-19): gate failed, stop.** He watched both takes and saw no +clear win. + +Stage cost isn't recorded, because the stage comments don't name `usage:` figures. +lem time: about 0.4 h for segment 1, 2.2 h for step 1, and 1.9 h for the gate. + +## Cut, and what brings each back + +- **Step 2, the face-sharpness group sweep.** Comes back only if Don wants to go + after face sharpness through attention again. It would run narrow late groups, + about 2.5 h dense. +- **The full arms (6 segments).** Come back after a step 2 pick that wins on a gate. + At the dense per-pass figures above, both arms together are about 5-6 h. +- **The chain key (`keystone: segment_1` + attention) and the other slots.** Come back + only on a viewing win. `first` and `last` would be wired first, because their + keystone sits in the keyframe rows. +- **A sparse-aware re-split.** Any positive result would be dense-only, while the + shipped templates run sparse (Q5). That is a new stage, proposed only after a + positive result. +- **The moving-shot arm.** Comes back only if arm 1 helps. The keystone's pull-back + to segment 1's view is the risk there. + +## What stays + +`experimental_keystone_attention` stays experimental and behind the flag, with no +template or default change. It is the attention seam a revival starts from, and its +block numbering has now been checked on lem. diff --git a/docs/proposals/todo.md b/docs/proposals/todo.md index c8a83a6cf..17380e024 100644 --- a/docs/proposals/todo.md +++ b/docs/proposals/todo.md @@ -37,6 +37,15 @@ remaining deferred fix is recorded in ## Shipped since the ranking +- **H3 keystone attention probe** (#1391, stages #1393 and #1394), closed + 2026-11-19. `experimental_keystone_attention`, an fl2va call argument behind + `DW_EXPERIMENTAL_REFINE_WINDOWS`, re-splits the keystone/carried-guide + attention slice on chosen blocks. A brightened-keystone check showed that + diffusers' block numbering matches ComfyUI's. The early gate on the narrated + chain, which ran dense, failed on its letter. The op visibly acts, but Don + saw no clear win and stopped the bench. The sharpness sweep, the full arms, + the chain key, the sparse re-split and the moving-shot arm were cut, each + with a trigger: `complete/h3-keystone-attention-complete.md`. - **H3 fl2va/ref2va hybrid probe** (#1441, stage #1463), closed 2026-11-19 as a bench record. The smhfacct-style graft (fl2va weights, ref2va's `adaln_proj` for blocks 20-49) was built locally from lem's cached From 9c9ae57ca649a75d019cd8d7bc20e5256a34b94a Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 08:33:55 -0600 Subject: [PATCH 265/412] docs(proposals): #1442 - close out per-shot audio drift figures Co-Authored-By: Claude Opus 5.5 --- .../complete/shot-audio-drift-complete.md | 113 ++++++++++++++++++ docs/proposals/todo.md | 7 ++ 2 files changed, 120 insertions(+) create mode 100644 docs/proposals/complete/shot-audio-drift-complete.md diff --git a/docs/proposals/complete/shot-audio-drift-complete.md b/docs/proposals/complete/shot-audio-drift-complete.md new file mode 100644 index 000000000..1a2639509 --- /dev/null +++ b/docs/proposals/complete/shot-audio-drift-complete.md @@ -0,0 +1,113 @@ +# Per-shot audio drift figures (#1442) + +Written by model `claude-opus-5-5` via provider `anthropic` (close-out session, +2026-11-19). Don filed the idea on 2026-11-18 from Adudeguyman/ComfyUI-H3-Project-Suite +1.5.0 (GPL-3.0, concepts only, README and `docs/HOW_IT_WORKS.md` read at 015db2c, no +code). It had two parts. **A:** audio drift numbers per chain segment (the high end and +the hiss under quiet moments). **B:** clip 1's sound passed to every later clip as an +audio anchor. Plan v1 is the plan comment on #1442, and it still holds the full sweep. +This file records what was built, what was measured, and what stayed cut. + +## Verdict: build smaller, A only, report-only + +- Most of A had already shipped. `analyze_shots` already reported per-shot loudness, + peak, crest and the low/mid/high band levels (high is 4-20 kHz). +- What was missing was a per-shot high-band **share** and a measured **noise floor**. +- B was deferred. Only ref2va chains can carry an audio reference. `chained-segments` + (fl2va `guide`, H3-invented sound) is the template most likely to drift, and B can't + reach it. + +## Plan history + +- **v1 (approved 2026-11-18, batch lane, Q1-Q3 at defaults).** + - Q1 [none]: the field names `high_share` and `noise_floor_dbfs`. + - Q2 [none]: the floor is the 10th percentile of 50 ms RMS windows, `null` under + 0.5 s. + - Q3 [none]: B stays deferred under its trigger. The close-out files B as a new + `idea` if stage 1's record meets the trigger, and records "no defect found" if it + doesn't. + +## What was built + +### Stage 1 (#1464): `high_share` and `noise_floor_dbfs` per shot (server) + +Merges on `develop`: 0e540407 (5e48bf8d) and a8b8f6af (ddf562b4, the +architecture-review fix). + +- **`high_share`** (`dw/tasks/assess.py`, `shots_answer`). The high band's share of + the shot's own `spectral_balance`, via `_shares_from_bands`, which is factored out of + `_band_shares`, so the seam probe's `spectral_shift` is unchanged. It is rounded to + 4 places, and `null` where the balance is `null`. +- **`noise_floor_dbfs`** (`_noise_floor`). The nearest-rank 10th percentile of the + shot's 50 ms window levels. + - `null` under 10 windows (0.5 s), or when the percentile lands on a digitally + silent window. Never NaN. + - Capped at the shot's `rms_dbfs`. This was a deviation: on a steady level, rounding + could otherwise put the floor about 0.01 dB above it. +- **One window helper**, `_window_levels`, shared by `_dead_air` and `_noise_floor`. + `_dead_air` answers are pinned unchanged. +- **Tests:** `TestHighShare`, `TestNoiseFloor`, `TestDeadAirSharesTheWindows` and the + steady-tone cap test in `tests/test_assess.py`. +- **Docs:** + - Two rows in the `analyze_shots` table, `docs/TASKS.md`, with the caveat that in + dense dialogue the floor may follow speech tails. + - The "rising together" sentence went in + `plugins/dw/skills/minimax-h3/references/chains.md` (*Drift*), not `SKILL.md`. + That was a deviation: `SKILL.md` was at its 12288-byte cap. +- **Unchanged:** no rule, probe, finding code, MCP parameter, REST route or syntax. + +**Bounces (1):** the architecture review bounced the first hand-off because +`dw/tasks/assess.py` had grown past the module-size ceiling (1,200 lines). The fix +moved code out (`dw/dsp.py`, `dw/tasks/image_ops.py`) and brought it to 1,091 lines. +The tester then passed C-F1002 to C-F1010 on the first verify, against develop @ +2ce2776c. + +Stage cost isn't recorded, because the stage comments don't name `usage:` figures. It +used no GPU time beyond the verify's `assess_output` calls. + +## What was measured + +The bench S3 dialogue chain (`bench` `s3-dialogue-walk/20261107-204402-f54d3126`: 6 +segments of generated dialogue on a guide chain). Shots come from the run manifest. Two +calls gave identical values. + +| Segment | Frames | rms_dbfs | high_share | noise_floor_dbfs | +|---|---|---|---|---| +| 1 | 0–124 | -26.59 | 0.0289 | -69.58 | +| 2 | 124–226 | -17.62 | 0.0539 | -78.67 | +| 3 | 226–328 | -12.59 | 0.0440 | -61.16 | +| 4 | 328–430 | -11.19 | 0.0633 | -22.87 | +| 5 | 430–532 | -14.79 | 0.0481 | -51.10 | +| 6 | 532–634 | -15.35 | 0.0910 | -59.20 | + +- `high_share` roughly triples from segment 1 to 6, but not monotonically. +- The floor doesn't rise with it. The exception is segment 4, which is dense and + continuous, so its floor sits only 11.7 dB under its level. +- Under the skill's rule (both figures rising together), **this chain doesn't show the + dulling-voice signature: no defect found.** +- **Not taken:** the S1 table and the rerun gap (a second run of the same scene). The + verify's acceptance named only S3. The trigger fails on S3 even before a rerun gap, + so neither was needed for the decision. +- The trend is seeded as `regression-perf/C-F1010.jsonl` on the harness repo. + +## Cut, and what brings each back + +- **Idea B, the audio anchor.** It isn't filed, because its trigger wasn't met (Q3's + default). + - It comes back only if, on a generated-voice chain, `high_share` and + `noise_floor_dbfs` rise together across segments by more than they move between + two runs of the same seed. + - It would then be its own `idea`, and it must say how it reaches fl2va guide + chains, or accept ref2va-only. + - It would need new `chain` syntax, so removing it later would be breaking. +- **A drift rule or finding.** Comes back once two or more generated-voice chains show + a trend past the rerun gap. +- **A spectral centroid ("brightness") field.** Comes back if `high_share` reads flat + while a listener hears dulling. +- **A bench driver measure and its `bench/README.md` row.** Left out to keep stage 1 + one session. It comes back with a bench that tracks audio drift. + +## What stays + +The two per-shot fields on `analyze_shots`, report-only. They are cheap to remove if +nothing comes to read them. diff --git a/docs/proposals/todo.md b/docs/proposals/todo.md index 17380e024..019c6cfbb 100644 --- a/docs/proposals/todo.md +++ b/docs/proposals/todo.md @@ -37,6 +37,13 @@ remaining deferred fix is recorded in ## Shipped since the ranking +- **Per-shot audio drift figures** (#1442, stage #1464), closed 2026-11-19. + `analyze_shots` gains report-only `high_share` (energy above 4 kHz) and + `noise_floor_dbfs` (10th percentile of 50 ms windows) per shot. On the bench + S3 dialogue chain `high_share` rose unevenly and the floor didn't follow, + so no dulling-voice defect was found. The audio anchor (idea B), a drift + rule, a centroid field and a bench measure were cut, each with a trigger: + `complete/shot-audio-drift-complete.md`. - **H3 keystone attention probe** (#1391, stages #1393 and #1394), closed 2026-11-19. `experimental_keystone_attention`, an fl2va call argument behind `DW_EXPERIMENTAL_REFINE_WINDOWS`, re-splits the keystone/carried-guide From d75d8cb0d3b622ff0aa0cdaee158d5911fd7599f Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 08:40:28 -0600 Subject: [PATCH 266/412] feat(ui): #1478 - event log on the job page A collapsed Event log section on every job page, read from GET /api/jobs/{id}/event-log only when opened: pages of 500 following truncated, capped at 5,000; the server's note above the rows, 404 as 'no event log for this job', a client-side kind filter, and Refresh from last_seq while the job is live. Its rows are its own; the page's events, flow view and chips still read the live stream alone. Co-Authored-By: Claude Opus 5.5 --- docs/SERVER.md | 14 ++ tests/test_ui_twins.py | 3 + ui/e2e/job-event-log.spec.ts | 123 +++++++++++++++++ ui/src/lib/api.test.ts | 29 ++++ ui/src/lib/api.ts | 21 +++ ui/src/lib/job/EventLog.svelte | 223 +++++++++++++++++++++++++++++++ ui/src/lib/job/eventLog.test.ts | 103 ++++++++++++++ ui/src/lib/job/eventLog.ts | 67 ++++++++++ ui/src/lib/pages/JobPage.svelte | 3 + ui/src/lib/pages/JobPage.test.ts | 146 +++++++++++++++++++- ui/src/lib/types.ts | 13 ++ 11 files changed, 744 insertions(+), 1 deletion(-) create mode 100644 ui/e2e/job-event-log.spec.ts create mode 100644 ui/src/lib/job/EventLog.svelte create mode 100644 ui/src/lib/job/eventLog.test.ts create mode 100644 ui/src/lib/job/eventLog.ts diff --git a/docs/SERVER.md b/docs/SERVER.md index 18c467a93..af95233f1 100644 --- a/docs/SERVER.md +++ b/docs/SERVER.md @@ -226,6 +226,20 @@ icon, a finish-alert toggle, the theme toggle, and links to these docs and among the results is drawn as a timeline strip (clips sized by duration, gaps hatched, a copy button for each clip's `output:` reference). + Every job page, live or from history, ends with an **Event log** section, + collapsed until clicked; nothing is fetched before then. Opening it reads + `GET /api/jobs/{id}/event-log` in pages of 500, following `truncated`, and + stops at 5,000 events ("showing the first 5,000; more on the server"). Each + row is the event's seq, its time since the job started, its kind (a + warning's own `kind` beside it, e.g. `warning · phase_stall`), and its + message or the rest of its payload as compact JSON; a **kind** select filters + the rows to one kind. The route's `note` - what a finished job's history + dropped, or that it kept no log - shows above the rows, and an unknown or + pruned job says "no event log for this job". While the job is live a + **Refresh** button fetches the events after the last one shown. The section + keeps its own rows: the Progress list, the flow view and its chips still + read the live stream alone (`ui/src/lib/job/EventLog.svelte`). + ![A finished job: a warning about a level jump at a cut, then the workflow as a data-flow graph from the edit and soundtrack through mixing and normalizing to the film](img/ui-job.png) - **Gallery** - everything in the workspace's output directory diff --git a/tests/test_ui_twins.py b/tests/test_ui_twins.py index e93f10af3..dc9d7c2fd 100644 --- a/tests/test_ui_twins.py +++ b/tests/test_ui_twins.py @@ -259,6 +259,9 @@ def test_the_ui_offload_modes_are_the_schemas(): # would filter (`probes`), so it has no response_model; the UI's narrowed # `AssessReply` in ui/src/lib/types.ts names this route (#1452 plan, Q1) "/api/gallery/{}/assess", + # The event-log route has no response_model either; the UI's narrowed + # `EventLogReply` in ui/src/lib/types.ts names it (#1452 plan, stage B) + "/api/jobs/{}/event-log", } # The raw workflow/prompt GETs serve the file verbatim; their PUT and DELETE # on the same path are in the contract diff --git a/ui/e2e/job-event-log.spec.ts b/ui/e2e/job-event-log.spec.ts new file mode 100644 index 000000000..c1cce17db --- /dev/null +++ b/ui/e2e/job-event-log.spec.ts @@ -0,0 +1,123 @@ +import { expect, test, type Page } from '@playwright/test' + +// The job page's Event log (#1478), on a mocked finished job whose history +// kept only the tail of its log: the section opens on a click, reads the +// event-log route once, and shows the server's note above the rows. +// Screenshots of the section in both themes land in this spec's +// test-results folder. + +const ID = 'j-eventlog' +const NOTE = + 'Only the last 200 events of this job were retained; everything before seq 37 was dropped when the job was recorded.' + +const job = { + id: ID, + status: 'succeeded', + workflow: 'text-to-image', + workflow_name: 'text-to-image', + workspace: 'default', + arguments: {}, + acknowledged: 'none', + acknowledged_cost: null, + created_at: 1_700_000_000, + started_at: 1_700_000_001, + finished_at: 1_700_000_042, + error: null, + traceback: null, + warnings: [], + event_count: 4, + manifest: [], + run_dir: null, + run_id: null, + run_version: null, + historical: true, +} + +const events = [ + { seq: 37, event: 'step_start', at: 1.2, step: 'generate' }, + { + seq: 38, + event: 'log', + at: 3.4, + message: 'loading pipeline StableDiffusionPipeline', + }, + { + seq: 39, + event: 'warning', + kind: 'phase_stall', + at: 30.1, + message: 'no progress for 20s in denoise', + }, + { seq: 40, event: 'step_end', at: 40.9, step: 'generate', files: [] }, +] + +async function mockJob(page: Page) { + const logCalls: string[] = [] + await page.route( + (url) => url.pathname === `/api/jobs/${ID}`, + (route) => route.fulfill({ json: job }), + ) + await page.route( + (url) => url.pathname === `/api/jobs/${ID}/workflow`, + (route) => + route.fulfill({ + json: { + id: ID, + definition: { id: 'text-to-image', steps: [] }, + realized: true, + seed_variable: null, + }, + }), + ) + await page.route( + (url) => url.pathname === `/api/jobs/${ID}/event-log`, + (route) => { + logCalls.push(new URL(route.request().url()).search) + return route.fulfill({ + json: { + id: ID, + status: 'succeeded', + events, + last_seq: 40, + truncated: false, + note: NOTE, + }, + }) + }, + ) + return logCalls +} + +for (const theme of ['light', 'dark'] as const) { + test(`event log on a finished job with a trimmed log (${theme})`, async ({ + page, + }, testInfo) => { + await page.emulateMedia({ colorScheme: theme }) + const logCalls = await mockJob(page) + await page.goto(`/#/ws/default/jobs/${ID}`) + + const section = page.getByRole('region', { name: 'Event log' }) + const toggle = section.getByRole('button', { name: /Event log/ }) + await expect(toggle).toHaveAttribute('aria-expanded', 'false') + // Collapsed, it has asked for nothing + expect(logCalls).toEqual([]) + + await toggle.click() + await expect(section.locator('tbody tr')).toHaveCount(4) + await expect(section).toContainText('everything before seq 37 was dropped') + await expect(section.locator('tbody tr').nth(2)).toContainText( + 'warning · phase_stall', + ) + // A finished job's log does not grow + await expect(section.getByRole('button', { name: 'Refresh' })).toHaveCount( + 0, + ) + expect(logCalls.length).toBe(1) + expect(logCalls[0]).toContain('after=-1') + expect(logCalls[0]).toContain('limit=500') + + await section.screenshot({ + path: testInfo.outputPath(`job-event-log-${theme}.png`), + }) + }) +} diff --git a/ui/src/lib/api.test.ts b/ui/src/lib/api.test.ts index 0d7f1c897..5bd722218 100644 --- a/ui/src/lib/api.test.ts +++ b/ui/src/lib/api.test.ts @@ -145,6 +145,35 @@ describe('name encoding', () => { }) }) +describe('job event log', () => { + it('sends after, limit and each kind as a repeated parameter', async () => { + const calls = stubFetch({ ok: true, body: { events: [] } }) + await api.eventLog('j1', { + after: 41, + limit: 500, + kinds: ['log', 'warning'], + }) + expect(calls[0][0]).toBe( + '/api/jobs/j1/event-log?after=41&limit=500&kinds=log&kinds=warning', + ) + expect(calls[0][1]?.method ?? 'GET').toBe('GET') + }) + + it('sends no query when nothing narrows it, and keeps after=-1', async () => { + const calls = stubFetch({ ok: true, body: { events: [] } }) + await api.eventLog('j1') + await api.eventLog('j1', { after: -1 }) + expect(calls[0][0]).toBe('/api/jobs/j1/event-log') + expect(calls[1][0]).toBe('/api/jobs/j1/event-log?after=-1') + }) + + it('fails with the 404 status for an unknown job', async () => { + stubFetch({ ok: false, status: 404, body: { detail: 'Unknown job' } }) + const failure = await api.eventLog('gone').catch((e) => e) + expect(failure.status).toBe(404) + }) +}) + describe('job listing', () => { it('passes workspace, status set and limit as query parameters', async () => { const calls = stubFetch({ ok: true, body: { jobs: [], total: 0 } }) diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 151d9289b..49528fcfc 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -10,6 +10,7 @@ import type { DiskCacheEntryDeleted, DiskCacheList, EnhancerPresets, + EventLogReply, GalleryList, GalleryMetadata, AssessReply, @@ -202,6 +203,26 @@ export const api = { * readable. */ getJobWorkflow: (id: string) => request(`/api/jobs/${id}/workflow`), + /** One JSON page of a job's events, after `after` (exclusive). `kinds` + * goes as repeated parameters and keeps events whose `event` or `kind` + * is one of them. A finished job answers from the tail history kept, + * with a `note` on what was dropped; an unknown job is a 404. */ + eventLog: ( + id: string, + { + after, + limit, + kinds, + }: { after?: number; limit?: number; kinds?: string[] } = {}, + ) => { + const query = new URLSearchParams() + if (after !== undefined) query.set('after', String(after)) + if (limit !== undefined) query.set('limit', String(limit)) + for (const kind of kinds ?? []) query.append('kinds', kind) + const qs = query.toString() + const path = `/api/jobs/${id}/event-log` + return request(qs ? `${path}?${qs}` : path) + }, /** Queue the job again. `newSeed` draws a fresh seed into the workflow's * seed variable; without it the arguments repeat exactly, which the step * cache serves from the earlier run rather than generating anything. diff --git a/ui/src/lib/job/EventLog.svelte b/ui/src/lib/job/EventLog.svelte new file mode 100644 index 000000000..22a11083a --- /dev/null +++ b/ui/src/lib/job/EventLog.svelte @@ -0,0 +1,223 @@ + + +
+
+

+ +

+ {#if open && loaded && !missing && rows.length} + + {/if} + {#if open && live && loaded && !missing} + + {/if} +
+ + {#if open} +
+ {#if loading && !loaded} +

Loading…

+ {:else if missing} +

no event log for this job

+ {:else} + {#if error}

{error}

{/if} + {#if note}

{note}

{/if} + {#if loaded && !rows.length && !error} +

no events

+ {:else if shown.length} + + + + + + {#each shown as event (event.seq)} + + + + + + + {/each} + +
seqtimekindevent
{event.seq}{typeof event.at === 'number' + ? '+' + formatDuration(event.at) + : ''}{eventKind(event)}{eventSummary(event)}
+ {/if} + {#if capped} +

+ showing the first {rows.length.toLocaleString('en-US')}; more on the + server +

+ {/if} + {/if} +
+ {/if} +
+ + diff --git a/ui/src/lib/job/eventLog.test.ts b/ui/src/lib/job/eventLog.test.ts new file mode 100644 index 000000000..d438941c0 --- /dev/null +++ b/ui/src/lib/job/eventLog.test.ts @@ -0,0 +1,103 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { api } from '../api' +import type { EventLogReply, JobEvent } from '../types' +import { + EVENT_LOG_CAP, + eventKind, + eventSummary, + fetchEventLog, +} from './eventLog' + +vi.mock('../api', () => ({ api: { eventLog: vi.fn() } })) + +/** A server holding events 0..total-1, paged the way the route pages: + * after is exclusive, truncated when more lie past the page. */ +function serve(total: number, note: string | null = null) { + vi.mocked(api.eventLog).mockImplementation( + async (id, { after = -1, limit = 200 } = {}) => { + const pending: JobEvent[] = [] + for (let seq = after + 1; seq < total; seq++) + pending.push({ seq, event: 'log', message: `line ${seq}` }) + const page = pending.slice(0, limit) + return { + id, + status: 'succeeded', + events: page, + last_seq: page.length ? page[page.length - 1].seq : Math.max(after, -1), + truncated: pending.length > page.length, + note, + } satisfies EventLogReply + }, + ) +} + +afterEach(() => vi.mocked(api.eventLog).mockReset()) + +describe('fetchEventLog', () => { + it('reads one page when the server says it is whole', async () => { + serve(3, 'only the tail was kept') + const got = await fetchEventLog('j1') + expect(got.events.map((e) => e.seq)).toEqual([0, 1, 2]) + expect(got.note).toBe('only the tail was kept') + expect(got.capped).toBe(false) + expect(got.lastSeq).toBe(2) + expect(vi.mocked(api.eventLog).mock.calls).toEqual([ + ['j1', { after: -1, limit: 500 }], + ]) + }) + + it('follows truncated, paging on from each last_seq', async () => { + serve(1200) + const got = await fetchEventLog('j1') + expect(got.events.length).toBe(1200) + expect(got.events.map((e) => e.seq)).toEqual([...Array(1200).keys()]) + expect(got.capped).toBe(false) + expect( + vi.mocked(api.eventLog).mock.calls.map(([, query]) => query?.after), + ).toEqual([-1, 499, 999]) + }) + + it('stops at the cap and says the server holds more', async () => { + serve(7000) + const got = await fetchEventLog('j1') + expect(got.events.length).toBe(EVENT_LOG_CAP) + expect(EVENT_LOG_CAP).toBe(5000) + expect(got.capped).toBe(true) + expect(got.lastSeq).toBe(4999) + expect(vi.mocked(api.eventLog).mock.calls.length).toBe(10) + }) + + it('is not capped when the log is exactly the cap', async () => { + serve(5000) + const got = await fetchEventLog('j1') + expect(got.events.length).toBe(5000) + expect(got.capped).toBe(false) + }) + + it('pages on from a given seq, and keeps it when nothing is new', async () => { + serve(10) + const got = await fetchEventLog('j1', 9) + expect(got.events).toEqual([]) + expect(got.lastSeq).toBe(9) + expect(vi.mocked(api.eventLog).mock.calls[0][1]?.after).toBe(9) + }) +}) + +describe('row text', () => { + it("shows a message as is, or the payload's rest as compact JSON", () => { + expect(eventSummary({ seq: 1, event: 'log', at: 2, message: 'hi' })).toBe( + 'hi', + ) + expect( + eventSummary({ seq: 2, event: 'step_start', at: 3, step: 'gen' }), + ).toBe('{"step":"gen"}') + expect(eventSummary({ seq: 3, event: 'job_done' })).toBe('') + }) + + it('files a warning under its own kind beside the event name', () => { + expect(eventKind({ seq: 1, event: 'warning', kind: 'phase_stall' })).toBe( + 'warning · phase_stall', + ) + expect(eventKind({ seq: 1, event: 'log' })).toBe('log') + }) +}) diff --git a/ui/src/lib/job/eventLog.ts b/ui/src/lib/job/eventLog.ts new file mode 100644 index 000000000..d8baa7a8b --- /dev/null +++ b/ui/src/lib/job/eventLog.ts @@ -0,0 +1,67 @@ +import { api } from '../api' +import type { JobEvent } from '../types' + +/** Events asked for per request, and the most one fetch gathers. A live + * job's in-memory log can run longer than the cap; Refresh pages on. */ +export const EVENT_LOG_PAGE = 500 +export const EVENT_LOG_CAP = 5000 + +export type EventLogFetch = { + events: JobEvent[] + /** The seq to page on from: the last event kept, or `after` if none. */ + lastSeq: number + note: string | null + /** The cap stopped the paging while the server still had more. */ + capped: boolean +} + +/** A job's event log from `after` on, paged at EVENT_LOG_PAGE while the + * server says a page was cut short, and stopped at `cap` events. Pure over + * `api.eventLog`: it holds nothing between calls. */ +export async function fetchEventLog( + id: string, + after = -1, + cap = EVENT_LOG_CAP, +): Promise { + const events: JobEvent[] = [] + let cursor = after + let note: string | null = null + let more = true + while (more && events.length < cap) { + const page = await api.eventLog(id, { + after: cursor, + limit: Math.min(EVENT_LOG_PAGE, cap - events.length), + }) + note = page.note ?? note + events.push(...page.events) + more = page.truncated && page.events.length > 0 + cursor = page.last_seq + } + return { + events, + lastSeq: events.length ? events[events.length - 1].seq : after, + note, + capped: more, + } +} + +// The fields a row already shows in its own columns +const ROW_FIELDS = new Set(['seq', 'event', 'at', 'kind']) + +/** What a row says beyond its seq, time and kind: the event's message, or + * the rest of its payload as compact JSON. */ +export function eventSummary(event: JobEvent): string { + if (typeof event.message === 'string') return event.message + const rest = Object.fromEntries( + Object.entries(event).filter(([key]) => !ROW_FIELDS.has(key)), + ) + return Object.keys(rest).length ? JSON.stringify(rest) : '' +} + +/** The kind a row is filed under: the event name, with a warning's own + * `kind` after it, so a stall and a clip read apart. */ +export function eventKind(event: JobEvent): string { + return typeof event.kind === 'string' + ? `${event.event} · ${event.kind}` + : event.event +} diff --git a/ui/src/lib/pages/JobPage.svelte b/ui/src/lib/pages/JobPage.svelte index baaa88738..f21800fdc 100644 --- a/ui/src/lib/pages/JobPage.svelte +++ b/ui/src/lib/pages/JobPage.svelte @@ -26,6 +26,7 @@ import JobProgress from '../job/JobProgress.svelte' import NoteEditor from '../ui/NoteEditor.svelte' import JobResults from '../job/JobResults.svelte' + import EventLog from '../job/EventLog.svelte' import type { JobDetail, JobEvent } from '../types' let { jobId }: { jobId: string } = $props() @@ -368,6 +369,8 @@
{logs.join('\n')}
{/if} + + {/if} diff --git a/ui/src/lib/job/ChainSegments.test.ts b/ui/src/lib/job/ChainSegments.test.ts new file mode 100644 index 000000000..c3883db3b --- /dev/null +++ b/ui/src/lib/job/ChainSegments.test.ts @@ -0,0 +1,106 @@ +import { cleanup, render, screen, within } from '@testing-library/svelte' +import { afterEach, expect, it } from 'vitest' +import ChainSegments from './ChainSegments.svelte' +import type { JobDetail } from '../types' + +afterEach(cleanup) + +const m = ( + value: number, + ceiling: number | null, + extra: Record = {}, +) => ({ + value, + ceiling, + bound: 'max', + warn_only: false, + failed: false, + ...extra, +}) + +const job = (shots: any[]): JobDetail => + ({ + id: 'job-1', + workspace: 'default', + arguments: {}, + manifest: [ + { step: 'render', files: ['run/still.png'] }, + { step: 'chain', files: ['run/chain.mp4'], shots }, + ], + }) as unknown as JobDetail + +const definition = { + steps: [ + { + name: 'chain', + pipeline: { + chain: { check: true, retries: 2 }, + arguments: { frame_rate: 24 }, + }, + }, + ], +} + +it('renders one row per segment with verdicts, marks and the planned count', () => { + render(ChainSegments, { + job: job([ + { + name: 'segment 1', + start_frame: 0, + num_frames: 97, + planned_segments: 4, + resumed: true, + }, + { + name: 'segment 2', + start_frame: 97, + num_frames: 97, + planned_segments: 4, + attempts: 2, + seed: 1000045, + measures: { + jump_ratio: m(0.9, 0.6, { failed: true }), + texture_ratio: m(1.7, 1.5, { warn_only: true, failed: true }), + mystery: m(1, 2), + }, + }, + { name: 'segment 3 (repaired)', start_frame: 194, num_frames: 97 }, + ]), + definition, + }) + const panel = screen.getByRole('region', { name: 'Chain segments: chain' }) + expect(within(panel).getByText('3 of 4 planned')).toBeTruthy() + const rows = panel.querySelectorAll('tbody tr') + expect(rows).toHaveLength(3) + + expect(rows[0].textContent).toContain('resumed') + expect(rows[0].textContent).toContain( + 'not recorded - resumed from an earlier run', + ) + + const two = rows[1] as HTMLElement + expect(two.textContent).toContain('2 of 3') + expect(two.textContent).toContain('kept seed 1000045') + expect(two.querySelector('.measure.fail')?.textContent).toContain('0.9 ≤ 0.6') + expect(two.querySelector('.measure.warn')?.textContent).toContain('warn') + expect(two.querySelector('.measure.pass')?.textContent).toContain('1 ≤ 2') + expect( + within(panel).getByRole('columnheader', { name: 'mystery' }), + ).toBeTruthy() + + expect(rows[2].textContent).toContain('(repaired)') + expect(rows[2].textContent).toContain('not recorded') + + // The take, seeked to segment 2's start at 24 fps + const video = two.querySelector('video')! + expect(video.getAttribute('src')).toMatch(/chain\.mp4.*#t=4\.042$/) + expect(video.getAttribute('preload')).toBe('metadata') +}) + +it('renders nothing for a job with no chained step', () => { + const { container } = render(ChainSegments, { + job: job([{ name: 'a', start_frame: 0, num_frames: 10 }]), + definition: null, + }) + expect(container.querySelector('section')).toBeNull() +}) diff --git a/ui/src/lib/pages/JobPage.svelte b/ui/src/lib/pages/JobPage.svelte index d1850fddd..76c1f6fdb 100644 --- a/ui/src/lib/pages/JobPage.svelte +++ b/ui/src/lib/pages/JobPage.svelte @@ -27,6 +27,7 @@ import NoteEditor from '../ui/NoteEditor.svelte' import JobResults from '../job/JobResults.svelte' import EventLog from '../job/EventLog.svelte' + import ChainSegments from '../job/ChainSegments.svelte' import type { JobDetail, JobEvent } from '../types' let { jobId }: { jobId: string } = $props() @@ -356,6 +357,8 @@ {/if} + + {#if job.error}

Error

From 3e0ab98be7310fd9613fa987c9e73fcf8a8c04b8 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 12:24:16 -0600 Subject: [PATCH 295/412] chore(arch): #1481 - modules baseline 263 -> 265 (modules: 265) for dw/ledger.py and dw_mcp/ledger.py (arch-approved) The requests-ledger stage of #1458 adds two modules that plan v2 names: dw/ledger.py (the ledger model, validation and file I/O, kept clear of the HTTP 'request' name) and dw_mcp/ledger.py (the set_request/get_request MCP handlers). modules rose by 2 (271 -> 273 against the merge base); the waiver was ruled on #1481 on 2026-11-19 (arch-approved), so the baseline rises by exactly those 2. Co-Authored-By: Claude Opus 5.5 --- docs/stabilization/baseline.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/stabilization/baseline.json b/docs/stabilization/baseline.json index 208719c01..29bebca90 100644 --- a/docs/stabilization/baseline.json +++ b/docs/stabilization/baseline.json @@ -1,5 +1,5 @@ { - "modules": 263, + "modules": 265, "modules_over_size_ceiling": 0, "functions_over_150_lines": 0, "prefix_literals": 0, From 9b7a940e15804268eaf49ec6343e2edbf639451a Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 12:42:31 -0600 Subject: [PATCH 296/412] feat(ui): #1476 - repair and continue actions on the chain segment table Each row offers Repair this segment: live when the chain step's model is one a pipeline step of templates/minimax/repair-segment loads, on rows 2..N with a kept segment file and no repaired segment in the take; else disabled with one reason. It opens the template's workflow page with chain_take and segment filled through a one-shot sessionStorage pre-fill. A take stopped short of its plan with every segment kept and stop_after / resume_from declared as variables offers Continue the chain: a confirmed rerun resuming from the last segment with stop_after cleared. Co-Authored-By: Claude Opus 5.5 --- docs/SERVER.md | 22 ++- ui/e2e/chain-actions.spec.ts | 179 +++++++++++++++++++++++ ui/src/lib/chainActions.test.ts | 210 +++++++++++++++++++++++++++ ui/src/lib/chainActions.ts | 134 +++++++++++++++++ ui/src/lib/chainRows.ts | 26 ++-- ui/src/lib/job/ChainSegments.svelte | 131 ++++++++++++++++- ui/src/lib/pages/WorkflowPage.svelte | 23 ++- 7 files changed, 709 insertions(+), 16 deletions(-) create mode 100644 ui/e2e/chain-actions.spec.ts create mode 100644 ui/src/lib/chainActions.test.ts create mode 100644 ui/src/lib/chainActions.ts diff --git a/docs/SERVER.md b/docs/SERVER.md index 79bc7a833..ed9f29d3a 100644 --- a/docs/SERVER.md +++ b/docs/SERVER.md @@ -241,9 +241,25 @@ icon, a finish-alert toggle, the theme toggle, and links to these docs and own name. A segment 1 the check had nothing to compare says "nothing measured"; a resumed segment, a `(repaired)` one, and a checked chain recorded before measures were kept say "not recorded"; a chain run with - `check` off has no measure cells. The table is read-only - (`ui/src/lib/job/ChainSegments.svelte`, its rows from - `ui/src/lib/chainRows.ts`). + `check` off has no measure cells (`ui/src/lib/job/ChainSegments.svelte`, + its rows from `ui/src/lib/chainRows.ts`). + + Each row ends with **Repair this segment**. It is live only when the + chain step loads a model that a pipeline step of + `templates/minimax/repair-segment` loads (today H3; the rule is read off + both definitions, not a family name), on rows 2..N whose segment file the + run kept, in a take with no `(repaired)` segment. Pressing it opens that + template's workflow page with `chain_take` set to the take's `output:` + reference and `segment` to the row's number; nothing runs until **Run**. + A disabled button says why, in one sentence: no repair-segment template + for this model family, segment 1 cannot be repaired (re-render with a new + seed), a repaired take has no segment files, or the run did not keep its + segments. A take that stopped short of its plan, kept every segment's + file, and whose chain's `stop_after` and `resume_from` are both declared + variables offers **Continue the chain** above the table: after a confirm, + it reruns the job with `resume_from` set to the last segment's `output:` + reference and `stop_after` cleared, and opens the new job. What each + action offers and sends is `ui/src/lib/chainActions.ts`. Every job page, live or from history, ends with an **Event log** section, collapsed until clicked; nothing is fetched before then. Opening it reads diff --git a/ui/e2e/chain-actions.spec.ts b/ui/e2e/chain-actions.spec.ts new file mode 100644 index 000000000..995d05ada --- /dev/null +++ b/ui/e2e/chain-actions.spec.ts @@ -0,0 +1,179 @@ +import { expect, test, type Page } from '@playwright/test' + +// The chain segment table's actions (#1476), on a mocked finished H3 job +// that stopped after 2 of its 4 planned segments and kept both segment +// files: Repair this segment opens repair-segment with its fields filled, +// and Continue the chain posts the rerun that resumes from segment 2. + +const ID = 'j-chain-actions' +const NEXT = 'j-chain-actions-next' +const H3 = 'MiniMaxAI/MiniMax-H3' +const REPAIR = 'templates/minimax/repair-segment' + +const shots = [1, 2].map((i) => ({ + name: `segment ${i}`, + start_frame: (i - 1) * 121, + num_frames: 121, + planned_segments: 4, + attempts: 1, + segment_file: `take.segment-00${i}.mp4`, +})) + +const job = (id: string) => ({ + id, + status: 'succeeded', + workflow: 'narrated-take', + workflow_name: 'narrated-take', + workspace: 'default', + arguments: { stop_after: 2, keep_segments: true }, + acknowledged: 'none', + acknowledged_cost: null, + created_at: 1_700_000_000, + started_at: 1_700_000_001, + finished_at: 1_700_000_942, + error: null, + traceback: null, + warnings: [], + event_count: 0, + manifest: [ + { + step: 'take', + files: [ + 'run/take.mp4', + 'run/take.segment-001.mp4', + 'run/take.segment-002.mp4', + ], + shots, + }, + ], + run_dir: null, + run_id: null, + run_version: null, + historical: true, +}) + +const definition = { + id: 'narrated-take', + variables: { stop_after: null, resume_from: null, keep_segments: false }, + steps: [ + { + name: 'take', + pipeline: { + from_pretrained_arguments: { model_name: H3 }, + chain: { + save_segments: true, + keep_segments: 'variable:keep_segments', + stop_after: 'variable:stop_after', + resume_from: 'variable:resume_from', + }, + arguments: {}, + }, + }, + ], +} + +const repairTemplate = { + id: 'repair-segment', + variables: { chain_take: '', chain_output: '', segment: 2 }, + steps: [ + { + name: 'repair', + pipeline: { + from_pretrained_arguments: { model_name: H3 }, + arguments: {}, + }, + }, + ], +} + +async function mockJob(page: Page) { + for (const id of [ID, NEXT]) { + await page.route( + (url) => url.pathname === `/api/jobs/${id}`, + (route) => route.fulfill({ json: job(id) }), + ) + await page.route( + (url) => url.pathname === `/api/jobs/${id}/workflow`, + (route) => + route.fulfill({ + json: { id, definition, realized: true, seed_variable: null }, + }), + ) + } + await page.route( + (url) => url.pathname === `/api/workflows/${REPAIR}`, + (route) => route.fulfill({ json: repairTemplate }), + ) + await page.route('**/outputs/**', (route) => route.fulfill({ status: 404 })) +} + +test('Repair this segment opens repair-segment with the take and segment filled', async ({ + page, +}) => { + await mockJob(page) + let submitted = false + await page.route( + (url) => url.pathname === '/api/jobs', + (route) => { + if (route.request().method() === 'POST') submitted = true + return route.fallback() + }, + ) + await page.goto(`/#/ws/default/jobs/${ID}`) + + const table = page.getByRole('region', { name: 'Chain segments: take' }) + const rows = table.locator('tbody tr') + await expect(rows).toHaveCount(2) + const first = rows.nth(0).getByRole('button', { name: 'Repair this segment' }) + await expect(first).toBeDisabled() + await expect(rows.nth(0)).toContainText( + 'segment 1 cannot be repaired - re-render with a new seed', + ) + + const second = rows + .nth(1) + .getByRole('button', { name: 'Repair this segment' }) + await expect(second).toBeEnabled() + await second.click() + + await expect(page).toHaveURL( + /#\/ws\/default\/workflows\/templates\/minimax\/repair-segment$/, + ) + await expect(page.locator('#var-chain_take')).toHaveValue( + 'output:run/take.mp4', + ) + await expect(page.locator('#var-segment')).toHaveValue('2') + // Filled in, not run + expect(submitted).toBe(false) +}) + +test('Continue the chain posts the rerun that resumes from the last segment', async ({ + page, +}) => { + await mockJob(page) + let body: unknown = null + await page.route( + (url) => url.pathname === `/api/jobs/${ID}/rerun`, + (route) => { + body = route.request().postDataJSON() + return route.fulfill({ json: job(NEXT) }) + }, + ) + await page.goto(`/#/ws/default/jobs/${ID}`) + + const table = page.getByRole('region', { name: 'Chain segments: take' }) + await table.getByRole('button', { name: 'Continue the chain' }).click() + await page + .getByRole('alertdialog') + .getByRole('button', { name: 'Continue' }) + .click() + + await expect(page).toHaveURL(new RegExp(`#/ws/default/jobs/${NEXT}$`)) + expect(body).toEqual({ + new_seed: false, + arguments: { + resume_from: 'output:run/take.segment-002.mp4', + stop_after: null, + }, + }) +}) diff --git a/ui/src/lib/chainActions.test.ts b/ui/src/lib/chainActions.test.ts new file mode 100644 index 000000000..9140f8402 --- /dev/null +++ b/ui/src/lib/chainActions.test.ts @@ -0,0 +1,210 @@ +import { describe, expect, it } from 'vitest' +import { + FIRST_SEGMENT, + NO_REPAIR_TEMPLATE, + NO_SEGMENTS, + REPAIRED_TAKE, + REPAIR_TEMPLATE, + chainModel, + continueAction, + repairAction, + repairModels, +} from './chainActions' +import { chainRows, type ChainTable } from './chainRows' +import type { ManifestEntry } from './types' + +const H3 = 'MiniMaxAI/MiniMax-H3' +const LTX = 'Lightricks/LTX-2.5-Diffusers' + +// The repair template as the catalog holds it: one pipeline step loading H3 +const repairTemplate = { + variables: { chain_take: '', segment: 2 }, + steps: [ + { name: 'split', task: { command: 'get_frame' } }, + { + name: 'repair', + pipeline: { from_pretrained_arguments: { model_name: H3 } }, + }, + ], +} + +const shot = (i: number, extra: Record = {}) => ({ + name: `segment ${i}`, + start_frame: (i - 1) * 121, + num_frames: 121, + planned_segments: 4, + ...extra, +}) + +const kept = (i: number) => shot(i, { segment_file: `take.segment-00${i}.mp4` }) + +const table = (shots: any[]): ChainTable => + chainRows({ + step: 'take', + files: [ + 'run/take.mp4', + ...shots + .filter((s) => s.segment_file) + .map((s) => `run/${s.segment_file}`), + ], + shots, + } as unknown as ManifestEntry) as ChainTable + +const definition = (model: unknown, chain: Record = {}) => ({ + variables: { + model: H3, + stop_after: 2, + resume_from: null, + keep_segments: true, + }, + steps: [ + { + name: 'take', + pipeline: { + from_pretrained_arguments: { model_name: model }, + chain, + }, + }, + ], +}) + +describe('chainModel and repairModels', () => { + it('reads the chain step model, following a variable', () => { + expect(chainModel(definition(H3), 'take')).toBe(H3) + expect(chainModel(definition('variable:model'), 'take')).toBe(H3) + expect( + chainModel(definition('variable:model'), 'take', { model: LTX }), + ).toBe(LTX) + expect(chainModel(definition(H3), 'other')).toBeNull() + expect(chainModel(null, 'take')).toBeNull() + }) + + it('lists the models a pipeline step of the repair template loads', () => { + expect(repairModels(repairTemplate)).toEqual([H3]) + expect(repairModels(null)).toEqual([]) + }) +}) + +describe('repairAction', () => { + const models = repairModels(repairTemplate) + const t = table([kept(1), kept(2), kept(3)]) + + it('opens repair-segment with the take and the segment number', () => { + expect(repairAction(t, t.rows[2], H3, models)).toEqual({ + enabled: true, + workflow: REPAIR_TEMPLATE, + arguments: { chain_take: 'output:run/take.mp4', segment: '3' }, + }) + }) + + it('is off for a family with no repair template', () => { + expect(repairAction(t, t.rows[1], LTX, models)).toEqual({ + enabled: false, + reason: NO_REPAIR_TEMPLATE, + }) + expect(repairAction(t, t.rows[1], null, models)).toMatchObject({ + reason: NO_REPAIR_TEMPLATE, + }) + // The template could not be read: nothing to repair with + expect(repairAction(t, t.rows[1], H3, [])).toMatchObject({ + reason: NO_REPAIR_TEMPLATE, + }) + }) + + it('is off on segment 1', () => { + expect(repairAction(t, t.rows[0], H3, models)).toEqual({ + enabled: false, + reason: FIRST_SEGMENT, + }) + }) + + it('is off on every row of a repaired take', () => { + const r = table([ + shot(1), + shot(2, { name: 'segment 2 (repaired)' }), + shot(3), + ]) + expect(repairAction(r, r.rows[2], H3, models)).toEqual({ + enabled: false, + reason: REPAIRED_TAKE, + }) + }) + + it('is off when the run did not keep its segments', () => { + const r = table([shot(1), shot(2), shot(3)]) + expect(repairAction(r, r.rows[1], H3, models)).toEqual({ + enabled: false, + reason: NO_SEGMENTS, + }) + }) + + it('gives exactly one reason, family first', () => { + const r = table([shot(1), shot(2, { name: 'segment 2 (repaired)' })]) + expect(repairAction(r, r.rows[0], LTX, models)).toMatchObject({ + reason: NO_REPAIR_TEMPLATE, + }) + expect(repairAction(r, r.rows[0], H3, models)).toMatchObject({ + reason: FIRST_SEGMENT, + }) + }) +}) + +describe('continueAction', () => { + const both = { + stop_after: 'variable:stop_after', + resume_from: 'variable:resume_from', + } + + it('resumes from the last kept segment and clears stop_after', () => { + const t = table([kept(1), kept(2)]) + expect(continueAction(t, definition(H3, both))).toEqual({ + arguments: { + resume_from: 'output:run/take.segment-002.mp4', + stop_after: null, + }, + }) + }) + + it('needs both variables declared', () => { + const t = table([kept(1), kept(2)]) + expect( + continueAction( + t, + definition(H3, { resume_from: 'variable:resume_from' }), + ), + ).toBeNull() + expect( + continueAction(t, definition(H3, { stop_after: 'variable:stop_after' })), + ).toBeNull() + // A literal stop_after names no variable to clear + expect( + continueAction( + t, + definition(H3, { stop_after: 2, resume_from: 'variable:resume_from' }), + ), + ).toBeNull() + // A variable the workflow does not declare + expect( + continueAction( + t, + definition(H3, { ...both, stop_after: 'variable:undeclared' }), + ), + ).toBeNull() + }) + + it('is not offered on a complete take', () => { + const t = table([1, 2, 3, 4].map(kept)) + expect(continueAction(t, definition(H3, both))).toBeNull() + }) + + it('is not offered when a row has no segment file', () => { + const t = table([kept(1), shot(2)]) + expect(continueAction(t, definition(H3, both))).toBeNull() + }) + + it('is offered on any family that declares both variables', () => { + // Continue is not H3-only: an LTX chain with both variables offers it + const t = table([kept(1), kept(2)]) + expect(continueAction(t, definition(LTX, both))).not.toBeNull() + }) +}) diff --git a/ui/src/lib/chainActions.ts b/ui/src/lib/chainActions.ts new file mode 100644 index 000000000..88a823286 --- /dev/null +++ b/ui/src/lib/chainActions.ts @@ -0,0 +1,134 @@ +/** What the chain segment table offers on a row and above it (#1476). + * + * **Repair this segment** opens `repair-segment` on the row's segment. Only + * one family has that template, and the UI never names the family: the + * chain step's `pipeline.from_pretrained_arguments.model_name` (a literal or + * a `variable:` the run resolved) has to be a model a pipeline step of the + * repair template loads. Rows 2..N of a take whose segments were kept can be + * repaired; every other row says, in one sentence, why not. + * + * **Continue the chain** reruns a take that stopped short of its plan from + * its last kept segment: the workflow has to declare the variables its + * chain's `stop_after` and `resume_from` name, and every row has to have its + * segment file. Pure, so the rules are tested without a DOM. */ + +import type { ChainRow, ChainTable } from './chainRows' +import { definitionStep, resolved } from './chainRows' +import { OUTPUT, VARIABLE, reference, referenceName } from './references' + +/** The only repair template the catalog holds */ +export const REPAIR_TEMPLATE = 'templates/minimax/repair-segment' + +/** The sessionStorage key the workflow page reads its pre-filled values from, + * once: `{workflow, arguments}` */ +export const WORKFLOW_PREFILL_KEY = 'dw-workflow-prefill' + +export const NO_REPAIR_TEMPLATE = + 'no repair-segment template for this model family' +export const FIRST_SEGMENT = + 'segment 1 cannot be repaired - re-render with a new seed' +export const REPAIRED_TAKE = 'a repaired take has no segment files' +export const NO_SEGMENTS = 'this run did not keep its segments' + +type Definition = Record | null | undefined + +export type RepairAction = + | { enabled: true; workflow: string; arguments: Record } + | { enabled: false; reason: string } + +export interface ContinueAction { + arguments: Record +} + +const modelOf = ( + step: any, + definition: Definition, + args?: Record | null, +): string | null => { + const pipeline = step?.pipeline + const name = resolved( + pipeline?.from_pretrained_arguments?.model_name, + definition, + args, + ) + return typeof name === 'string' && name ? name : null +} + +/** The model the chained step loads, as the run resolved it; null for a + * step the definition does not hold at its top level, or names no model of */ +export function chainModel( + definition: Definition, + step: string, + args?: Record | null, +): string | null { + return modelOf(definitionStep(definition, step), definition, args) +} + +/** Every model a pipeline step of the repair template loads */ +export function repairModels(repair: Definition): string[] { + const steps = Array.isArray(repair?.steps) ? repair.steps : [] + return steps + .map((step: any) => modelOf(step, repair, null)) + .filter((name: string | null): name is string => name !== null) +} + +/** Whether, and how, one row can be repaired. `model` is the chain step's + * (`chainModel`), `models` the repair template's (`repairModels`; empty + * when it could not be read) */ +export function repairAction( + table: ChainTable, + row: ChainRow, + model: string | null, + models: readonly string[], +): RepairAction { + if (model === null || !models.includes(model)) + return { enabled: false, reason: NO_REPAIR_TEMPLATE } + if (row.index === 1) return { enabled: false, reason: FIRST_SEGMENT } + if (table.rows.some((r) => r.repaired)) + return { enabled: false, reason: REPAIRED_TAKE } + if (!row.segmentFile || !table.take) + return { enabled: false, reason: NO_SEGMENTS } + return { + enabled: true, + workflow: REPAIR_TEMPLATE, + arguments: { + chain_take: reference(OUTPUT, table.take), + segment: String(row.index), + }, + } +} + +/** The variable a chain setting names, when the workflow declares it */ +function declaredVariable(value: unknown, definition: Definition) { + const name = referenceName(value, VARIABLE) + const variables = definition?.variables + return name !== null && + variables && + typeof variables === 'object' && + name in variables + ? name + : null +} + +/** The rerun arguments that continue a stopped take from its last segment, + * or null when it is not offered */ +export function continueAction( + table: ChainTable, + definition: Definition, +): ContinueAction | null { + const { rows, planned } = table + if (!rows.length || planned === null || rows.length >= planned) return null + if (rows.some((row) => !row.segmentFile)) return null + const chain = definitionStep(definition, table.step)?.pipeline?.chain + if (!chain || typeof chain !== 'object') return null + const stopAfter = declaredVariable(chain.stop_after, definition) + const resumeFrom = declaredVariable(chain.resume_from, definition) + if (!stopAfter || !resumeFrom) return null + const last = rows[rows.length - 1].segmentFile as string + return { + arguments: { + [resumeFrom]: reference(OUTPUT, last), + [stopAfter]: null, + }, + } +} diff --git a/ui/src/lib/chainRows.ts b/ui/src/lib/chainRows.ts index 26f6a72b7..96a55d4bf 100644 --- a/ui/src/lib/chainRows.ts +++ b/ui/src/lib/chainRows.ts @@ -82,11 +82,15 @@ export interface ChainRow { measures: Record resumed: boolean repaired: boolean + /** The output path of the segment's own clip, when the run kept it */ + segmentFile: string | null } export interface ChainTable { step: string rows: ChainRow[] + /** The output path of the take the chain wrote, when the entry lists it */ + take: string | null /** The plan's segment count, which a `stop_after` take falls short of */ planned: number | null /** Every measure name any row carries, known names first in the engine's @@ -180,15 +184,15 @@ interface RowContext { const orZero = (value: unknown) => (isNumber(value) ? value : 0) +function shotSegmentFile(shot: Shot, ctx: RowContext): string | null { + return typeof shot.segment_file === 'string' && shot.segment_file + ? segmentPath(ctx.entry, ctx.take, shot.segment_file) + : null +} + function shotThumb(shot: Shot, ctx: RowContext): Thumb | null { - const segmentFile = - typeof shot.segment_file === 'string' && shot.segment_file - ? shot.segment_file - : null - if (segmentFile) { - const file = segmentPath(ctx.entry, ctx.take, segmentFile) - return { file, seconds: 0, fraction: 0 } - } + const file = shotSegmentFile(shot, ctx) + if (file) return { file, seconds: 0, fraction: 0 } if (!ctx.take) return null const start = orZero(shot.start_frame) return { @@ -230,6 +234,7 @@ function shotRow(shot: Shot, i: number, ctx: RowContext): ChainRow { ...shotMeasures(shot, ctx), resumed: shot.resumed === true, repaired: String(shot.name ?? '').includes('(repaired)'), + segmentFile: shotSegmentFile(shot, ctx), } } @@ -256,6 +261,7 @@ export function chainRows( return { step: entry.step, rows, + take: ctx.take, planned: planned.length ? Math.max(...planned) : null, measureNames: orderNames(rows.flatMap((row) => Object.keys(row.measures))), } @@ -299,7 +305,7 @@ type Definition = Record | null | undefined /** A value as the run resolved it: a literal, or a `variable:` the job's * arguments (or the definition's own default) supplied. Anything else - * a reference the UI cannot follow - is unknown */ -function resolved( +export function resolved( value: unknown, definition: Definition, args: Record | null | undefined, @@ -310,7 +316,7 @@ function resolved( return definition?.variables?.[name] } -function definitionStep(definition: Definition, step: string) { +export function definitionStep(definition: Definition, step: string) { const at = step.indexOf(MEMBER_SEPARATOR) const name = at === -1 ? step : step.slice(0, at) const steps = Array.isArray(definition?.steps) ? definition.steps : [] diff --git a/ui/src/lib/job/ChainSegments.svelte b/ui/src/lib/job/ChainSegments.svelte index ceac2e9f9..1c017c726 100644 --- a/ui/src/lib/job/ChainSegments.svelte +++ b/ui/src/lib/job/ChainSegments.svelte @@ -3,8 +3,26 @@ * segment's frame, how many renders its check tried, each measure its * kept attempt computed against the ceiling, and whether it was resumed or * repaired. One panel per chained step in the job's manifest; a job with - * no chained step renders nothing. The rows are `chainRows`'s. */ - import { outputUrl } from '../api' + * no chained step renders nothing. The rows are `chainRows`'s. + * + * Each row offers Repair this segment, and a take that stopped short of + * its plan offers Continue the chain (#1476): when each is offered, and + * what it sends, is `chainActions`'s. Repair opens the repair template's + * workflow page with its fields filled; nothing runs until Run there. + * Continue reruns this job, behind a confirm. */ + import { api, outputUrl } from '../api' + import { + REPAIR_TEMPLATE, + WORKFLOW_PREFILL_KEY, + chainModel, + continueAction, + repairAction, + repairModels, + type ContinueAction, + } from '../chainActions' + import { confirmDialog } from '../confirm.svelte' + import { go } from '../router.svelte' + import { notify } from '../toast' import { attemptsText, chainContext, @@ -36,6 +54,67 @@ .filter((table): table is ChainTable => table !== null), ) + // The models the repair template loads: read once there is a chain to + // offer it on. Unreadable, it repairs nothing + let models = $state([]) + const hasChain = $derived(tables.length > 0) + $effect(() => { + if (!hasChain) return + let stopped = false + try { + api + .getWorkflow(REPAIR_TEMPLATE) + .then(({ definition: repair }) => { + if (!stopped) models = repairModels(repair as Record) + }) + .catch(() => { + /* no repair template on this server */ + }) + } catch { + /* no repair template on this server */ + } + return () => { + stopped = true + } + }) + + const args = $derived(job.arguments as Record) + const repairFor = (table: ChainTable, row: ChainRow) => + repairAction(table, row, chainModel(definition, table.step, args), models) + + function repair(table: ChainTable, row: ChainRow) { + const action = repairFor(table, row) + if (!action.enabled) return + sessionStorage.setItem( + WORKFLOW_PREFILL_KEY, + JSON.stringify({ + workflow: action.workflow, + arguments: action.arguments, + }), + ) + go('ws', job.workspace, 'workflows', ...action.workflow.split('/')) + } + + let continuing = $state(false) + async function continueChain(table: ChainTable, action: ContinueAction) { + const remaining = (table.planned ?? 0) - table.rows.length + const ok = await confirmDialog( + `Queue this job again from its last kept segment (${table.rows.length} of ${table.planned})? ` + + `It renders the remaining ${remaining} segment${remaining === 1 ? '' : 's'} of ${table.step}.`, + { confirmLabel: 'Continue' }, + ) + if (!ok) return + continuing = true + try { + const next = await api.rerunJob(job.id, { arguments: action.arguments }) + go('ws', job.workspace, 'jobs', next.id) + } catch (e) { + notify.error(e instanceof Error ? e.message : String(e)) + } finally { + continuing = false + } + } + const fileUrl = (path: string) => outputUrl(path, job.id, job.workspace) const plannedText = (table: ChainTable) => @@ -96,6 +175,7 @@ {#each tables as table (table.step)} + {@const more = continueAction(table, definition)}
{table.step} {plannedText(table)} + {#if more} +
+ +
+ {/if}
@@ -119,10 +211,12 @@ {:else if anyChecked(table)} {/if} + {#each table.rows as row (row.index)} + {@const action = repairFor(table, row)} {/if} + {/each} @@ -278,4 +385,24 @@ .muted { color: var(--muted); } + .continue { + margin-bottom: 0.5rem; + } + .repair button { + white-space: nowrap; + font-size: 0.8rem; + } + .repair .reason { + display: block; + max-width: 16rem; + font-size: 0.75rem; + } + .sr-only { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + } diff --git a/ui/src/lib/pages/WorkflowPage.svelte b/ui/src/lib/pages/WorkflowPage.svelte index db526c378..a5f5bae2b 100644 --- a/ui/src/lib/pages/WorkflowPage.svelte +++ b/ui/src/lib/pages/WorkflowPage.svelte @@ -27,6 +27,7 @@ import { onDestroy } from 'svelte' import { describePlan } from '../plan' import { placeFindings } from '../findings' + import { WORKFLOW_PREFILL_KEY } from '../chainActions' let { name }: { name: string } = $props() @@ -56,8 +57,28 @@ * steps=30". Null when the card has no cost - never "unknown cost". */ let curated = $state(null) + /** Values another page asked this one to open with (Repair this + * segment, #1476): read once, and only when they name this workflow. + * Filled in, never submitted - Run is still the user's */ + function takePrefill(): Record { + const raw = sessionStorage.getItem(WORKFLOW_PREFILL_KEY) + if (raw === null) return {} + sessionStorage.removeItem(WORKFLOW_PREFILL_KEY) + try { + const parsed = JSON.parse(raw) + if (parsed?.workflow !== name) return {} + const args = parsed.arguments + if (!args || typeof args !== 'object') return {} + return Object.fromEntries( + Object.entries(args).map(([key, value]) => [key, String(value)]), + ) + } catch { + return {} + } + } + $effect(() => { - overrides = {} + overrides = takePrefill() workflow = null origin = '' writable = true From 770b86f6b0aa82910d9d87359c181158623a0e0f Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 12:47:01 -0600 Subject: [PATCH 297/412] docs(proposals): #1452 - record the #1499 fix-forward in the design record Co-Authored-By: Claude Opus 5.5 --- ...gallery-findings-job-event-log-complete.md | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/docs/proposals/complete/gallery-findings-job-event-log-complete.md b/docs/proposals/complete/gallery-findings-job-event-log-complete.md index f3f305615..1ca7ce968 100644 --- a/docs/proposals/complete/gallery-findings-job-event-log-complete.md +++ b/docs/proposals/complete/gallery-findings-job-event-log-complete.md @@ -124,6 +124,34 @@ C-F1097 to C-F1099, C-F1101 and SE-F075, with two arms short: static mocks can't make `seq` follow each request's `after`. Filed as dkackman/harnest#254. The cap is covered by `eventLog.test.ts`. +### Fix-forward (#1499): a live job's log rows past the fold + +The feature's final check (develop @ `058736f9`) failed **C-F1097**. On a running job, the +table seemed to end at seq 11, but Refresh sent `after=13`. Rows 12 and 13 never +appeared, and nothing appended after a Refresh. Fix-forward stage #1499 was filed against +stage B's behaviour, with C-F1097 as its acceptance. + +- **Diagnosis:** no row was lost, and the server was right. The log body is a 512px + scroll box. Each `memory` row's JSON payload wrapped to about 132px, so seq 12 onward + sat below the fold, and macOS overlay scrollbars hid that there was more. The cursor + `after=13` was the last row in the DOM. +- **Fix** (`7ec42ae5`, merged `59c05925`, UI only, `EventLog.svelte`): + - each row is one line, with the event column ellipsized and the full summary in its + text and `title`; + - a count line above the rows, such as `25 events, seq 0–24`, or `2 of 25 …` with a + filter on; + - a live log scrolls to its newest row after the first load and after each Refresh + that brings rows; + - the Refresh button's accessible name is "Refresh event log". +- **Tests:** a new live-job case in `ui/e2e/job-event-log.spec.ts`, built from a real + mini-ai answer with its `memory` payloads. It fails on the old component. +- **Verified** on mini-ai (develop @ `59c05925`): C-F1097 passed on a fresh live job. + +**Bounces at the final check: 1** (C-F1097, a layout miss in stage B), fixed forward by +#1499. Also from that check: #1498, the job page's "Unknown job" error persisting after +navigating to a valid job (filed separately and closed, not part of this feature's +acceptance). + Stage costs aren't recorded, because the stage comments name no `usage:` figures. The plan estimated about $6. Neither stage used GPU time; the fixtures were CPU tasks and one small text-to-image job. From fd07b289e4e0ad0660197fe6f5b1f657a69b0ec7 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 12:52:59 -0600 Subject: [PATCH 298/412] docs(proposals): #1456 - record the #1501 fix-forward in the design record Co-Authored-By: Claude Opus 5.5 --- .../lora-editor-suggestions-complete.md | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/docs/proposals/complete/lora-editor-suggestions-complete.md b/docs/proposals/complete/lora-editor-suggestions-complete.md index baa1d55c2..16c9f1cbd 100644 --- a/docs/proposals/complete/lora-editor-suggestions-complete.md +++ b/docs/proposals/complete/lora-editor-suggestions-complete.md @@ -91,6 +91,23 @@ the optional `.withicon` cleanup needed no change. C-F1119, SE-F077 and SE-F078 pass; C-F1118 (b) and (c) pass; C-F1120 passes in the light theme. No LoRA was downloaded and no job ran. +### Fix-forward #1501: a failed catalog fetch shows its line (C-F1119 c/d) + +The feature's final check (at `058736f9`) failed C-F1119 (c) and (d). With +`/api/loras` stubbed to a 500 or aborted, the panel showed only its heading. The +`'loading'` state rendered nothing under the heading, so a fetch that never settled in +the browser looked the same as a failed one. Commit `e9a82b67` was merged to `develop` +as `5d245a10` (branch `feat/1456-A-catalog-fetch-error`): +- the loading state now shows "Loading catalog suggestions…"; +- a fetch still unsettled after 8 s counts as failed and shows "Catalog suggestions are + unavailable right now."; +- Playwright routes `/api/loras?*` to a 500, an abort and a request that is never + answered, and asserts the line each time; vitest covers the loading line and the + timeout. + +It was verified on mini-ai at `4dc724fe`: C-F1119 (a)–(e) pass, and C-F1120 passes in +both themes. A late answer after the timeout replaces the error line. + ## Bounces Stage A: one. @@ -100,18 +117,20 @@ Stage A: one. `color: var(--ink)`, with a Playwright check that reads them with no wait after each toggle. +Feature final check: one (C-F1119 c/d), fixed forward in #1501, which then passed +with no bounce. + ## Cost Not recorded: no stage comment names a `usage:` figure. The plan estimated $3–5. ## Open points -- **C-F1118 (a) keeps `pending: #1480`.** The case asserts `turbo-reference` first for - an unpartitioned H3 step; the build follows the plan's "proven first, then by name", - which puts it 4th of 4 proven. The tester filed the case amendment as - dkackman/harnest#255 / #256. -- **C-F1120's dark theme was not re-run** after the fix: the ui-check runner has no - colour-scheme emulation. The fix is pinned by the Playwright check instead. +- **C-F1118 passed in the final check.** It was checked against the plan's order + (proven first, then by name), which is the subject of dkackman/harnest#255 / #256. The + tester removed its `pending: #1480` line. +- **C-F1120's dark theme** was re-run in #1501's verify, by toggling the theme and + reloading. It passes. - **The rest of the step editor lags the theme switch** the same way (any text inheriting from `.panel`). It predates this feature; fixing it means changing the global `.panel` transition in `ui/src/app.css`. From 115d39b67d4bf2585edea5f02e3e5eda76277f63 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 13:01:21 -0600 Subject: [PATCH 299/412] fix(ledger): #1481 - an id with a '/' or none meets the id rule The MCP client percent-encodes the request id, and the router decodes it, so an id like a/b or an empty one matched no ledger route and got a bare 404/405. The GET-one and PUT routes take {request_id:path}, so the ledger's validate_ledger_key answers every bad id with its reason. Co-Authored-By: Claude Opus 5.5 --- dw/server/routes/library.py | 7 +++++-- tests/test_ledger.py | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/dw/server/routes/library.py b/dw/server/routes/library.py index 90cb193a4..94ab0c5d0 100644 --- a/dw/server/routes/library.py +++ b/dw/server/routes/library.py @@ -935,6 +935,9 @@ def enhance( # carries `query_token_ok`: nothing a browser loads without headers reads # the ledger. A default workspace with no root folder reads as holding no # requests, and a write is refused with 409 `no_workspace_root`. +# `{request_id:path}`: the router decodes a percent-encoded '/', so an id +# like `a/b` (or an empty one) must still match here and meet the ledger's +# id rule (`validate_ledger_key`), not fall through to a bare 404/405. class RequestWrite(BaseModel): @@ -984,7 +987,7 @@ def list_requests(request: Request, name: str): @router.get( - "/api/workspaces/{name}/requests/{request_id}", + "/api/workspaces/{name}/requests/{request_id:path}", response_model=LedgerRequest, response_model_exclude_unset=True, ) @@ -1004,7 +1007,7 @@ def get_request(request: Request, name: str, request_id: str): @router.put( - "/api/workspaces/{name}/requests/{request_id}", + "/api/workspaces/{name}/requests/{request_id:path}", response_model=LedgerRequest, response_model_exclude_unset=True, ) diff --git a/tests/test_ledger.py b/tests/test_ledger.py index 9203262f1..8a44869d0 100644 --- a/tests/test_ledger.py +++ b/tests/test_ledger.py @@ -13,6 +13,7 @@ from dw.server.app import create_app from dw.server.jobs import JobManager from dw.workspace import REQUESTS_FILE_NAME, Workspace +from dw_mcp.client import api_path from .test_server import ScriptedWorkerManager, success_script @@ -489,6 +490,20 @@ def test_refusals_carry_their_code(self, server): assert client.get(f"{URL}/A").status_code == 400 assert client.put(f"{URL}/A", json=plan()).status_code == 400 + @pytest.mark.parametrize( + "request_id", ["", "../x", "a/b", "/etc/hosts", "../../etc/hosts"] + ) + def test_an_id_with_a_slash_or_none_meets_the_id_rule(self, server, request_id): + # The MCP client percent-encodes the id (api_path), and the router + # decodes it back: an id with a '/' (or an empty one) must still reach + # the ledger's id rule, not fall through to a bare 404/405. + path = api_path("api", "workspaces", "default", "requests", request_id) + with server() as client: + for reply in (client.get(path), client.put(path, json=plan())): + assert reply.status_code == 400, (request_id, reply.text) + assert "request id" in reply.text.lower(), reply.text + assert client.get(URL).json()["requests"] == [] + def test_a_named_workspace_has_its_own_ledger(self, server, workspace_root): with server() as client: assert ( From fd59627d401dfcdc5a07de1780abebba15b6b1ac Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 13:32:23 -0600 Subject: [PATCH 300/412] feat(ui): #1476 - Continue the chain's confirm quotes an estimate The confirm prices the rerun with POST /api/validate (the job's catalog name, else its definition inline, with the merged arguments, in the job's workspace) and reads the plan's figure line, as the restart-batch confirm does. One that cannot be priced says so. Co-Authored-By: Claude Opus 5.5 --- docs/SERVER.md | 6 ++-- ui/e2e/chain-actions.spec.ts | 48 ++++++++++++++++++++++--- ui/src/lib/api.ts | 2 ++ ui/src/lib/chainActions.test.ts | 54 +++++++++++++++++++++++++++++ ui/src/lib/chainActions.ts | 44 +++++++++++++++++++++++ ui/src/lib/job/ChainSegments.svelte | 42 ++++++++++++++++++---- 6 files changed, 183 insertions(+), 13 deletions(-) diff --git a/docs/SERVER.md b/docs/SERVER.md index ed9f29d3a..66578a465 100644 --- a/docs/SERVER.md +++ b/docs/SERVER.md @@ -256,8 +256,10 @@ icon, a finish-alert toggle, the theme toggle, and links to these docs and seed), a repaired take has no segment files, or the run did not keep its segments. A take that stopped short of its plan, kept every segment's file, and whose chain's `stop_after` and `resume_from` are both declared - variables offers **Continue the chain** above the table: after a confirm, - it reruns the job with `resume_from` set to the last segment's `output:` + variables offers **Continue the chain** above the table. Its confirm + quotes an estimate: `POST /api/validate` with the job's workflow and the + rerun's merged arguments, read as the plan's figure line (one that cannot + be priced says so). Confirmed, it reruns the job with `resume_from` set to the last segment's `output:` reference and `stop_after` cleared, and opens the new job. What each action offers and sends is `ui/src/lib/chainActions.ts`. diff --git a/ui/e2e/chain-actions.spec.ts b/ui/e2e/chain-actions.spec.ts index 995d05ada..742844524 100644 --- a/ui/e2e/chain-actions.spec.ts +++ b/ui/e2e/chain-actions.spec.ts @@ -159,14 +159,54 @@ test('Continue the chain posts the rerun that resumes from the last segment', as return route.fulfill({ json: job(NEXT) }) }, ) + // The confirm prices the rerun with validate, as a run would be priced + let priced: any = null + await page.route('**/api/validate**', (route) => { + priced = route.request().postDataJSON() + return route.fulfill({ + json: { + valid: true, + errors: [], + warnings: [], + plan: { + fingerprint: 'sha256:abc', + steps: 1, + list_entries: {}, + cached_steps: 0, + elided_steps: [], + downloads_required: [], + estimate: { + minutes: 12, + basis: 'catalog', + device: 'mps', + measured_on: 'M4 Max', + partial: false, + unpriced: [], + runs: null, + cached_minutes: 12, + }, + workspace: 'default', + }, + }, + }) + }) await page.goto(`/#/ws/default/jobs/${ID}`) const table = page.getByRole('region', { name: 'Chain segments: take' }) await table.getByRole('button', { name: 'Continue the chain' }).click() - await page - .getByRole('alertdialog') - .getByRole('button', { name: 'Continue' }) - .click() + const dialog = page.getByRole('alertdialog') + await expect(dialog).toContainText('Estimate: ~12 min on mps') + expect(priced).toMatchObject({ + workflow_path: 'narrated-take', + workspace: 'default', + arguments: { + resume_from: 'output:run/take.segment-002.mp4', + stop_after: null, + }, + }) + // Pricing it queued nothing + expect(body).toBeNull() + await dialog.getByRole('button', { name: 'Continue' }).click() await expect(page).toHaveURL(new RegExp(`#/ws/default/jobs/${NEXT}$`)) expect(body).toEqual({ diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 733b44293..76fde7eeb 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -154,6 +154,8 @@ export type ValidateRequest = { workflow?: WorkflowDefinition workflow_path?: string arguments?: Record + /** The workspace it resolves in, when not the open one (body first) */ + workspace?: string sizes?: boolean } diff --git a/ui/src/lib/chainActions.test.ts b/ui/src/lib/chainActions.test.ts index 9140f8402..3e372684b 100644 --- a/ui/src/lib/chainActions.test.ts +++ b/ui/src/lib/chainActions.test.ts @@ -7,6 +7,8 @@ import { REPAIR_TEMPLATE, chainModel, continueAction, + continueConfirmText, + continueValidation, repairAction, repairModels, } from './chainActions' @@ -208,3 +210,55 @@ describe('continueAction', () => { expect(continueAction(t, definition(LTX, both))).not.toBeNull() }) }) + +describe('continueValidation and continueConfirmText', () => { + const action = { + arguments: { + resume_from: 'output:run/take.segment-002.mp4', + stop_after: null, + }, + } + const ran = { workspace: 'ws1', arguments: { stop_after: 2, seed: 7 } } + + it('prices the rerun by the catalog name, with the merged arguments', () => { + expect( + continueValidation( + { ...ran, workflow_name: 'chain-1451' }, + action, + definition(LTX), + ), + ).toEqual({ + workflow_path: 'chain-1451', + workspace: 'ws1', + arguments: { + seed: 7, + stop_after: null, + resume_from: 'output:run/take.segment-002.mp4', + }, + sizes: false, + }) + }) + + it('falls back to the definition the job ran, inline', () => { + const d = definition(LTX) + expect( + continueValidation({ ...ran, workflow_name: null }, action, d), + ).toMatchObject({ workflow: d, workspace: 'ws1' }) + }) + + it('has nothing to price with neither', () => { + expect( + continueValidation({ ...ran, workflow_name: null }, action, null), + ).toBeNull() + }) + + it('states the rerun, then the estimate', () => { + const text = continueConfirmText( + table([kept(1), kept(2)]), + '~3.2 min on mps', + ) + expect(text).toContain('(2 of 4)') + expect(text).toContain('remaining 2 segments of take') + expect(text).toMatch(/\n\nEstimate: ~3\.2 min on mps$/) + }) +}) diff --git a/ui/src/lib/chainActions.ts b/ui/src/lib/chainActions.ts index 88a823286..d637d3001 100644 --- a/ui/src/lib/chainActions.ts +++ b/ui/src/lib/chainActions.ts @@ -15,6 +15,8 @@ import type { ChainRow, ChainTable } from './chainRows' import { definitionStep, resolved } from './chainRows' import { OUTPUT, VARIABLE, reference, referenceName } from './references' +import type { ValidateRequest } from './api' +import type { WorkflowDefinition } from './types' /** The only repair template the catalog holds */ export const REPAIR_TEMPLATE = 'templates/minimax/repair-segment' @@ -132,3 +134,45 @@ export function continueAction( }, } } + +/** What `/api/validate` is asked to price a Continue: the rerun's merged + * arguments (the job's own, then the action's), in the job's workspace, by + * the catalog name it ran as when it has one (so the plan quotes that + * workflow's observed figures), otherwise the definition it ran inline. Null + * when there is neither, and the confirm says it has no estimate. */ +export function continueValidation( + job: { + workflow_name?: string | null + workspace: string + arguments?: Record | null + }, + action: ContinueAction, + definition: Definition, +): ValidateRequest | null { + const source = job.workflow_name + ? { workflow_path: job.workflow_name } + : definition + ? { workflow: definition as WorkflowDefinition } + : null + if (!source) return null + return { + ...source, + workspace: job.workspace, + arguments: { ...(job.arguments ?? {}), ...action.arguments }, + sizes: false, + } +} + +/** The Continue confirm's words: what it reruns, then the estimate line. */ +export function continueConfirmText( + table: ChainTable, + estimate: string, +): string { + const kept = table.rows.length + const remaining = (table.planned ?? 0) - kept + return ( + `Queue this job again from its last kept segment (${kept} of ${table.planned})? ` + + `It renders the remaining ${remaining} segment${remaining === 1 ? '' : 's'} of ${table.step}.` + + `\n\nEstimate: ${estimate}` + ) +} diff --git a/ui/src/lib/job/ChainSegments.svelte b/ui/src/lib/job/ChainSegments.svelte index 1c017c726..861d6b282 100644 --- a/ui/src/lib/job/ChainSegments.svelte +++ b/ui/src/lib/job/ChainSegments.svelte @@ -16,11 +16,14 @@ WORKFLOW_PREFILL_KEY, chainModel, continueAction, + continueConfirmText, + continueValidation, repairAction, repairModels, type ContinueAction, } from '../chainActions' import { confirmDialog } from '../confirm.svelte' + import { describeEstimate } from '../plan' import { go } from '../router.svelte' import { notify } from '../toast' import { @@ -96,13 +99,34 @@ } let continuing = $state(false) + let pricing = $state(false) + // The estimate the confirm quotes: the validate route's plan for the + // rerun's merged arguments, the figure line every plan shows. One that + // cannot be priced says so rather than reading as free + async function continueEstimate(action: ContinueAction): Promise { + const asked = continueValidation( + { ...job, arguments: job.arguments as Record }, + action, + definition, + ) + if (!asked) return describeEstimate(null).text + try { + const answer = await api.validate(asked) + if (!answer.valid) return 'none - a run would be refused' + return describeEstimate(answer.plan?.estimate ?? null).text + } catch (e) { + return `none - could not price it (${e instanceof Error ? e.message : String(e)})` + } + } + async function continueChain(table: ChainTable, action: ContinueAction) { - const remaining = (table.planned ?? 0) - table.rows.length - const ok = await confirmDialog( - `Queue this job again from its last kept segment (${table.rows.length} of ${table.planned})? ` + - `It renders the remaining ${remaining} segment${remaining === 1 ? '' : 's'} of ${table.step}.`, - { confirmLabel: 'Continue' }, + pricing = true + const estimate = await continueEstimate(action).finally( + () => (pricing = false), ) + const ok = await confirmDialog(continueConfirmText(table, estimate), { + confirmLabel: 'Continue', + }) if (!ok) return continuing = true try { @@ -188,11 +212,15 @@
{continuing + ? 'Queueing…' + : pricing + ? 'Pricing…' + : 'Continue the chain'}
{/if} From 9b6ea22f1ce903f541acbcb5987a38436ff05853 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 14:01:55 -0600 Subject: [PATCH 301/412] feat(ledger): #1482 - link jobs to a request item, derive item state from them Admission takes request+item (both or neither, refused before queueing with unknown_request / request_closed / unknown_item / item_dropped), the job record, history, exports and reruns carry the link, GET /api/jobs and /api/gallery filter by request, and the ledger derives item status, attempts, result, accepted_missing, spent and remaining minutes. Co-Authored-By: Claude Opus 5.5 --- dw/ledger.py | 213 +++++++++-- dw/server/admission.py | 24 ++ dw/server/api_models.py | 48 ++- dw/server/app.py | 13 + dw/server/exports.py | 2 + dw/server/job_history.py | 65 +++- dw/server/job_record.py | 7 + dw/server/jobs.py | 122 +++++- dw/server/routes/gallery.py | 25 +- dw/server/routes/jobs.py | 44 ++- dw/server/routes/library.py | 37 +- tests/test_job_history_parity.py | 3 +- tests/test_ledger_job_link.py | 582 +++++++++++++++++++++++++++++ ui/src/lib/generated/api-schema.ts | 98 ++++- ui/src/lib/generated/openapi.json | 274 +++++++++++++- 15 files changed, 1505 insertions(+), 52 deletions(-) create mode 100644 tests/test_ledger_job_link.py diff --git a/dw/ledger.py b/dw/ledger.py index f200c45f7..efff8037f 100644 --- a/dw/ledger.py +++ b/dw/ledger.py @@ -9,10 +9,15 @@ revisioned: the caller names the revision it read, and a write against a newer one is refused rather than merged. -An item's status is derived, never stored. Until jobs are linked to items -(a later stage) every item reads `planned`, or `dropped` when it was removed -from the plan after jobs were linked to it - an item with no linked jobs is -deleted when a write leaves it out. +An item's status is derived, never stored, from the jobs linked to it (a +job is submitted with a `request` and an `item`; the callers pass the linked +jobs into the views): `dropped` when it was removed from the plan after jobs +were linked to it (an item with no linked jobs is deleted when a write +leaves it out); else `done` when any linked job succeeded, `running`, +`queued`, `failed` (every linked job failed or was cancelled) or `planned` +(none). Each item also derives `attempts`, `result` and `spent_minutes`, and +the request `spent_minutes` and `remaining_minutes`; this module reads only +the job dicts it is handed, never the job store. Written with `write_json_atomic` under a per-directory lock (the notes.py pattern), read without one: a rename is atomic, so a reader sees the old @@ -58,8 +63,9 @@ # here - but held to name characters so a later stage can. _WORKFLOW_NAME_PATTERN = r"^[\w][\w.:-]*(/[\w][\w.:-]*)*\Z" -# What an item may carry on a write. `status` is derived and ignored, so a -# plan read with GET can be written back as it came. +# What an item may carry on a write. `status`, `attempts`, `result`, +# `accepted_missing` and `spent_minutes` are derived and ignored, so a plan +# read with GET can be written back as it came. _ITEM_FIELDS = frozenset( ( "key", @@ -72,6 +78,10 @@ "accepted", "comment", "status", + "attempts", + "result", + "accepted_missing", + "spent_minutes", ) ) @@ -144,25 +154,130 @@ def read_requests(root): # --- views --------------------------------------------------------------- -def _item_status(item): - # No job links an item yet, so nothing is running, done or failed - return "dropped" if item.get("dropped") else "planned" +def _no_jobs(_request_id): + return [] + + +def _minutes(job): + """How long a linked job ran, in minutes to two places, or None when it + has not both started and finished.""" + started, finished = job.get("started_at"), job.get("finished_at") + if started is None or finished is None: + return None + return round(max(finished - started, 0) / 60, 2) + + +def _item_status(item, jobs): + """An item's status, derived from the jobs linked to it: dropped; done + (any succeeded); running; queued; failed (every linked job failed or was + cancelled); planned (none).""" + if item.get("dropped"): + return "dropped" + statuses = {job.get("status") for job in jobs} + if "succeeded" in statuses: + return "done" + if "running" in statuses: + return "running" + if "queued" in statuses: + return "queued" + if statuses: + return "failed" + return "planned" + + +def _result(item, jobs): + """`(result, accepted_missing)`: the accepted job's run when it is set + and its run still exists, else the latest-finished succeeded job whose + run exists, else None.""" + accepted = item.get("accepted") + missing = False + if accepted: + for job in jobs: + if job.get("job") == accepted.get("job") and job.get("run_exists"): + return {"job": job["job"], "run_id": job.get("run_id")}, False + missing = True + kept = [ + job + for job in jobs + if job.get("status") == "succeeded" and job.get("run_exists") + ] + if not kept: + return None, missing + latest = max(kept, key=lambda job: job.get("finished_at") or 0) + return {"job": latest["job"], "run_id": latest.get("run_id")}, missing + + +def _jobs_by_item(jobs): + grouped = {} + for job in jobs: + grouped.setdefault(job.get("item"), []).append(job) + for group in grouped.values(): + group.sort(key=lambda job: job.get("created_at") or 0) + return grouped + + +def item_view(item, jobs): + """One item as read, with what its linked `jobs` derive: `status`, + `attempts` (every linked job, oldest first, as `{job, status, note, + minutes}` - `note` only when set, `minutes` null until it has run), + `result`, `accepted_missing` (only when true) and `spent_minutes`.""" + attempts = [ + { + "job": job.get("job"), + "status": job.get("status"), + **({"note": job["note"]} if job.get("note") else {}), + "minutes": _minutes(job), + } + for job in jobs + ] + result, missing = _result(item, jobs) + return { + **item, + "status": _item_status(item, jobs), + "attempts": attempts, + "result": result, + **({"accepted_missing": True} if missing else {}), + "spent_minutes": _spent(jobs), + } + + +def _spent(jobs): + return round(sum(_minutes(job) or 0 for job in jobs), 2) + + +def _remaining(request, grouped): + """What is left to do: the estimates of the items not done and not + dropped.""" + total = 0 + for item in request.get("items", []): + if _item_status(item, grouped.get(item.get("key"), [])) in ("done", "dropped"): + continue + total += item.get("estimate_minutes") or 0 + return round(total, 2) -def request_view(request): - """A stored request as read: every item with its derived `status`.""" +def request_view(request, jobs=()): + """A stored request as read: every item with its derived fields + (`item_view`) and the request's `spent_minutes` and `remaining_minutes`. + `jobs` are the linked jobs (`{job, item, status, run_id, run_exists, + note, created_at, started_at, finished_at}`).""" + grouped = _jobs_by_item(jobs) view = dict(request) view["items"] = [ - {**item, "status": _item_status(item)} for item in request.get("items", []) + item_view(item, grouped.get(item.get("key"), [])) + for item in request.get("items", []) ] + view["spent_minutes"] = _spent(jobs) + view["remaining_minutes"] = _remaining(request, grouped) return view -def summary_view(request): +def summary_view(request, jobs=()): """One row of the list: what a request is, without its items.""" + grouped = _jobs_by_item(jobs) counts = {} for item in request.get("items", []): - status = _item_status(item) + status = _item_status(item, grouped.get(item.get("key"), [])) counts[status] = counts.get(status, 0) + 1 history = request.get("history") or [] return { @@ -172,22 +287,66 @@ def summary_view(request): "revision": request.get("revision"), "items": len(request.get("items", [])), "status_counts": counts, + "spent_minutes": _spent(jobs), + "remaining_minutes": _remaining(request, grouped), "updated_at": history[-1].get("at") if history else None, } -def list_requests(root): - """The list view, newest change first.""" - rows = [summary_view(r) for r in read_requests(root).values()] +def list_requests(root, jobs_for=_no_jobs): + """The list view, newest change first. `jobs_for(request_id)` lists the + jobs linked to a request.""" + rows = [ + summary_view(r, jobs_for(r.get("id"))) for r in read_requests(root).values() + ] rows.sort(key=lambda row: row.get("updated_at") or "", reverse=True) return rows -def get_request(root, request_id): +def get_request(root, request_id, jobs_for=_no_jobs): """One request's view, or None.""" validate_ledger_key(request_id, "Request id") request = read_requests(root).get(request_id) - return request_view(request) if request is not None else None + if request is None: + return None + return request_view(request, jobs_for(request_id)) + + +def link_problem(root, request_id, item_key): + """The LedgerError that says why a job cannot be linked to + `request_id`/`item_key` in the workspace at `root`, or None when it can: + `unknown_request` (no such request, or no root), `request_closed`, + `unknown_item`, `item_dropped`. Both keys are checked as keys first + (InvalidInputError otherwise). Takes no lock.""" + validate_ledger_key(request_id, "Request") + validate_ledger_key(item_key, "Item") + request = read_requests(root).get(request_id) + if request is None: + return LedgerError( + f"no request {request_id!r} in this workspace", + status=422, + code="unknown_request", + ) + if request.get("state") != "open": + return LedgerError( + f"request {request_id!r} is {request.get('state')}, not open", + status=422, + code="request_closed", + ) + for item in request.get("items", []): + if item.get("key") == item_key: + if item.get("dropped"): + return LedgerError( + f"item {item_key!r} of request {request_id!r} was dropped", + status=422, + code="item_dropped", + ) + return None + return LedgerError( + f"request {request_id!r} has no item {item_key!r}", + status=422, + code="unknown_item", + ) # --- validation ---------------------------------------------------------- @@ -318,8 +477,12 @@ def _comment(value, key, existing, by, at): def _accepted(value, key, existing, linked): if value is None: return None + if isinstance(value, str): + value = {"job": value} if not isinstance(value, dict) or set(value) - {"job", "run_id"}: - raise LedgerError(f"item {key!r}: accepted must be {{job, run_id}} or null") + raise LedgerError( + f"item {key!r}: accepted must be {{job}} (or a job id) or null" + ) if existing and value.get("job") == existing.get("job"): return existing job = value.get("job") @@ -536,12 +699,16 @@ def _history(current, write, revision, by, at): return history -def put_request(root, request_id, body, *, by, linked_jobs=_no_links): +def put_request( + root, request_id, body, *, by, linked_jobs=_no_links, jobs_for=_no_jobs +): """Write one request's whole plan and return its view. `body` holds title, goal, items, revision and why, and optionally prompt and state. `linked_jobs(request_id, key)` lists the jobs linked - to an item as `{job, status, run_id}`; none link yet. + to an item as `{job, status, run_id}`; `accepted` must name one of them + that succeeded. `jobs_for(request_id)` lists every job linked to the request, for + the returned view's derived fields. Raises LedgerError, or OSError when the file cannot be written. """ @@ -585,4 +752,4 @@ def put_request(root, request_id, body, *, by, linked_jobs=_no_links): code="ledger_too_large", ) write_json_atomic(ledger_path(root), document) - return request_view(request) + return request_view(request, jobs_for(request_id)) diff --git a/dw/server/admission.py b/dw/server/admission.py index ee1b31e68..ac520a29c 100644 --- a/dw/server/admission.py +++ b/dw/server/admission.py @@ -26,6 +26,7 @@ resolve_asset_reference, ) from .. import get_device_type, references, validation +from ..security import InvalidInputError, validate_ledger_key from ..notes import MAX_NOTE_LENGTH, NoteTooLong, clean_note from ..plan import list_entries from ..plan_downloads import repos_named @@ -475,6 +476,29 @@ class JobRequest(BaseModel): description=f"A note on the run, at most {MAX_NOTE_LENGTH} characters: " "kept with the job and written as the run note when the run opens", ) + request: Optional[str] = Field( + default=None, + description="The requests-ledger request this job serves (with `item`): " + "an open request in the job's workspace. Refused with 422 and a " + "`{code, message}` detail - unknown_request, request_closed, " + "unknown_item or item_dropped - before anything queues", + ) + item: Optional[str] = Field( + default=None, + description="The item key of `request` this job serves; both or neither", + ) + + @model_validator(mode="after") + def _ledger_link(self): + if (self.request is None) != (self.item is None): + raise ValueError("request and item go together: give both or neither") + for value, what in ((self.request, "Request"), (self.item, "Item")): + if value is not None: + try: + validate_ledger_key(value, what) + except InvalidInputError as e: + raise ValueError(str(e)) from e + return self def admitted_note(note): diff --git a/dw/server/api_models.py b/dw/server/api_models.py index 6143cb4ac..1594daab8 100644 --- a/dw/server/api_models.py +++ b/dw/server/api_models.py @@ -433,6 +433,12 @@ class JobSummary(ApiModel): rerun_of: str = sometimes( "The job this one reran; absent for a job submitted fresh." ) + request: str = sometimes( + "The requests-ledger request this job serves; absent when unlinked." + ) + item: str = sometimes( + "The item of `request` this job serves; absent when unlinked." + ) overrides: dict = sometimes( "The variables a rerun changed from the job it reran; absent when none were." ) @@ -1081,6 +1087,20 @@ class LedgerComment(ApiModel): at: str +class LedgerAttempt(ApiModel): + job: str + status: JobStatus + note: str = sometimes("The job's note.") + minutes: int | float | None = Field( + description="Run time; null until the job has started." + ) + + +class LedgerResult(ApiModel): + job: str + run_id: str | None + + class LedgerItem(ApiModel): key: str title: str @@ -1093,8 +1113,26 @@ class LedgerItem(ApiModel): comment: LedgerComment | None = Field( description="The user's; an agent never writes it." ) - status: Literal["planned", "dropped"] = Field( - description="Derived from the item's jobs; none link yet, so planned or dropped." + status: Literal["dropped", "done", "running", "queued", "failed", "planned"] = ( + Field( + description="Derived from the item's linked jobs, first that holds: " + "dropped, done (a result exists), running, queued, failed (every " + "linked job failed or was cancelled), planned." + ) + ) + attempts: list["LedgerAttempt"] = Field( + description="Every linked job, oldest first." + ) + result: "LedgerResult | None" = Field( + description="The accepted job's run, else the latest succeeded job's " + "run whose directory still exists; null when neither." + ) + accepted_missing: bool = sometimes( + "True when an accepted job's run directory is gone; `result` then " + "falls back to the latest succeeded attempt." + ) + spent_minutes: int | float = Field( + description="Minutes the item's linked jobs ran, summed." ) @@ -1115,6 +1153,10 @@ class LedgerRequest(ApiModel): goal: str items: list[LedgerItem] history: list[LedgerHistoryEntry] + spent_minutes: int | float = Field(description="Minutes every linked job ran.") + remaining_minutes: int | float = Field( + description="Estimates of the items not done and not dropped." + ) class LedgerSummary(ApiModel): @@ -1124,6 +1166,8 @@ class LedgerSummary(ApiModel): revision: int items: int status_counts: dict[str, int] + spent_minutes: int | float + remaining_minutes: int | float updated_at: str | None diff --git a/dw/server/app.py b/dw/server/app.py index 3de14119e..f0f22f440 100644 --- a/dw/server/app.py +++ b/dw/server/app.py @@ -122,6 +122,19 @@ def _store_directories( prompts=state.prompt_dir, root=state.workspace, ) + + # Where a job's requests-ledger link is checked on a rerun: the folder + # holding the workspace's requests.json, or None. Never raises - a + # workspace that is gone has no ledger, which the rerun warns about + def ledger_root_for(name): + from .deps import workspace_for + + try: + return workspace_for(state, name).root or None + except Exception: + return None + + manager.ledger_root_for = ledger_root_for # A StaticFiles instance per output/asset root, built lazily and reused - # a mount is bound to one directory at startup, but a named workspace's # root does not exist yet then. Keeping the instance around (rather than diff --git a/dw/server/exports.py b/dw/server/exports.py index 17c2b1db8..da72468e5 100644 --- a/dw/server/exports.py +++ b/dw/server/exports.py @@ -78,6 +78,8 @@ "run_id", "run_dir", "run_version", + "request", + "item", ) README_TEMPLATE = """# {workflow_name} - job {job_id} diff --git a/dw/server/job_history.py b/dw/server/job_history.py index 317920f9a..6be84a4b7 100644 --- a/dw/server/job_history.py +++ b/dw/server/job_history.py @@ -118,6 +118,11 @@ def _memory_key_of(job): # The job a rerun reran. NULL for a fresh submit and for every row # before the column ("rerun_of", "TEXT"), + # The requests-ledger request and item the job was submitted for (#1458). + # NULL for a job with no link and for every row before the columns. A + # workspace forget renames only `workspace`, so both survive it + ("request", "TEXT"), + ("item", "TEXT"), # The variables a rerun changed, as JSON. NULL for a job without any # and for every row before the column ("overrides", "TEXT"), @@ -185,6 +190,8 @@ def _rerun_spec(job): ("note", lambda job: getattr(job, "note", None)), ("memory_key", _memory_key_of), ("rerun_of", lambda job: getattr(job, "rerun_of", None)), + ("request", lambda job: getattr(job, "request", None)), + ("item", lambda job: getattr(job, "item", None)), ( "overrides", lambda job: _json(job.spec["overrides"]) if job.spec.get("overrides") else None, @@ -301,6 +308,10 @@ def __init__(self, db_path): connection.execute( "CREATE INDEX IF NOT EXISTS jobs_rerun_of ON jobs (rerun_of)" ) + # What a request's linked-jobs query and the list filter read + connection.execute( + "CREATE INDEX IF NOT EXISTS jobs_request ON jobs (workspace, request)" + ) @contextlib.contextmanager def _connect(self): @@ -454,7 +465,7 @@ def _peaks_for_key(self, key): committed = [row["committed"] for row in rows if row["committed"] is not None] return (committed or [row["peak"] for row in rows]), bool(committed) - def _history_where(self, workspace, statuses): + def _history_where(self, workspace, statuses, request=None, item=None): """The WHERE clauses and params shared by the summary list and its count, or None when the filter can match no closed row.""" params = [] @@ -476,12 +487,20 @@ def _history_where(self, workspace, statuses): params.extend(statuses) clauses.append(f"status NOT IN ({_OPEN_PLACEHOLDERS})") params.extend(_OPEN_STATES) + if request: + clauses.append("request = ?") + params.append(request) + if item: + clauses.append("item = ?") + params.append(item) return clauses, params - def count_summaries(self, workspace=None, statuses=None, exclude_ids=()): + def count_summaries( + self, workspace=None, statuses=None, exclude_ids=(), request=None, item=None + ): """How many rows `recent_summaries` would match with no limit, not counting `exclude_ids` (#1466).""" - where = self._history_where(workspace, statuses) + where = self._history_where(workspace, statuses, request, item) if where is None: return 0 clauses, params = where @@ -495,7 +514,9 @@ def count_summaries(self, workspace=None, statuses=None, exclude_ids=()): ).fetchone() return row[0] - def recent_summaries(self, limit=200, workspace=None, statuses=None): + def recent_summaries( + self, limit=200, workspace=None, statuses=None, request=None, item=None + ): """Summary rows only - the jobs list is polled, and parsing four JSON blobs per row just to show six scalars was pure waste. @@ -511,10 +532,10 @@ def recent_summaries(self, limit=200, workspace=None, statuses=None): " device, note, run_dir," " CASE WHEN json_valid(spec) THEN json_extract(spec, '$.output_dir') END" " AS output_dir," - " rerun_of, error, server_instance" + " rerun_of, request, item, error, server_instance" " FROM jobs" ) - where = self._history_where(workspace, statuses) + where = self._history_where(workspace, statuses, request, item) if where is None: return [] clauses, params = where @@ -546,6 +567,8 @@ def recent_summaries(self, limit=200, workspace=None, statuses=None): "_run_dir": row["run_dir"], "_output_dir": row["output_dir"], **({"rerun_of": row["rerun_of"]} if row["rerun_of"] else {}), + **({"request": row["request"]} if row["request"] else {}), + **({"item": row["item"]} if row["item"] else {}), # `reason` and, on a restart tombstone, `restart_batch` - so # a caller triages the list without a get_job per row (#1449) **row_reason_fields( @@ -561,13 +584,39 @@ def get(self, job_id): "SELECT id, workflow, status, created_at, started_at, finished_at," " arguments, spec, manifest, warnings, error, workspace," " workflow_name, run_id, run_dir, acknowledged, events," - " run_version, device, note, rerun_of, overrides, server_instance," + " run_version, device, note, rerun_of, request, item, overrides," + " server_instance," " host_memory_job_peak_committed_mb FROM jobs WHERE id = ?" f" AND status NOT IN ({_OPEN_PLACEHOLDERS})", (job_id, *_OPEN_STATES), ).fetchone() return self._to_detail(row) if row else None + def request_jobs(self, workspace, request): + """Every closed job linked to `request` in `workspace`, oldest first: + one indexed query (`jobs_request`). Open jobs are the live queue's.""" + with self._lock, self._connect() as connection: + rows = connection.execute( + "SELECT id, item, status, run_id, run_dir, note, created_at," + " started_at, finished_at," + " CASE WHEN json_valid(spec) THEN json_extract(spec, '$.output_dir') END" + " AS output_dir FROM jobs WHERE workspace = ? AND request = ?" + f" AND status NOT IN ({_OPEN_PLACEHOLDERS}) ORDER BY created_at", + (workspace, request, *_OPEN_STATES), + ).fetchall() + return [dict(row) for row in rows] + + def run_ids_for_request(self, workspace, request): + """The run ids of `workspace`'s jobs linked to `request` - what the + run-based gallery filters by.""" + with self._lock, self._connect() as connection: + rows = connection.execute( + "SELECT run_id FROM jobs WHERE workspace = ? AND request = ?" + " AND run_id IS NOT NULL", + (workspace, request), + ).fetchall() + return {row["run_id"] for row in rows} + def device_ordinal(self, job_id): """The ordinal of the card a finished job ran on ('cuda:1'), or None for a job that never ran or that history has never seen.""" @@ -826,6 +875,8 @@ def parse(text, fallback): "historical": True, **({"note": row["note"]} if row["note"] else {}), **({"rerun_of": row["rerun_of"]} if row["rerun_of"] else {}), + **({"request": row["request"]} if row["request"] else {}), + **({"item": row["item"]} if row["item"] else {}), **({"overrides": parse(row["overrides"], {})} if row["overrides"] else {}), # A detail is a summary plus more, so it carries the row fields # too (#1449) - beside the full `error` they summarise diff --git a/dw/server/job_record.py b/dw/server/job_record.py index 1b8f7fbec..858327109 100644 --- a/dw/server/job_record.py +++ b/dw/server/job_record.py @@ -81,6 +81,9 @@ def row_reason_fields(status, error, server_instance=None): "acknowledged_cost", # the note it was submitted with, carried to the rerun's own run "note", + # the requests-ledger link (#1458): a rerun serves the same item + "request", + "item", ) RERUN_SEED_UNKNOWN = "rerun_seed_unknown" @@ -186,6 +189,8 @@ def __init__(self, spec): # The note it was submitted with; written as the run note at run_start self.note = spec.get("note") self.rerun_of = spec.get("rerun_of") + self.request = spec.get("request") + self.item = spec.get("item") # The worker's own high-water mark for this run, from its final # memory_info message - None for a run that never got that far (#243) self.host_memory_peak_rss_mb = None @@ -425,6 +430,8 @@ def summary(self): ), **({"note": self.note} if self.note else {}), **({"rerun_of": self.rerun_of} if self.rerun_of else {}), + **({"request": self.request} if self.request else {}), + **({"item": self.item} if self.item else {}), # A live job is never a tombstone (the sweep writes those into a # dead server's rows), so only `reason` can apply here **row_reason_fields(self.status, self.error), diff --git a/dw/server/jobs.py b/dw/server/jobs.py index c423f3d81..9cd9994d4 100644 --- a/dw/server/jobs.py +++ b/dw/server/jobs.py @@ -52,7 +52,7 @@ validate_path, validate_workflow_path, ) -from .. import model_use, references +from .. import ledger, model_use, references from ..runs import REALIZED_FILE_NAME from ..settings import resolve_path from ..workspace import DEFAULT_WORKSPACE_NAME @@ -141,6 +141,10 @@ def __init__( # Held across a restart-batch rerun, admission included, so two # concurrent batches cannot both pass its already-rerun check (#1266) self._batch_lock = threading.Lock() + # workspace name -> the folder holding its requests.json, or None; + # set by the app, which knows the workspaces. Unset, a rerun does + # not check the link it inherits + self.ledger_root_for = None # Pending job ids in run order - a list, not a Queue, so the queue # can be reordered while jobs wait self._pending = [] @@ -281,6 +285,8 @@ def submit( note=None, rerun_of=None, overrides=None, + request=None, + item=None, ): """Record a job request and queue it. @@ -332,6 +338,8 @@ def submit( `note` is the run's note, already cleaned (`admitted_note`): kept on the job and written into the run directory when the run opens. + `request` and `item` link the job to a requests-ledger item (#1458). + `rerun_of` is the job this one reruns, recorded so the list can say so; `overrides` the variables the rerun changed, recorded beside it. @@ -387,6 +395,11 @@ def submit( spec["rerun_of"] = rerun_of if overrides: spec["overrides"] = overrides + # The requests-ledger link, already checked by admission (a rerun's + # inherited one is not - `rerun` warns instead) + if request and item: + spec["request"] = request + spec["item"] = item job = Job(spec) job.host_ram_need = host_ram_need @@ -619,6 +632,7 @@ def rerun( if prepared is None: return None spec, recorded = prepared + link_warnings = self._link_warnings(spec) return self.submit( workflow_path=spec.get("workflow_path"), workflow=spec.get("workflow"), @@ -637,7 +651,11 @@ def rerun( else spec.get("acknowledged_cost") ), # keep_drawn_seed's, unless a new_seed replaced the drawn seed - warnings=[*(warnings or []), *([] if new_seed else spec["rerun_warnings"])], + warnings=[ + *(warnings or []), + *([] if new_seed else spec["rerun_warnings"]), + *link_warnings, + ], vram_need=vram_need, host_ram_need=host_ram_need, repos_named=repos_named, @@ -645,8 +663,87 @@ def rerun( note=spec.get("note"), rerun_of=job_id, overrides=overrides, + # The original's requests-ledger link, kept whatever the ledger + # says now (a warning, never a refusal) + request=spec.get("request"), + item=spec.get("item"), ) + def _link_warnings(self, spec): + """The warning a rerun carries when the ledger link it inherits no + longer admits a job: the request closed or gone, the item dropped + or gone. The rerun runs and keeps the link regardless.""" + request, item = spec.get("request"), spec.get("item") + if not (request and item) or self.ledger_root_for is None: + return [] + try: + root = self.ledger_root_for(spec.get("workspace") or DEFAULT_WORKSPACE_NAME) + problem = ledger.link_problem(root, request, item) + except Exception: + return [] + if problem is None: + return [] + return [f"rerun_ledger_link_{problem.code}: {problem}"] + + def request_jobs(self, workspace, request_id): + """Every job linked to `request_id` in `workspace`, live queue and + history, oldest first, as `{job, item, status, run_id, run_dir, + run_exists, started_at, finished_at, created_at, note}`. + + `run_exists` is whether the job's run directory is still on disk - + the directory `delete_job_run` removes. One indexed history query.""" + found = {} + for row in self.history.request_jobs(workspace, request_id): + found[row["id"]] = self._linked( + row["id"], row, row["run_dir"], row["output_dir"] + ) + with self._lock: + live = [ + job + for job in self.jobs.values() + if job.request == request_id + and (job.spec.get("workspace") or DEFAULT_WORKSPACE_NAME) == workspace + ] + for job in live: + found[job.id] = self._linked( + job.id, + { + "item": job.item, + "status": job.status, + "run_id": job.run_id, + "note": job.note, + "created_at": job.created_at, + "started_at": job.started_at, + "finished_at": job.finished_at, + }, + job.run_dir, + job.spec.get("output_dir"), + ) + return sorted(found.values(), key=lambda entry: entry["created_at"] or 0) + + def _linked(self, job_id, row, run_dir, output_dir): + exists = False + if run_dir: + try: + root = validate_output_path(output_dir or self.output_dir, None) + exists = os.path.isdir( + validate_path(os.path.join(root, run_dir), root, allow_create=True) + ) + except SecurityError: + exists = False + return { + "job": job_id, + "item": row["item"], + "status": row["status"], + "run_id": row["run_id"], + "run_dir": run_dir, + "run_exists": exists, + "started_at": row["started_at"], + "finished_at": row["finished_at"], + "created_at": row["created_at"], + "note": row["note"], + } + def rerun_restart_batch(self, job_id, admit, *, queue): """Rerun every tombstone the dead server that left `job_id` left (#1266), oldest first - or None when `job_id` is not a restart @@ -752,15 +849,17 @@ def describe(self, job): detail["queue_position"] = position return detail - def list(self, workspace=None, statuses=None): + def list(self, workspace=None, statuses=None, request=None, item=None): """All jobs, live and historical, sorted by creation. `workspace` filters to one workspace; omitted, the list spans every workspace the server holds, unchanged from before workspaces existed. `statuses` filters to a set of job states ('queued', 'running', 'succeeded', 'failed', 'cancelled'); omitted, every state is listed.""" - return self.list_page(workspace, statuses)[0] + return self.list_page(workspace, statuses, request=request, item=item)[0] - def list_page(self, workspace=None, statuses=None, limit=None): + def list_page( + self, workspace=None, statuses=None, limit=None, request=None, item=None + ): """`list`'s jobs cut to the newest `limit` (every one when None), and how many matched before the cut. Each run's current note is read after the cut, so a small page does not read the notes of @@ -777,6 +876,11 @@ def list_page(self, workspace=None, statuses=None, limit=None): continue if statuses and summary["status"] not in statuses: continue + # `request`/`item` filter in SQL for history, here for the live + if request and summary.get("request") != request: + continue + if item and summary.get("item") != item: + continue if job.id in positions: summary["queue_position"] = positions[job.id] output_dir = job.spec.get("output_dir") @@ -787,12 +891,18 @@ def list_page(self, workspace=None, statuses=None, limit=None): live_count = len(summaries) history_limit = None if limit is None else limit + len(live_ids) history_total = self.history.count_summaries( - workspace=workspace, statuses=statuses, exclude_ids=live_ids + workspace=workspace, + statuses=statuses, + exclude_ids=live_ids, + request=request, + item=item, ) for historical in self.history.recent_summaries( limit=history_limit if history_limit is not None else -1, workspace=workspace, statuses=statuses, + request=request, + item=item, ): run_dir = historical.pop("_run_dir", None) output_dir = historical.pop("_output_dir", None) diff --git a/dw/server/routes/gallery.py b/dw/server/routes/gallery.py index 4a9bc15ab..779e2bc1e 100644 --- a/dw/server/routes/gallery.py +++ b/dw/server/routes/gallery.py @@ -32,7 +32,12 @@ record_run_versions, split_run_path, ) -from ...security import SecurityError, validate_path +from ...security import ( + InvalidInputError, + SecurityError, + validate_ledger_key, + validate_path, +) from ...workspace import Workspace, forget_workspace_usage from ..deps import selected_workspace from ..outputs import ( @@ -186,6 +191,12 @@ def gallery( version: Optional[int] = None, media: bool = False, role: Optional[list[str]] = Query(None), + request_id: Optional[str] = Query( + default=None, + alias="request", + description="Only the files of runs whose job is linked to this " + "requests-ledger request in this workspace", + ), ws: Workspace = Depends(selected_workspace), ): """A page of media files in the output directory, newest first. @@ -235,6 +246,11 @@ def gallery( status_code=400, detail=f"unknown role {unknown}; roles are {list(ROLES)}", ) + if request_id: + try: + validate_ledger_key(request_id, "request") + except InvalidInputError as e: + raise HTTPException(status_code=422, detail=str(e)) if only_orphans: entries = _orphan_entries(ws.outputs) offset = max(0, offset) @@ -264,6 +280,13 @@ def gallery( if role: wanted = set(role) entries = [e for e in entries if (e.get("role") or "final") in wanted] + if request_id: + # A run belongs to the request its job was linked to; the history's + # run_id column is the map from one to the other + runs = request.app.state.job_manager.history.run_ids_for_request( + ws.name, request_id + ) + entries = [e for e in entries if e["run_id"] in runs] offset = max(0, offset) limit = max(0, limit) page = entries[offset : offset + limit] diff --git a/dw/server/routes/jobs.py b/dw/server/routes/jobs.py index 6d4cc91cf..4357cd38a 100644 --- a/dw/server/routes/jobs.py +++ b/dw/server/routes/jobs.py @@ -30,12 +30,18 @@ RunDeleted, ValidationResult, ) +from ... import ledger from ...events import select_kinds from ...host_memory_projection import CEILING_FRACTION, host_memory_warnings from ...plan import build_plan, gate_warnings, missing_repo_errors from ...presets import apply_presets from ...schema import format_validation_errors -from ...security import SecurityError, validate_path +from ...security import ( + InvalidInputError, + SecurityError, + validate_ledger_key, + validate_path, +) from ...variables import set_variables from ...library import SubWorkflowNotFound, resolve_sub_workflow_reference from ...workspace import Workspace @@ -129,6 +135,15 @@ def submit_job( note = admitted_note(request.note) try: workspace = workspace_for(state, request.workspace or ws.name) + if request.request: + # Before anything queues: a job links only to an open request's + # live item in its own workspace. A rerun's inherited link is + # not held to this (JobManager.rerun warns instead) + problem = ledger.link_problem( + workspace.root or None, request.request, request.item + ) + if problem is not None: + raise HTTPException(status_code=problem.status, detail=problem.detail()) resolved, source = resolve_workflow_reference( request.workflow_path, sources_for(state, workspace) ) @@ -215,6 +230,8 @@ def submit_job( host_ram_need=admission.host_ram_need, repos_named=admission.repos_named, note=note, + request=request.request, + item=request.item, ) return manager.describe(job) except HTTPException: @@ -229,6 +246,15 @@ def list_jobs( workspace: Optional[str] = None, status: Optional[str] = None, limit: Optional[int] = None, + request_id: Optional[str] = Query( + default=None, + alias="request", + description="Only the jobs linked to this requests-ledger request", + ), + item: Optional[str] = Query( + default=None, + description="With `request`: only the jobs linked to this item of it", + ), ): """All jobs by default - a plain filter, not `selected_workspace`, since the jobs list spans every workspace the server holds unless a @@ -240,6 +266,14 @@ def list_jobs( complete one. The default is still every matching job, oldest first - what the web UI polls.""" manager = request.app.state.job_manager + if item and not request_id: + raise HTTPException(status_code=422, detail="item needs request") + for value, what in ((request_id, "request"), (item, "item")): + if value: + try: + validate_ledger_key(value, what) + except InvalidInputError as e: + raise HTTPException(status_code=422, detail=str(e)) if workspace: # A name that was never a workspace is a typo, not "no jobs here" workspace_for(request.app.state, workspace) @@ -259,7 +293,13 @@ def list_jobs( ) if limit is not None and limit < 0: raise HTTPException(status_code=400, detail="limit must not be negative") - jobs, total = manager.list_page(workspace=workspace, statuses=statuses, limit=limit) + jobs, total = manager.list_page( + workspace=workspace, + statuses=statuses, + limit=limit, + request=request_id, + item=item, + ) return {"jobs": jobs, "total": total} diff --git a/dw/server/routes/library.py b/dw/server/routes/library.py index 94ab0c5d0..d65921919 100644 --- a/dw/server/routes/library.py +++ b/dw/server/routes/library.py @@ -960,6 +960,27 @@ class RequestWrite(BaseModel): ) +def _jobs_for(request, name): + """`rid -> the jobs linked to that request`, for the derived item state.""" + manager = request.app.state.job_manager + return lambda rid: manager.request_jobs(name, rid) + + +def _linked_jobs_for(request, name): + """`(rid, item key) -> [{job, status, run_id}]`: what `accepted` is + checked against.""" + jobs_for = _jobs_for(request, name) + + def linked(rid, key): + return [ + {"job": j["job"], "status": j["status"], "run_id": j["run_id"]} + for j in jobs_for(rid) + if j["item"] == key + ] + + return linked + + def _ledger_root(state, name): """The workspace root whose requests.json a request names, or None for a default workspace with no root folder. Raises 400/404/409 as @@ -983,7 +1004,10 @@ def _ledger_root(state, name): def list_requests(request: Request, name: str): """A workspace's requests, newest change first, without their items.""" root = _ledger_root(request.app.state, name) - return {"workspace": name, "requests": ledger.list_requests(root)} + return { + "workspace": name, + "requests": ledger.list_requests(root, _jobs_for(request, name)), + } @router.get( @@ -996,7 +1020,7 @@ def get_request(request: Request, name: str, request_id: str): history.""" root = _ledger_root(request.app.state, name) try: - found = ledger.get_request(root, request_id) + found = ledger.get_request(root, request_id, _jobs_for(request, name)) except SecurityError as e: raise HTTPException(status_code=400, detail=str(e)) if found is None: @@ -1020,7 +1044,14 @@ def put_request(request: Request, name: str, request_id: str, body: RequestWrite root = _ledger_root(request.app.state, name) payload = body.model_dump(exclude={"by"}) try: - return ledger.put_request(root, request_id, payload, by=body.by) + return ledger.put_request( + root, + request_id, + payload, + by=body.by, + linked_jobs=_linked_jobs_for(request, name), + jobs_for=_jobs_for(request, name), + ) except ledger.LedgerError as e: raise HTTPException(status_code=e.status, detail=e.detail()) except OSError: diff --git a/tests/test_job_history_parity.py b/tests/test_job_history_parity.py index c39898dcb..52ecbbcc0 100644 --- a/tests/test_job_history_parity.py +++ b/tests/test_job_history_parity.py @@ -44,8 +44,9 @@ def _job(**extra): {}, {"note": "a test", "rerun_of": "abc123def456"}, {"rerun_of": "abc123def456", "overrides": {"steps": 4}}, + {"request": "cats", "item": "shot-1"}, ], - ids=["optional-unset", "optional-set", "overrides-set"], + ids=["optional-unset", "optional-set", "overrides-set", "ledger-link-set"], ) def test_history_serves_the_keys_a_live_job_does(tmp_path, extra): job = _job(**extra) diff --git a/tests/test_ledger_job_link.py b/tests/test_ledger_job_link.py new file mode 100644 index 000000000..920c51b16 --- /dev/null +++ b/tests/test_ledger_job_link.py @@ -0,0 +1,582 @@ +"""A job linked to a requests-ledger request and item (#1482): admission, +the record, history, rerun inheritance, exports, filters and the derived +item state.""" + +import json +import os +import shutil +import sqlite3 +import zipfile # noqa: F401 - kept with the export helpers' imports + +import pytest +from fastapi.testclient import TestClient + +from dw import ledger +from dw.runs import new_run_id +from dw.server.app import create_app +from dw.server.job_record import TERMINAL_STATES +from dw.server.jobs import JobManager +from dw.workspace import Workspace + +from .test_ledger import item, plan +from .test_server import ( + ScriptedWorkerManager, + admitted_for, + valid_workflow, + wait_for_status, +) + +WS = "default" + + +def run_id_for(job_script_name): + return new_run_id({"workflow": job_script_name}) + + +class Scripts: + """A worker script that finishes with one file in a fresh run directory, + or fails, by the prompt the job was given.""" + + def __init__(self): + self.count = 0 + self.fail_next = False + + def __call__(self, command): + self.count += 1 + if self.fail_next: + self.fail_next = False + yield {"type": "error", "message": "boom"} + return + output_dir = command["output_dir"] + rid = run_id_for(f"link{self.count}") + rel = f"server_test/{rid}" + run_dir = os.path.join(output_dir, "server_test", rid) + os.makedirs(run_dir, exist_ok=True) + with open(os.path.join(run_dir, "still.png"), "wb") as file: + file.write(b"an image") + with open(os.path.join(run_dir, "manifest.json"), "w") as file: + json.dump( + { + "run_id": rid, + "version": 4, + "status": "completed", + "workflow": {"identity": "server_test"}, + "steps": [{"step": "gen", "files": ["still.png"]}], + }, + file, + ) + yield { + "type": "progress", + "event": "run_start", + "run_id": rid, + "version": 4, + "identity": "server_test", + "run_dir": rel, + } + yield { + "type": "success", + "message": "ok", + "run_count": 1, + "manifest": [ + {"step": "gen", "files": [os.path.join(run_dir, "still.png")]} + ], + } + + +@pytest.fixture +def root(tmp_path): + return Workspace(tmp_path / "studio", "flag").ensure() + + +@pytest.fixture +def client(root, tmp_path): + script = Scripts() + manager = JobManager( + root.outputs, + worker_manager=ScriptedWorkerManager(script), + history_path=str(tmp_path / "jobs.sqlite"), + workflow_dir=root.workflows, + ) + app = create_app( + workflow_dir=root.workflows, + output_dir=root.outputs, + job_manager=manager, + prompt_dir=root.prompts, + asset_dir=root.assets, + workspace=root.root, + ) + c = TestClient(app, base_url="http://localhost") + c.manager = manager + c.script = script + c.root = root + return c + + +def write_plan(client, request_id="cats", revision=0, items=None, **fields): + body = plan(revision=revision, items=items, **fields) + body["by"] = "agent" + r = client.put(f"/api/workspaces/{WS}/requests/{request_id}", json=body) + assert r.status_code == 200, r.text + return r.json() + + +def view(client, request_id="cats"): + r = client.get(f"/api/workspaces/{WS}/requests/{request_id}") + assert r.status_code == 200, r.text + return r.json() + + +def items_of(client, request_id="cats"): + return {i["key"]: i for i in view(client, request_id)["items"]} + + +def submit(client, prompt="hi", request="cats", item_key="a", expect=201, **extra): + body = {"workflow": valid_workflow(), "arguments": {"prompt": prompt}} + if request is not None: + body["request"] = request + if item_key is not None: + body["item"] = item_key + body.update(extra) + r = client.post("/api/jobs", json=body) + assert r.status_code == expect, r.text + return r.json() + + +def finish(client, job): + return wait_for_status(client, job["id"], TERMINAL_STATES) + + +@pytest.fixture +def planned(client): + write_plan(client) + return client + + +# --- admission ------------------------------------------------------------ + + +class TestAdmission: + def test_a_linked_submit_carries_both_through_to_history(self, planned): + job = submit(planned) + assert job["request"] == "cats" and job["item"] == "a" + done = finish(planned, job) + assert done["request"] == "cats" and done["item"] == "a" + planned.manager.jobs.pop(job["id"]) + again = planned.get(f"/api/jobs/{job['id']}").json() + assert again["request"] == "cats" and again["item"] == "a" + + def test_an_unlinked_job_has_neither_key(self, planned): + job = submit(planned, request=None, item_key=None) + assert "request" not in job and "item" not in job + + def test_the_unknown_request(self, planned): + r = planned.post( + "/api/jobs", + json={"workflow": valid_workflow(), "request": "nope", "item": "a"}, + ) + assert r.status_code == 422 + assert r.json()["detail"]["code"] == "unknown_request" + assert planned.manager.jobs == {} + + def test_the_unknown_item(self, planned): + r = planned.post( + "/api/jobs", + json={"workflow": valid_workflow(), "request": "cats", "item": "zzz"}, + ) + assert r.status_code == 422 + assert r.json()["detail"]["code"] == "unknown_item" + assert planned.manager.jobs == {} + + def test_a_closed_request(self, planned): + write_plan(planned, revision=1, state="done") + r = planned.post( + "/api/jobs", + json={"workflow": valid_workflow(), "request": "cats", "item": "a"}, + ) + assert r.status_code == 422 + assert r.json()["detail"]["code"] == "request_closed" + assert planned.manager.jobs == {} + + def test_a_dropped_item(self, planned): + write_plan(planned, revision=1, items=[item("a")]) + submit(planned, item_key="a") + write_plan(planned, revision=2, items=[item("b")]) + assert items_of(planned)["a"]["status"] == "dropped" + r = planned.post( + "/api/jobs", + json={"workflow": valid_workflow(), "request": "cats", "item": "a"}, + ) + assert r.status_code == 422 + assert r.json()["detail"]["code"] == "item_dropped" + + def test_an_item_without_a_request_is_refused(self, planned): + r = planned.post("/api/jobs", json={"workflow": valid_workflow(), "item": "a"}) + assert r.status_code == 422 + + def test_a_request_without_an_item_is_refused(self, planned): + r = planned.post( + "/api/jobs", json={"workflow": valid_workflow(), "request": "cats"} + ) + assert r.status_code == 422 + + def test_a_bad_key_is_refused(self, planned): + r = planned.post( + "/api/jobs", + json={"workflow": valid_workflow(), "request": "Demo", "item": "a"}, + ) + assert r.status_code == 422 + assert planned.manager.jobs == {} + + +# --- reruns --------------------------------------------------------------- + + +class TestRerun: + def test_a_single_rerun_inherits_the_link(self, planned): + job = submit(planned) + finish(planned, job) + r = planned.post(f"/api/jobs/{job['id']}/rerun", json={}) + assert r.status_code == 201, r.text + rerun = r.json() + assert rerun["request"] == "cats" and rerun["item"] == "a" + assert not any("rerun_ledger_link" in w for w in rerun.get("warnings", [])) + + def test_a_rerun_into_a_closed_request_runs_with_a_warning(self, planned): + job = submit(planned) + finish(planned, job) + write_plan(planned, revision=1, state="done") + r = planned.post(f"/api/jobs/{job['id']}/rerun", json={}) + assert r.status_code == 201, r.text + rerun = r.json() + assert rerun["request"] == "cats" and rerun["item"] == "a" + assert any( + w.startswith("rerun_ledger_link_request_closed") for w in rerun["warnings"] + ) + + def test_a_rerun_into_a_dropped_item_runs_with_a_warning(self, planned): + job = submit(planned) + finish(planned, job) + write_plan(planned, revision=1, items=[item("b")]) + r = planned.post(f"/api/jobs/{job['id']}/rerun", json={}) + assert r.status_code == 201, r.text + rerun = r.json() + assert rerun["item"] == "a" + assert any( + w.startswith("rerun_ledger_link_item_dropped") for w in rerun["warnings"] + ) + + def test_a_restart_batch_rerun_inherits_the_link(self, planned, tmp_path): + # A server that died with a linked job open: its tombstone's batch + # is rerun by a fresh server over the same history + from .test_restart_tombstones import ( + StuckWorkerManager, + kill, + stuck_script, + wait_until, + ) + + root = planned.root + dead = JobManager( + root.outputs, + worker_manager=StuckWorkerManager(stuck_script), + history_path=str(tmp_path / "jobs.sqlite"), + workflow_dir=root.workflows, + ) + wf = valid_workflow() + spec_job = dead.submit( + admitted=admitted_for(dead, wf), + workflow=wf, + arguments={"prompt": "x"}, + base_dir=root.workflows, + workflow_dir=root.workflows, + request="cats", + item="a", + ) + wait_until(lambda: spec_job.run_dir is not None) + kill(dead) + + manager = JobManager( + root.outputs, + worker_manager=ScriptedWorkerManager(Scripts()), + history_path=str(tmp_path / "jobs.sqlite"), + workflow_dir=root.workflows, + ) + app = create_app( + workflow_dir=root.workflows, + output_dir=root.outputs, + job_manager=manager, + prompt_dir=root.prompts, + asset_dir=root.assets, + workspace=root.root, + ) + c = TestClient(app, base_url="http://localhost") + try: + r = c.post( + f"/api/jobs/{spec_job.id}/rerun-restart-batch", + json={"acknowledged_cost": True}, + ) + assert r.status_code == 200, r.text + queued = r.json()["queued"] + assert len(queued) == 1 + made = manager.jobs[queued[0]["id"]] + assert (made.request, made.item) == ("cats", "a") + finally: + manager.shutdown() + + +# --- history -------------------------------------------------------------- + + +class TestHistory: + def test_forget_workspace_keeps_the_strings(self, planned, tmp_path): + job = submit(planned) + finish(planned, job) + history = planned.manager.history + history.forget_workspace(WS) + con = sqlite3.connect(tmp_path / "jobs.sqlite") + try: + rows = con.execute( + "SELECT request, item FROM jobs WHERE id = ?", (job["id"],) + ).fetchall() + finally: + con.close() + assert rows == [("cats", "a")] + + +# --- exports -------------------------------------------------------------- + + +def test_an_exported_job_json_carries_both(planned): + job = submit(planned) + finish(planned, job) + r = planned.post(f"/api/jobs/{job['id']}/export") + assert r.status_code == 201, r.text + directory = r.json()["directory"] + path = os.path.join(directory, "job.json") + if not os.path.isabs(path): + path = os.path.join(planned.root.root, path) + with open(path) as file: + record = json.load(file) + assert record["request"] == "cats" and record["item"] == "a" + + +# --- filters -------------------------------------------------------------- + + +class TestFilters: + def test_the_job_list_filters_by_request_and_item(self, planned): + write_plan(planned, revision=1, items=[item("a"), item("b")]) + write_plan(planned, request_id="dogs") + a = submit(planned, item_key="a") + b = submit(planned, item_key="b") + d = submit(planned, request="dogs", item_key="a") + loose = submit(planned, request=None, item_key=None) + for j in (a, b, d, loose): + finish(planned, j) + + def ids(query): + r = planned.get(f"/api/jobs?{query}") + assert r.status_code == 200, r.text + return {j["id"] for j in r.json()["jobs"]} + + assert ids("request=cats") == {a["id"], b["id"]} + assert ids("request=cats&item=b") == {b["id"]} + assert ids("request=dogs") == {d["id"]} + + def test_item_without_request_is_422(self, planned): + assert planned.get("/api/jobs?item=a").status_code == 422 + + def test_a_bad_key_in_the_filter_is_422(self, planned): + assert planned.get("/api/jobs?request=Demo").status_code == 422 + + def test_the_gallery_filters_by_request(self, planned): + write_plan(planned, request_id="dogs") + a = submit(planned) + d = submit(planned, request="dogs", item_key="a") + loose = submit(planned, request=None, item_key=None) + done = {j["id"]: finish(planned, j) for j in (a, d, loose)} + r = planned.get("/api/gallery") + assert r.status_code == 200, r.text + assert r.json()["total"] >= 3 + r = planned.get("/api/gallery?request=cats") + assert r.status_code == 200, r.text + entries = r.json()["files"] + assert len(entries) == 1 + assert ( + entries[0]["run_id"] == planned.manager.get(a["id"]).run_dir.split("/")[-1] + ) + assert done + assert planned.get("/api/gallery?request=Demo").status_code == 422 + + +# --- derived state -------------------------------------------------------- + + +class TestDerivedState: + def test_a_planned_item_has_no_attempts(self, planned): + a = items_of(planned)["a"] + assert a["status"] == "planned" + assert a["attempts"] == [] and a["result"] is None + assert a["spent_minutes"] == 0 + assert "accepted_missing" not in a + + def test_the_latest_succeeded_job_is_the_result_until_one_is_accepted( + self, planned + ): + first = finish(planned, submit(planned)) + second = finish(planned, submit(planned)) + a = items_of(planned)["a"] + assert a["status"] == "done" + assert [x["job"] for x in a["attempts"]] == [first["id"], second["id"]] + assert a["result"]["job"] == second["id"] + + body = view(planned) + body["items"][0]["accepted"] = {"job": first["id"]} + r = planned.put( + f"/api/workspaces/{WS}/requests/cats", + json={k: body[k] for k in ("title", "goal", "items", "revision")} + | {"why": "pick the first", "by": "user"}, + ) + assert r.status_code == 200, r.text + assert {i["key"]: i for i in r.json()["items"]}["a"]["result"]["job"] == first[ + "id" + ] + + def test_accepted_as_a_bare_job_id_is_taken(self, planned): + first = finish(planned, submit(planned)) + finish(planned, submit(planned)) + body = view(planned) + body["items"][0]["accepted"] = first["id"] + r = planned.put( + f"/api/workspaces/{WS}/requests/cats", + json={k: body[k] for k in ("title", "goal", "items", "revision")} + | {"why": "pick", "by": "user"}, + ) + assert r.status_code == 200, r.text + assert items_of(planned)["a"]["result"]["job"] == first["id"] + + def _accept(self, client, job_id, key="a"): + body = view(client) + for i in body["items"]: + if i["key"] == key: + i["accepted"] = {"job": job_id} + return client.put( + f"/api/workspaces/{WS}/requests/cats", + json={k: body[k] for k in ("title", "goal", "items", "revision")} + | {"why": "pick", "by": "user"}, + ) + + def test_accepted_on_a_job_of_another_item_is_refused(self, planned): + other = finish(planned, submit(planned, item_key="b")) + r = self._accept(planned, other["id"], key="a") + assert r.status_code in (400, 422), r.text + assert "not linked" in json.dumps(r.json()) + + def test_accepted_on_a_job_of_another_request_is_refused(self, planned): + write_plan(planned, request_id="dogs") + other = finish(planned, submit(planned, request="dogs", item_key="a")) + r = self._accept(planned, other["id"]) + assert r.status_code in (400, 422), r.text + + def test_accepted_on_a_failed_job_is_refused(self, planned): + planned.script.fail_next = True + failed = finish(planned, submit(planned)) + assert failed["status"] == "failed" + assert items_of(planned)["a"]["status"] == "failed" + r = self._accept(planned, failed["id"]) + assert r.status_code in (400, 422), r.text + assert "not succeeded" in json.dumps(r.json()) + + def test_accepted_missing_when_the_accepted_run_is_deleted(self, planned): + first = finish(planned, submit(planned)) + second = finish(planned, submit(planned)) + assert self._accept(planned, first["id"]).status_code == 200 + run_dir = planned.manager.get(first["id"]).run_dir + shutil.rmtree(os.path.join(planned.root.outputs, run_dir)) + a = items_of(planned)["a"] + assert a["accepted_missing"] is True + assert a["result"]["job"] == second["id"] + assert a["status"] == "done" + + def test_status_order(self): + def job(status, key="a", **kw): + return { + "job": status, + "item": key, + "status": status, + "run_exists": True, + **kw, + } + + def status_of(jobs, **item_fields): + req = {"items": [{"key": "a", **item_fields}]} + return ledger.request_view(req, jobs)["items"][0]["status"] + + assert status_of([]) == "planned" + assert status_of([job("failed"), job("cancelled")]) == "failed" + assert status_of([job("failed"), job("queued")]) == "queued" + assert status_of([job("queued"), job("running")]) == "running" + assert status_of([job("running"), job("succeeded")]) == "done" + assert status_of([job("succeeded")], dropped=True) == "dropped" + + def test_spent_and_remaining(self): + req = { + "items": [ + {"key": "a", "estimate_minutes": 10}, + {"key": "b", "estimate_minutes": 5}, + {"key": "c", "estimate_minutes": 7}, + {"key": "d", "estimate_minutes": 3, "dropped": True}, + ] + } + jobs = [ + { + "job": "j1", + "item": "a", + "status": "succeeded", + "run_exists": True, + "started_at": 100, + "finished_at": 220, + }, + { + "job": "j2", + "item": "b", + "status": "failed", + "started_at": 300, + "finished_at": 330, + }, + {"job": "j3", "item": "b", "status": "queued"}, + ] + view_ = ledger.request_view(req, jobs) + assert view_["spent_minutes"] == 2.5 + assert view_["remaining_minutes"] == 12 + by_key = {i["key"]: i for i in view_["items"]} + assert by_key["a"]["spent_minutes"] == 2 + assert by_key["b"]["spent_minutes"] == 0.5 + assert by_key["b"]["attempts"][1]["minutes"] is None + summary = ledger.summary_view({"id": "r", **req}, jobs) + assert summary["spent_minutes"] == 2.5 + assert summary["remaining_minutes"] == 12 + + def test_the_request_view_and_list_carry_the_totals(self, planned): + finish(planned, submit(planned)) + body = view(planned) + assert "spent_minutes" in body and "remaining_minutes" in body + listed = planned.get(f"/api/workspaces/{WS}/requests").json()["requests"] + assert listed[0]["spent_minutes"] >= 0 + assert listed[0]["status_counts"].get("done") == 1 + + +# --- one real-HTTP walk --------------------------------------------------- + + +def test_submit_then_history_then_request_view(planned): + job = submit(planned, note="the first take") + finish(planned, job) + listed = planned.get("/api/jobs?request=cats").json()["jobs"] + assert [j["id"] for j in listed] == [job["id"]] + a = items_of(planned)["a"] + assert a["status"] == "done" + assert a["attempts"][0]["job"] == job["id"] + assert a["attempts"][0]["note"] == "the first take" + assert a["result"]["job"] == job["id"] + assert items_of(planned)["b"]["status"] == "planned" diff --git a/ui/src/lib/generated/api-schema.ts b/ui/src/lib/generated/api-schema.ts index decbc75c8..b0c6d0101 100644 --- a/ui/src/lib/generated/api-schema.ts +++ b/ui/src/lib/generated/api-schema.ts @@ -2677,6 +2677,11 @@ export interface components { host_memory_job_peak_committed_mb?: number | null; /** Id */ id: string; + /** + * Item + * @description The item of `request` this job serves; absent when unlinked. + */ + item?: string; /** * Manifest * @description Null on a history row recorded before manifests, or by a run that wrote none. @@ -2713,6 +2718,11 @@ export interface components { * @description Why the job ended: the first line of its `error`, clipped to 160 characters with a trailing '…'. Only on a failed or cancelled job that has an error - a plain user cancel has none. The full error, traceback and all, is on the job's detail. */ reason?: string; + /** + * Request + * @description The requests-ledger request this job serves; absent when unlinked. + */ + request?: string; /** * Rerun Of * @description The job this one reran; absent for a job submitted fresh. @@ -2878,11 +2888,21 @@ export interface components { * @description Directory relative paths in an inline workflow resolve against */ base_dir?: string | null; + /** + * Item + * @description The item key of `request` this job serves; both or neither + */ + item?: string | null; /** * Note * @description A note on the run, at most 4000 characters: kept with the job and written as the run note when the run opens */ note?: string | null; + /** + * Request + * @description The requests-ledger request this job serves (with `item`): an open request in the job's workspace. Refused with 422 and a `{code, message}` detail - unknown_request, request_closed, unknown_item or item_dropped - before anything queues + */ + request?: string | null; /** * Workflow * @description Inline workflow definition @@ -2930,6 +2950,11 @@ export interface components { historical?: boolean; /** Id */ id: string; + /** + * Item + * @description The item of `request` this job serves; absent when unlinked. + */ + item?: string; /** * Note * @description The note it was submitted with; also its run's note. @@ -2952,6 +2977,11 @@ export interface components { * @description Why the job ended: the first line of its `error`, clipped to 160 characters with a trailing '…'. Only on a failed or cancelled job that has an error - a plain user cancel has none. The full error, traceback and all, is on the job's detail. */ reason?: string; + /** + * Request + * @description The requests-ledger request this job serves; absent when unlinked. + */ + request?: string; /** * Rerun Of * @description The job this one reran; absent for a job submitted fresh. @@ -3074,6 +3104,26 @@ export interface components { /** Run Id */ run_id: string | null; }; + /** LedgerAttempt */ + LedgerAttempt: { + /** Job */ + job: string; + /** + * Minutes + * @description Run time; null until the job has started. + */ + minutes: number | null; + /** + * Note + * @description The job's note. + */ + note?: string; + /** + * Status + * @enum {string} + */ + status: "queued" | "running" | "succeeded" | "failed" | "cancelled"; + }; /** LedgerComment */ LedgerComment: { /** At */ @@ -3103,10 +3153,20 @@ export interface components { /** LedgerItem */ LedgerItem: { accepted: components["schemas"]["LedgerAccepted"] | null; + /** + * Accepted Missing + * @description True when an accepted job's run directory is gone; `result` then falls back to the latest succeeded attempt. + */ + accepted_missing?: boolean; /** Arguments */ arguments: { [key: string]: unknown; }; + /** + * Attempts + * @description Every linked job, oldest first. + */ + attempts: components["schemas"]["LedgerAttempt"][]; /** @description The user's; an agent never writes it. */ comment: components["schemas"]["LedgerComment"] | null; /** Depends On */ @@ -3117,12 +3177,19 @@ export interface components { estimate_minutes: number | null; /** Key */ key: string; + /** @description The accepted job's run, else the latest succeeded job's run whose directory still exists; null when neither. */ + result: components["schemas"]["LedgerResult"] | null; + /** + * Spent Minutes + * @description Minutes the item's linked jobs ran, summed. + */ + spent_minutes: number; /** * Status - * @description Derived from the item's jobs; none link yet, so planned or dropped. + * @description Derived from the item's linked jobs, first that holds: dropped, done (a result exists), running, queued, failed (every linked job failed or was cancelled), planned. * @enum {string} */ - status: "planned" | "dropped"; + status: "dropped" | "done" | "running" | "queued" | "failed" | "planned"; /** Title */ title: string; /** Workflow */ @@ -3150,8 +3217,18 @@ export interface components { * @description The ask that started it; write-once. */ prompt: string | null; + /** + * Remaining Minutes + * @description Estimates of the items not done and not dropped. + */ + remaining_minutes: number; /** Revision */ revision: number; + /** + * Spent Minutes + * @description Minutes every linked job ran. + */ + spent_minutes: number; /** * State * @enum {string} @@ -3160,14 +3237,25 @@ export interface components { /** Title */ title: string; }; + /** LedgerResult */ + LedgerResult: { + /** Job */ + job: string; + /** Run Id */ + run_id: string | null; + }; /** LedgerSummary */ LedgerSummary: { /** Id */ id: string; /** Items */ items: number; + /** Remaining Minutes */ + remaining_minutes: number; /** Revision */ revision: number; + /** Spent Minutes */ + spent_minutes: number; /** * State * @enum {string} @@ -5063,6 +5151,8 @@ export interface operations { version?: number | null; media?: boolean; role?: string[] | null; + /** @description Only the files of runs whose job is linked to this requests-ledger request in this workspace */ + request?: string | null; workspace?: string | null; }; header?: never; @@ -5523,6 +5613,10 @@ export interface operations { workspace?: string | null; status?: string | null; limit?: number | null; + /** @description Only the jobs linked to this requests-ledger request */ + request?: string | null; + /** @description With `request`: only the jobs linked to this item of it */ + item?: string | null; }; header?: never; path?: never; diff --git a/ui/src/lib/generated/openapi.json b/ui/src/lib/generated/openapi.json index 3956354e2..794c6ee02 100644 --- a/ui/src/lib/generated/openapi.json +++ b/ui/src/lib/generated/openapi.json @@ -1780,6 +1780,11 @@ "title": "Id", "type": "string" }, + "item": { + "description": "The item of `request` this job serves; absent when unlinked.", + "title": "Item", + "type": "string" + }, "manifest": { "anyOf": [ { @@ -1848,6 +1853,11 @@ "title": "Reason", "type": "string" }, + "request": { + "description": "The requests-ledger request this job serves; absent when unlinked.", + "title": "Request", + "type": "string" + }, "rerun_of": { "description": "The job this one reran; absent for a job submitted fresh.", "title": "Rerun Of", @@ -2290,6 +2300,18 @@ "description": "Directory relative paths in an inline workflow resolve against", "title": "Base Dir" }, + "item": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The item key of `request` this job serves; both or neither", + "title": "Item" + }, "note": { "anyOf": [ { @@ -2302,6 +2324,18 @@ "description": "A note on the run, at most 4000 characters: kept with the job and written as the run note when the run opens", "title": "Note" }, + "request": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The requests-ledger request this job serves (with `item`): an open request in the job's workspace. Refused with 422 and a `{code, message}` detail - unknown_request, request_closed, unknown_item or item_dropped - before anything queues", + "title": "Request" + }, "workflow": { "anyOf": [ { @@ -2410,6 +2444,11 @@ "title": "Id", "type": "string" }, + "item": { + "description": "The item of `request` this job serves; absent when unlinked.", + "title": "Item", + "type": "string" + }, "note": { "description": "The note it was submitted with; also its run's note.", "title": "Note", @@ -2431,6 +2470,11 @@ "title": "Reason", "type": "string" }, + "request": { + "description": "The requests-ledger request this job serves; absent when unlinked.", + "title": "Request", + "type": "string" + }, "rerun_of": { "description": "The job this one reran; absent for a job submitted fresh.", "title": "Rerun Of", @@ -2695,6 +2739,53 @@ "title": "LedgerAccepted", "type": "object" }, + "LedgerAttempt": { + "additionalProperties": false, + "properties": { + "job": { + "title": "Job", + "type": "string" + }, + "minutes": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "number" + }, + { + "type": "null" + } + ], + "description": "Run time; null until the job has started.", + "title": "Minutes" + }, + "note": { + "description": "The job's note.", + "title": "Note", + "type": "string" + }, + "status": { + "enum": [ + "queued", + "running", + "succeeded", + "failed", + "cancelled" + ], + "title": "Status", + "type": "string" + } + }, + "required": [ + "job", + "status", + "minutes" + ], + "title": "LedgerAttempt", + "type": "object" + }, "LedgerComment": { "additionalProperties": false, "properties": { @@ -2772,11 +2863,24 @@ } ] }, + "accepted_missing": { + "description": "True when an accepted job's run directory is gone; `result` then falls back to the latest succeeded attempt.", + "title": "Accepted Missing", + "type": "boolean" + }, "arguments": { "additionalProperties": true, "title": "Arguments", "type": "object" }, + "attempts": { + "description": "Every linked job, oldest first.", + "items": { + "$ref": "#/components/schemas/LedgerAttempt" + }, + "title": "Attempts", + "type": "array" + }, "comment": { "anyOf": [ { @@ -2817,11 +2921,38 @@ "title": "Key", "type": "string" }, + "result": { + "anyOf": [ + { + "$ref": "#/components/schemas/LedgerResult" + }, + { + "type": "null" + } + ], + "description": "The accepted job's run, else the latest succeeded job's run whose directory still exists; null when neither." + }, + "spent_minutes": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "number" + } + ], + "description": "Minutes the item's linked jobs ran, summed.", + "title": "Spent Minutes" + }, "status": { - "description": "Derived from the item's jobs; none link yet, so planned or dropped.", + "description": "Derived from the item's linked jobs, first that holds: dropped, done (a result exists), running, queued, failed (every linked job failed or was cancelled), planned.", "enum": [ - "planned", - "dropped" + "dropped", + "done", + "running", + "queued", + "failed", + "planned" ], "title": "Status", "type": "string" @@ -2852,7 +2983,10 @@ "dropped", "accepted", "comment", - "status" + "status", + "attempts", + "result", + "spent_minutes" ], "title": "LedgerItem", "type": "object" @@ -2916,10 +3050,34 @@ "description": "The ask that started it; write-once.", "title": "Prompt" }, + "remaining_minutes": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "number" + } + ], + "description": "Estimates of the items not done and not dropped.", + "title": "Remaining Minutes" + }, "revision": { "title": "Revision", "type": "integer" }, + "spent_minutes": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "number" + } + ], + "description": "Minutes every linked job ran.", + "title": "Spent Minutes" + }, "state": { "enum": [ "open", @@ -2942,11 +3100,39 @@ "prompt", "goal", "items", - "history" + "history", + "spent_minutes", + "remaining_minutes" ], "title": "LedgerRequest", "type": "object" }, + "LedgerResult": { + "additionalProperties": false, + "properties": { + "job": { + "title": "Job", + "type": "string" + }, + "run_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Run Id" + } + }, + "required": [ + "job", + "run_id" + ], + "title": "LedgerResult", + "type": "object" + }, "LedgerSummary": { "additionalProperties": false, "properties": { @@ -2958,10 +3144,32 @@ "title": "Items", "type": "integer" }, + "remaining_minutes": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "number" + } + ], + "title": "Remaining Minutes" + }, "revision": { "title": "Revision", "type": "integer" }, + "spent_minutes": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "number" + } + ], + "title": "Spent Minutes" + }, "state": { "enum": [ "open", @@ -3001,6 +3209,8 @@ "revision", "items", "status_counts", + "spent_minutes", + "remaining_minutes", "updated_at" ], "title": "LedgerSummary", @@ -7209,6 +7419,24 @@ "title": "Role" } }, + { + "description": "Only the files of runs whose job is linked to this requests-ledger request in this workspace", + "in": "query", + "name": "request", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only the files of runs whose job is linked to this requests-ledger request in this workspace", + "title": "Request" + } + }, { "in": "query", "name": "workspace", @@ -8205,6 +8433,42 @@ ], "title": "Limit" } + }, + { + "description": "Only the jobs linked to this requests-ledger request", + "in": "query", + "name": "request", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only the jobs linked to this requests-ledger request", + "title": "Request" + } + }, + { + "description": "With `request`: only the jobs linked to this item of it", + "in": "query", + "name": "item", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "With `request`: only the jobs linked to this item of it", + "title": "Item" + } } ], "responses": { From 8d0056efb833682208ba18e0fc4b7c02ad0bd9b8 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 14:04:04 -0600 Subject: [PATCH 302/412] feat(mcp): #1482 - run_workflow takes request="/" to link a job to a ledger item Co-Authored-By: Claude Opus 5.5 --- dw_mcp/diagnose.py | 32 +++++++++++++++- dw_mcp/tools_jobs.py | 6 ++- tests/test_mcp_server.py | 81 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 117 insertions(+), 2 deletions(-) diff --git a/dw_mcp/diagnose.py b/dw_mcp/diagnose.py index f0be7fb5a..d81b452a4 100644 --- a/dw_mcp/diagnose.py +++ b/dw_mcp/diagnose.py @@ -10,6 +10,7 @@ import logging import math import os +import re import time from dw_mcp.client import DwApiError, api_path, clip_note, workflow_source @@ -86,6 +87,27 @@ def _acknowledgement_body(acknowledged_cost): return {"acknowledged_cost": bool(acknowledged_cost)} +# The ledger's key rule, copied because dw_mcp imports no dw module +# (dw.security.validate_ledger_key) +LEDGER_KEY = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}\Z") + + +def _ledger_link(request): + """`"/"` as the POST body's `request` and `item`, + or None for no link. Refused here, before any HTTP call, when it is not + that form.""" + if request is None or request == "": + return None + parts = request.split("/") if isinstance(request, str) else [] + if len(parts) != 2 or not all(LEDGER_KEY.match(part) for part in parts): + raise DwApiError( + f'`request` must be "/": exactly one ' + f"'/', each half 1-64 of a-z, 0-9 and dash, starting with a " + f"letter or digit (got {request!r})." + ) + return {"request": parts[0], "item": parts[1]} + + def run_workflow( client, workflow_path=None, @@ -97,6 +119,7 @@ def run_workflow( workspace=None, wait_seconds=0, note=None, + request=None, ): """Queue a workflow. `workflow_path` (or `name` - the same thing `validate_workflow` calls it) is either a catalog name from @@ -121,7 +144,12 @@ def run_workflow( `acknowledged_cost` is true or, better, the plan it was quoted from: {fingerprint, minutes, downloads} from `validate_workflow` - see COST_REFUSAL. A bound one the server checks; a 409 means the run's - shape changed since the quote and the message carries the new plan.""" + shape changed since the quote and the message carries the new plan. + + `request` is "/": the job is linked to that ledger + item (both keys meet the ledger's key rule). The server refuses a link + it cannot admit with a 422 naming the code.""" + ledger_link = _ledger_link(request) path, inline = workflow_source(name, workflow_path, workflow, inline_workflow) if not acknowledged_cost: raise DwApiError(COST_REFUSAL) @@ -135,6 +163,8 @@ def run_workflow( payload.update(_acknowledgement_body(acknowledged_cost)) if note: payload["note"] = note + if ledger_link: + payload.update(ledger_link) if path is not None: payload["workflow_path"] = path else: diff --git a/dw_mcp/tools_jobs.py b/dw_mcp/tools_jobs.py index cc2993d08..429bea332 100644 --- a/dw_mcp/tools_jobs.py +++ b/dw_mcp/tools_jobs.py @@ -22,6 +22,7 @@ def run_workflow( workspace: str | None = None, wait_seconds: int = 0, note: str | None = None, + request: str | None = None, ) -> dict: """Queue a workflow for generation. This costs GPU time: a run occupies a GPU for minutes and the engine runs one job per GPU. @@ -53,7 +54,9 @@ def run_workflow( that was null. `note`: what this run is for, shown on every file it writes - ('testing video_shift 5 against 3'). Give each variation its own.""" + ('testing video_shift 5 against 3'). Give each variation its own. + + `request`: "/" links the job to a ledger item.""" return diagnose.run_workflow( self.client, workflow_path=workflow_path, @@ -65,6 +68,7 @@ def run_workflow( workspace=workspace, wait_seconds=wait_seconds, note=note, + request=request, ) # The cap is a number a caller paces against, so the description diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index d3914f302..ead823532 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -1707,3 +1707,84 @@ async def test_the_tool_surface_fits_the_budget(): f"(descriptions {descriptions / 4:.0f}, schemas {schemas / 4:.0f}, " f"instructions {instructions / 4:.0f})" ) + + +@pytest.mark.asyncio +async def test_run_workflow_request_is_an_optional_nullable_string(): + tools = await tools_of(server_over(ok({}))) + run = tools["run_workflow"].input_schema + + assert "request" not in run.get("required", []) + assert run["properties"]["request"]["default"] is None + assert {"type": "string"} in run["properties"]["request"]["anyOf"] + assert {"type": "null"} in run["properties"]["request"]["anyOf"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("bad", ["demo", "a/b/c", "Demo/cat", "demo/", "/cat"]) +async def test_run_workflow_refuses_a_malformed_request_before_any_call(bad): + calls = [] + + def handler(request): + calls.append(request) + return httpx.Response(200, json={"id": "job-1"}) + + server = server_over(handler) + with pytest.raises(Exception) as caught: + await server.call_tool( + "run_workflow", + {"workflow_path": "w.json", "acknowledged_cost": True, "request": bad}, + ) + + assert "/" in str(caught.value) + assert calls == [] + + +@pytest.mark.asyncio +async def test_run_workflow_sends_the_request_and_item_split(): + sent = [] + + def handler(request): + sent.append(json.loads(request.content)) + return httpx.Response(200, json={"id": "job-1", "status": "queued"}) + + await server_over(handler).call_tool( + "run_workflow", + { + "workflow_path": "w.json", + "acknowledged_cost": True, + "request": "demo-1/cat", + }, + ) + await server_over(handler).call_tool( + "run_workflow", {"workflow_path": "w.json", "acknowledged_cost": True} + ) + + assert sent[0]["request"] == "demo-1" and sent[0]["item"] == "cat" + assert "request" not in sent[1] and "item" not in sent[1] + + +@pytest.mark.asyncio +async def test_run_workflow_shows_the_servers_ledger_refusal(): + def handler(request): + return httpx.Response( + 422, + json={ + "detail": { + "code": "request_closed", + "message": "request 'demo' is done", + } + }, + ) + + with pytest.raises(Exception) as caught: + await server_over(handler).call_tool( + "run_workflow", + { + "workflow_path": "w.json", + "acknowledged_cost": True, + "request": "demo/cat", + }, + ) + + assert "request 'demo' is done" in str(caught.value) From a19b0fdabe5c31a02cd5ea87ed54982145e35490 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 14:06:07 -0600 Subject: [PATCH 303/412] docs: #1482 - ledger job link in the map, SERVER.md, MCP.md and the Requests guide Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 10 +++++----- docs/MCP.md | 6 +++--- docs/SERVER.md | 16 ++++++++++++++-- docs/WORKSPACES.md | 26 +++++++++++++++++++++++--- 4 files changed, 45 insertions(+), 13 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0bd910d23..acd582d7b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -70,7 +70,7 @@ one to open. | Run directories | `dw/runs.py`: `open_run`, `workflow_identity`, `new_run_id` | Each execution writes into `///` with a `manifest.json`, unless the flat layout is chosen (the test pins the flat-layout exception). | `tests/test_runs.py::TestRunDirectories::test_the_flat_layout_writes_where_it_always_did` | | A file's role (final / intermediate / input) | `dw/roles.py` | Decided per step: result.role, then a final/intermediate subfolder, then data flow (a step a media-writing or unsaved consumer reads is intermediate). Engine records it at run end, with `role_declared` where result.role stated it; a run that predates roles recorded none, so the listing falls back on the file's own `final`/`intermediate` subfolder, then the demotion below, and a file neither places has none. At read time the gallery (`GET /api/gallery`, its `role=` filter, the metadata route) also demotes a file a later run of the same workspace read - an `output:` input (an unpinned `latest` is the newest run started before the reader) or an `asset:` keep_output kept from it - unless its role was declared (`consumed_outputs`, `listed_role`, once per listing; no manifest is rewritten). | `tests/test_roles.py`, `tests/test_roles.py::test_a_file_a_later_run_read_is_consumed`, `tests/test_roles.py::test_listed_role`, `tests/test_roles.py::test_listed_role_of_a_run_that_recorded_none`, `tests/test_gallery_roles.py::test_older_run_reads_its_intermediate_subfolder_as_intermediate`, `tests/test_gallery_roles.py::test_a_pre_roles_file_a_later_run_read_lists_as_intermediate`, `tests/test_gallery_roles.py::test_metadata_agrees_with_the_listing_for_an_older_run`, `tests/test_gallery_roles.py::test_a_file_a_later_run_read_lists_as_intermediate`, `tests/test_gallery_roles.py::test_a_declared_final_stays_final` | | Notes on runs, files, assets, workspaces | `dw/notes.py` | A note is `notes.json` beside what it describes (run dir or asset dir; a file's own note, else the run's), or `workspace.json` at a workspace root. Only the server writes them, never the engine; at most 4000 characters, plain text. | `tests/test_notes.py` | -| Requests ledger | `dw/ledger.py`, `dw/security.py`: `validate_ledger_key`, `dw/server/routes/library.py` (the ledger routes), `dw_mcp/ledger.py` | A workspace's requests are `requests.json` at its root, written only by the server, whole-request at the revision read (409 `stale_revision` otherwise), atomically under a per-directory lock; read without one. `prompt` is write-once, item keys and request ids match `^[a-z0-9][a-z0-9-]{0,63}`, `depends_on` stays within one request and acyclic, and a user's item comment survives an agent's write. A workspace with no root reads as empty and refuses writes. | `tests/test_ledger.py` | +| Requests ledger | `dw/ledger.py`, `dw/security.py`: `validate_ledger_key`, `dw/server/routes/library.py` (the ledger routes), `dw_mcp/ledger.py` | A workspace's requests are `requests.json` at its root, written only by the server, whole-request at the revision read (409 `stale_revision` otherwise), atomically under a per-directory lock; read without one. `prompt` is write-once, item keys and request ids match `^[a-z0-9][a-z0-9-]{0,63}`, `depends_on` stays within one request and acyclic, and a user's item comment survives an agent's write. A workspace with no root reads as empty and refuses writes. An item's status, attempts, result and spent/remaining minutes are derived from its linked jobs at read time and never stored; `accepted` is `{job, run_id}` of a succeeded job linked to that item. | `tests/test_ledger.py`, `tests/test_ledger_job_link.py` | | Run versions | `dw/runs.py`: `open_run`, `run_versions`, `record_run_versions`, `copy_runs_in` | A run takes its number once, when it opens (or, copied in from another workspace, when `copy_runs_in` places it), so deleting a middle run leaves a gap rather than renumbering. | `tests/test_runs.py::TestRunVersions::test_a_deleted_middle_run_leaves_a_gap_rather_than_renumbering`, `tests/test_runs.py::TestRunVersions::test_runs_started_in_the_same_second_still_number_upward` | | Run-version surfaces | `dw/runs.py`: `run_versions`, `dw/server/routes/gallery.py`, `dw/server/outputs.py`, `dw_mcp/tools_catalog.py`: `list_gallery`, `ui/src/lib/pages/GalleryPage.svelte` | Only `dw/runs.py` computes the number, and every other module reads it back. | `tests/test_runs.py::TestRunVersions::test_an_output_reference_can_name_a_run_by_its_version` | | What the server says about an output file | `dw/server/outputs.py`: `output_annotations` | The gallery listing (`dw/server/routes/gallery.py`) and the metadata route (`dw/server/routes/media.py`) describe an output file's `role`, `note`, `note_source`, `run_note`, `starred` and `version` through `output_annotations`, and neither builds those fields on its own. | `tests/test_gallery_roles.py::test_metadata_agrees_with_the_listing_on_a_starred_noted_demoted_file` | @@ -116,7 +116,7 @@ one to open. | Pipeline limits | `dw/pipeline_limits.py`: `pipeline_limit_errors` | Only what the pipeline would refuse is refused: a literal H3 `num_frames`, `width` or `height` outside the limits read off `MiniMaxH3ModularPipeline`. A diffusers that renames the class or a property makes it check nothing. | `tests/test_pipeline_limits.py` | | Step-value checks | `dw/step_value_checks.py`: `fps_errors`, `cache_errors`, `null_media_errors`, `select_errors`, `chain_prompts_errors`, `chain_length_errors` | The only caller of these checks is the error registry. | `dw/validation.py`: `ERROR_CHECKS` | | Command result type | `dw/scalar_result_validation.py`: `scalar_result_errors`, `unsaved_json_warnings`; a command declares it on `register_command` (`returns`, `result_content_type`) | A command's required `result` content_type (`application/json` for a json command, `result_content_type` for a fixed container such as `export_timeline`'s .otioz) is checked here from its own declaration, never by a second walk or a command-name match elsewhere. A JSON-answering task step with no `result` block and no later `previous_result:` reader (resolved by `step_cache.reference_resolves_to`) gets a validate warning, since its answer is dropped (#1366). | `tests/test_content_types.py::TestExportTimelineContentType::test_a_wellformed_but_wrong_type_is_refused_naming_otioz`; `tests/test_scalar_result_validation.py::TestUnsavedJsonWarnings::test_probe_without_result_warns` | -| Admission | `dw/server/admission.py`: `admit` | Validate, submit, rerun and enhance load and check a request once, and `JobManager.submit` does not check it again. | `tests/test_admission.py::test_a_submit_expands_once` | +| Admission | `dw/server/admission.py`: `admit` | Validate, submit, rerun and enhance load and check a request once, and `JobManager.submit` does not check it again; a `request`/`item` link is validated in that one step too (`unknown_request`, `request_closed`, `unknown_item`, `item_dropped`, 422). | `tests/test_admission.py::test_a_submit_expands_once` | | Presets | `dw/presets.py`: `apply_presets`, `effective_variables`, `preset_errors` | A `presets` bundle sets the variables the caller did not pass, through `set_variables` right before the caller's own arguments fold, so an explicit argument wins and a bundle value is validated like a caller's. The fold applies the default bundle with no usable arguments. Every reader of a written definition's variables for some arguments (constraint checks, argument warnings, host-RAM key, VRAM inheritance, observed-cost buckets, the estimate's defaults) goes through `effective_variables`; a reader of an expanded definition reads its folded `variables`. | `tests/test_presets.py::test_a_caller_value_beats_the_bundle`, `tests/test_presets.py::test_no_arguments_and_the_default_selector_have_one_fingerprint`, `tests/test_presets.py::test_a_bundle_value_breaking_a_rule_is_an_error_at_the_bundle` | | Variable constraints | `dw/variable_constraints.py`: `apply_constraints`; the grid arithmetic `aligned` / `aligned_down` | A model's rule about a value is declared in the workflow's `variable_constraints`, and it is checked at validation and again before anything loads. `plan_cuts` (and its static check) rounds render lengths through `aligned` / `aligned_down`, never its own copy, so a planned `num_frames` is one the template's constraint accepts; `crop_face_track` pads its crops to the step's `modulus`/`remainder` grid through `aligned` too (`padding_to_grid`), and `detect_cuts` rounds each cut's `render_frames` through `aligned` (`scene_cuts.render_frames`). | `tests/test_variable_constraints.py::TestTheGrid::test_without_snap_an_off_grid_value_is_refused_not_rounded`, `tests/test_variable_constraints.py::TestTheGrid::test_plan_cuts_rounds_through_the_constraint_owner`, `tests/test_face_track.py::TestPadding::test_padding_to_grid_rounds_through_the_constraint_owner`, `tests/test_variable_constraints.py::TestTheRunTimePass::test_an_illegal_value_is_refused_before_anything_loads` | | Bound acknowledgement | `dw/plan.py`: `fingerprint`, `dw/server/admission.py`: `check_bound_acknowledgement` | A bound `acknowledged_cost` is refused with 409 when the plan's fingerprint or its required downloads changed. The fingerprint is keyed only by what can change the output: `DOCUMENTATION_KEYS` (`cost`, `cost_drivers`, `vram_estimate`, descriptions, catalog shape/traits), a constraint's `reason` and a result's role, subfolder and file name are left out, of the workflow and of each composed child; every schema key is sorted into left out or kept. A number digests by value, not spelling (`12.0` as `12`), and the seed stays out (#85). | `tests/test_plan.py::TestFingerprintKeys::test_the_exclusion_lists_are_pinned`, `tests/test_plan.py::TestTheCatalogH3Template::test_a_client_round_trip_keeps_it`, `tests/test_plan.py::TestFingerprintKeys::test_every_top_level_schema_key_is_sorted`, `tests/test_server.py::TestBoundRerun::test_a_rerun_bound_to_a_stale_plan_is_refused`, `tests/test_server.py::TestBoundAcknowledgement::test_a_matching_fingerprint_queues` | @@ -200,8 +200,8 @@ one to open. | Per-card memory and cache | `dw/server/worker_memory.py`: `memory_status`, `clear_memory`, `probe_cache` | Each card keeps its own last memory reading; an idle card's worker is asked live, a busy one answers with the run's last report and says why it is not live, and a clear leaves a card running a job alone. Every request takes the card's lock with a bounded wait, and a card's lock is never taken while the JobManager's lock is held. | `tests/test_worker_pool.py::TestMemoryPerCard::test_a_named_card_running_a_job_is_refused_though_the_other_is_idle`, `tests/test_worker_pool.py::TestProbeRouting::test_the_probe_goes_to_the_worker_the_job_would_be_routed_to`, `tests/test_server.py::test_memory_says_why_a_reading_is_not_the_worker_s` | | dw disk caches | `dw/disk_caches.py`; `dw/server/jobs.py`: `JobManager.hold_dispatch`; `dw/server/routes/system.py`: `clear_cache`, `delete_cache_entry` | Members `inductor`, `triton`, `quantized`. Clear only a root carrying the `.dw-cache` marker, never while a job is running or queued (`quantized` also not during a model download); an entry delete takes only a 64-hex id, checked before any path is built; clear renames into `.clearing-*` then deletes. The busy check and the dispatch hold are one step in `JobManager.hold_dispatch`, kept for the whole clear or entry delete: a job submitted meanwhile is accepted but stays queued until it ends. | `tests/test_disk_caches.py`, `tests/test_disk_caches.py::test_job_submitted_during_a_clear_waits_for_it` | | Model-use index | `dw/model_use.py`; `dw/plan_downloads.py`: `repos_named`; `dw/server/jobs.py`: `JobManager._on_run_start` | `last_job_use` per Hub repo is written only by the server, at a job's run start, from the repos the run names (`repos_named`, computed at admission); keys are validated hub ids, the file is capped and best-effort, and a successful model delete forgets the repo. | `tests/test_model_use.py`, `tests/test_repos_named.py`, `tests/test_models_last_job_use.py` | -| Job-to-run link | `dw/server/job_record.py`, `dw/server/jobs.py`: `JobManager.realized` | A job records `run_id`, `run_dir` and `run_version`, and `JobManager.realized` reads that run's `workflow.json`, confined to the output root. | `tests/test_server_jobs.py::test_realized_reads_the_file_the_run_wrote`, `tests/test_server_jobs.py::test_realized_refuses_a_run_dir_that_escapes_the_output_root` | -| Job history | `dw/server/job_history.py`: `JobHistory`, `_ADDED_COLUMNS`, `close_instance`, `close_dead_servers`, `hold_server_lock` | Jobs persist in `jobs.sqlite`, in WAL mode, so the Jobs view survives a restart. A database from an older release gains each column it lacks from the `_ADDED_COLUMNS` table when it is opened. Every admitted job has a row from submit on, stamped with its server's instance id; each server holds `servers/.lock` beside the database for its life. A startup closes the queued and running rows of every server whose lock it can take as `cancelled`, `error` starting `server restart:` (a running one names its run directory), and leaves a live sibling's rows alone; readers serve closed rows only (#1220). A restart batch (`JobHistory.restart_batch`, `JobManager.rerun_restart_batch`, `POST /api/jobs/{id}/rerun-restart-batch`) is every `server restart:` row of one non-NULL `server_instance`, oldest first, uncapped; it is rerun under one batch lock, so concurrent calls queue each member once, and a member already rerun (`rerun_of`, indexed) or in a deleted workspace is skipped, never stopping the rest (#1266). A list row's `reason` (the error's first line, clipped to 160) and `restart_batch` (a tombstone's `server_instance`) come from one helper, `job_record.row_reason_fields`, on both the live summary and history's rows and details, so neither side can drift (#1449). | `tests/test_server.py::test_job_history_survives_restart_and_reruns`, `tests/test_restart_tombstones.py`, `tests/test_job_row_reason.py`, `tests/test_job_history_parity.py`, `tests/test_restart_tombstones.py::test_two_concurrent_calls_queue_each_member_once`, `tests/test_job_history_wal.py::test_the_jobs_database_uses_wal_mode`, `tests/test_server_jobs.py::test_a_v0_13_0_database_gains_the_columns_added_since` | +| Job-to-run link | `dw/server/job_record.py`, `dw/server/jobs.py`: `JobManager.realized` | A job records `run_id`, `run_dir` and `run_version`, and `JobManager.realized` reads that run's `workflow.json`, confined to the output root; a job linked to a ledger item also records `request` and `item`. | `tests/test_server_jobs.py::test_realized_reads_the_file_the_run_wrote`, `tests/test_server_jobs.py::test_realized_refuses_a_run_dir_that_escapes_the_output_root` | +| Job history | `dw/server/job_history.py`: `JobHistory`, `_ADDED_COLUMNS`, `close_instance`, `close_dead_servers`, `hold_server_lock` | Jobs persist in `jobs.sqlite`, in WAL mode, so the Jobs view survives a restart. A database from an older release gains each column it lacks from the `_ADDED_COLUMNS` table when it is opened. Every admitted job has a row from submit on, stamped with its server's instance id; each server holds `servers/.lock` beside the database for its life. A startup closes the queued and running rows of every server whose lock it can take as `cancelled`, `error` starting `server restart:` (a running one names its run directory), and leaves a live sibling's rows alone; readers serve closed rows only (#1220). A restart batch (`JobHistory.restart_batch`, `JobManager.rerun_restart_batch`, `POST /api/jobs/{id}/rerun-restart-batch`) is every `server restart:` row of one non-NULL `server_instance`, oldest first, uncapped; it is rerun under one batch lock, so concurrent calls queue each member once, and a member already rerun (`rerun_of`, indexed) or in a deleted workspace is skipped, never stopping the rest (#1266). A list row's `reason` (the error's first line, clipped to 160) and `restart_batch` (a tombstone's `server_instance`) come from one helper, `job_record.row_reason_fields`, on both the live summary and history's rows and details, so neither side can drift (#1449). The ledger link is two history columns, `request` and `item`, indexed by `request` so a request's jobs are found without a scan, and the hand-written list in `tests/test_job_history_parity.py` names them (#1482). | `tests/test_server.py::test_job_history_survives_restart_and_reruns`, `tests/test_restart_tombstones.py`, `tests/test_job_row_reason.py`, `tests/test_job_history_parity.py`, `tests/test_restart_tombstones.py::test_two_concurrent_calls_queue_each_member_once`, `tests/test_job_history_wal.py::test_the_jobs_database_uses_wal_mode`, `tests/test_server_jobs.py::test_a_v0_13_0_database_gains_the_columns_added_since` | | Job fields, live and persisted | `dw/server/job_record.py`: `Job.summary`, `Job.detail`; `dw/server/job_history.py`: `_RECORDED`, `_ADDED_COLUMNS`, `recent_summaries`, `_to_detail` | A job field is declared once per side: on `Job` (and its `summary()`/`detail()`), and in history as an `_ADDED_COLUMNS` entry plus one `(column, getter)` in `_RECORDED`. History readers take columns by name, never by position, and a historical job serves the same summary and detail keys a live one does, apart from the live-only poll state and the history-only markers the parity test declares. | `tests/test_job_history_parity.py::test_history_serves_the_keys_a_live_job_does` | | HTTP security | `dw/server/http_security.py`: `install_middleware`, `query_token_ok` | Every API route needs the token, and only a route marked `query_token_ok` takes it as `?token=`. | `tests/test_security_auth.py::TestTheTokenGate::test_every_api_spelling_needs_the_token`, `tests/test_security_auth.py::TestTheTokenGate::test_the_query_token_is_refused_where_it_is_not_allowed` | | Prompt enhancement | `dw/server/enhancers.py`: `PRESETS`, `_T2I_SYSTEM_PROMPT` | `PRESETS` is the Enhance panel's menu (label, curated LLMs, preselect hints); a preset's family-specific knowledge, its spec, lives in a builtin under `dw/workflows/`, never in Python. `t2i`'s generic, family-agnostic system prompt stays in Python. A third preset moves the menu into builtin metadata (#696). | `tests/test_prompt_library.py::test_every_enhancer_preset_targets_a_known_family`, `tests/test_server.py::TestEnhance::test_presets_are_listed`, `tests/test_server.py::TestEnhance::test_enhance_workflows_are_schema_valid`, `tests/test_server.py::TestEnhance::test_an_unknown_preset_is_a_client_error` | @@ -211,7 +211,7 @@ one to open. | Concept | Owner | Rule | Enforced by | | --- | --- | --- | --- | | `dw_mcp` stays torch-free | `dw_mcp/` | `dw_mcp` reaches `dw.serve` over HTTP and imports no `dw` module, because `dw/__init__.py` pulls in torch. | `tests/test_mcp_server.py::TestStartupWeight::test_the_server_starts_without_importing_the_engine` | -| Tool surface | `dw_mcp/server.py`, `dw_mcp/tools_*.py` | Only these modules import the MCP SDK, and each tool body is a one-line call into a handler. | `tests/test_mcp_server.py::test_the_wiring_table_covers_every_registered_tool`, `tests/test_mcp_server.py::test_the_stated_tool_count_is_the_registered_one` | +| Tool surface | `dw_mcp/server.py`, `dw_mcp/tools_*.py` | Only these modules import the MCP SDK, and each tool body is a one-line call into a handler; `run_workflow`'s `request` (`/`) is parsed in `dw_mcp/diagnose.py` before any HTTP call and sent as the body's `request` and `item`. | `tests/test_mcp_server.py::test_the_wiring_table_covers_every_registered_tool`, `tests/test_mcp_server.py::test_the_stated_tool_count_is_the_registered_one` | | Surface text budget | the tool docstrings in `dw_mcp/tools_*.py`, the instructions in `dw_mcp/server.py` | The instructions and each tool description stay at or under 2,048 characters, and the whole surface stays within its token budget. | `tests/test_mcp_server.py`: `SURFACE_BUDGET`, `CLIENT_TEXT_LIMIT`; `tests/test_mcp_server.py::test_no_text_the_agent_reads_is_cut_off_by_the_client`, `tests/test_mcp_server.py::test_the_tool_surface_fits_the_budget` | | Guide pointers in resident text | the tool docstrings in `dw_mcp/tools_*.py`, the instructions in `dw_mcp/server.py`, each plugin `SKILL.md` and its `references/` | Every `get_guide(...)` / guide-section pointer opens a real section through `dw/server/guides.py`'s `get_guide`, and the tools that point at a guide keep their pointer when text is trimmed to fit the budget. | `tests/test_guide_pointers.py` (`TOOLS_THAT_POINT`) | | Spending needs consent | each handler behind a tool that takes `acknowledged_cost` (`dw_mcp/diagnose.py`, `models.py`, `prompts.py`, `workspaces.py`) | Every tool that takes `acknowledged_cost` refuses until it is set; `delete_workspace`'s refusal is the server's 409. `rerun_job(restart_batch=true)` passes through without it, and the server owns that gate: `POST /api/jobs/{id}/rerun-restart-batch` (`JobManager.rerun_restart_batch`) answers a preview that queues nothing. The jobs page's restart banner is the route's second caller and keeps the same order: a click previews, and only a confirm sends `acknowledged_cost` (`ui/src/lib/restartBatches.ts`). | `tests/test_mcp_twins.py::test_every_tool_that_takes_acknowledged_cost_refuses_without_it`, `tests/test_restart_tombstones.py::test_mcp_rerun_job_previews_queues_then_skips_a_restart_batch`, `ui/src/lib/pages/JobsPage.test.ts` | diff --git a/docs/MCP.md b/docs/MCP.md index b963e3b64..b3ba0324b 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -240,8 +240,8 @@ isolation on a mounted server passes `workspace=` on every call that takes it. | `list_assets(detail=False, workspace=None, limit=50, prefix=None)` | Input media on the server, each with its `asset:` reference, newest first. Entries carry `name`, `reference`, `kind`, `size`, `origin` and any `note`; `detail=true` adds `folder`, `mtime`, `url`, `writable`, and `absolute_url`/`used_by` when set. `prefix` keeps names starting with it (`cast/`); `total` counts all matches. `libraries` and `shadowed` are as in `list_workflows` | | `keep_output(name, asset_name=None, overwrite=False, shared=False, workspace=None, note=None)` | Keep a generated file as an input asset under a stable `asset:` name, copied on the server. `asset_name` may name a folder and takes the file's extension when it has none; `shared=true` keeps it in the shared library, where a recurring cast belongs. `note` defaults to the source file's note | | `set_note(target, note=None, workspace=None)` | Set the note (plain text, up to 4000 characters) on a run (`/`), an output file, `asset:` or `workspace:`; null or `""` clears it. Returns `{target, note, note_source}`. Listings clip notes to 200 characters (`note_truncated`); `get_job` and `get_gallery_metadata` return them whole, and `get_job` shows the current note | -| `get_request(request=None, workspace=None)` | Read the workspace's requests ledger (`requests.json` at its root). With no `request`, every request newest change first, with item counts by status; with one, its whole plan: every item with its derived `status` (`planned` or `dropped` until jobs link to items), and its history | -| `set_request(request, title, goal, items, revision, why, prompt=None, state=None, workspace=None)` | Write one request's whole plan against the `revision` it was read at (0 creates it); another revision is refused with `stale_revision` and the current one. `prompt` is the user's ask, set on create only. Items match by `key`: one left out is deleted, or kept as dropped when jobs link to it. `why` is one line saying what changed. A user's item `comment` is kept when the write omits it. See `get_guide("workspaces", section="Requests")` | +| `get_request(request=None, workspace=None)` | Read the workspace's requests ledger (`requests.json` at its root). With no `request`, every request newest change first, with item counts by status; with one, its whole plan: every item with its derived `status`, `attempts`, `result` and `spent_minutes` (from the jobs linked by `run_workflow(request=...)`), the request's `spent_minutes` and `remaining_minutes`, and its history | +| `set_request(request, title, goal, items, revision, why, prompt=None, state=None, workspace=None)` | Write one request's whole plan against the `revision` it was read at (0 creates it); another revision is refused with `stale_revision` and the current one. `prompt` is the user's ask, set on create only. Items match by `key`: one left out is deleted, or kept as dropped when jobs link to it. `why` is one line saying what changed. A user's item `comment` is kept when the write omits it. An item's `accepted` takes `{"job": id}` (or a bare job id): a succeeded job linked to that item. See `get_guide("workspaces", section="Requests")` | | `upload_asset(file_path=None, content=None, asset_name=None, shared=False, workspace=None, note=None)` | Put an image, video, audio file or `.cube` LUT into the asset library and get its `asset:` reference. Exactly one of `file_path` (read on the machine running the MCP server, up to 200MB) or `content` (base64 inline, up to 4MB, #203; `asset_name` required). The file is stored under the library's `uploads/`, named `asset_name` when given (`cast/priya-voice.wav`, folders allowed, the extension matching the file's kind) and randomly otherwise; `shared=true` uses the shared library | | `delete_asset(name, workspace=None)` | Permanently remove one asset, by the name `list_assets` reports, from whichever library holds it (the workspace's own before the shared one). One from a read-only examples library is refused. A workflow still carrying the reference stops loading | | `save_workflow(name, workflow=None, patch=None, workspace=None)` | Save into the writable workflow directory, overwriting a workflow of that name there; `name` may include folders. Exactly one of `workflow` (the full document) or `patch` (a JSON Merge Patch, RFC 7396, onto the stored definition: `null` deletes a key, a list is replaced whole). Either may be a JSON-encoded string. A name that resolves to a read-only source is not overwritten: the copy lands in the writable directory and shadows it | @@ -271,7 +271,7 @@ enhancers and the LoRA catalog. | Tool | Purpose | | --- | --- | -| `run_workflow(workflow_path=None, inline_workflow=None, workflow=None, name=None, arguments=None, acknowledged_cost=False, workspace=None, wait_seconds=0, note=None)` | Queue a workflow. Exactly one of `workflow_path` (a catalog name from `list_workflows`, with or without `.json`, or a path on the server) or `inline_workflow` (an object or JSON-encoded string); `validate_workflow`'s spellings `name` and `workflow` are accepted too. `arguments` overrides variables by name and is checked as `validate_workflow` checks it; a bad one is refused before queueing. `acknowledged_cost` is `true` or the bound `{fingerprint, minutes, downloads}` from the validate plan; a 409 means the plan changed and carries the new estimate. Returns once queued, unless `wait_seconds` > 0: then it waits as `wait_for_job(job_id, timeout_seconds=wait_seconds)` would, under the same cap, and adds that wait's fields. `note` says what the run tests (see `set_note`) | +| `run_workflow(workflow_path=None, inline_workflow=None, workflow=None, name=None, arguments=None, acknowledged_cost=False, workspace=None, wait_seconds=0, note=None, request=None)` | Queue a workflow. Exactly one of `workflow_path` (a catalog name from `list_workflows`, with or without `.json`, or a path on the server) or `inline_workflow` (an object or JSON-encoded string); `validate_workflow`'s spellings `name` and `workflow` are accepted too. `arguments` overrides variables by name and is checked as `validate_workflow` checks it; a bad one is refused before queueing. `acknowledged_cost` is `true` or the bound `{fingerprint, minutes, downloads}` from the validate plan; a 409 means the plan changed and carries the new estimate. Returns once queued, unless `wait_seconds` > 0: then it waits as `wait_for_job(job_id, timeout_seconds=wait_seconds)` would, under the same cap, and adds that wait's fields. `note` says what the run tests (see `set_note`). `request` is `"/"`: it links the job to that ledger item (one `/`, both halves meeting the key rule, refused before any call otherwise; the server's 422 `unknown_request`, `request_closed`, `unknown_item` or `item_dropped` is shown as its message). See `get_guide("workspaces", section="Requests")` | | `get_job(job_id)` | Status, warnings, output manifest, error and traceback. Each manifest entry's `subfolder` is the one the step declared. A running job carries `progress`; a job held for host RAM or behind busy cards carries `waiting_for` (#869). `host_memory_job_peak_committed_mb` is the job's peak committed host memory, the figure the host-RAM gate projects from (null until a reading lands, #1214) | | `get_job_workflow(job_id)` | The workflow the job ran (`GET /api/jobs/{id}/workflow`, [SERVER.md](SERVER.md#jobs-api)). `realized: true` pins every mutable input (arguments, seed, prompts, `output:latest`); `false` is the submitted definition of a job from before run tracking. `seed_variable` names the variable `rerun_job(new_seed=true)` draws into. Pass it to `save_workflow` to keep it | | `export_job(job_id, overwrite=False)` | Gather a finished job into `/exports//` **on the server machine**: the realized workflow, the manifest, the job row, a README, and copies of its assets, earlier-run inputs and outputs (`total_bytes` is what was copied). Returns the directory, a zip URL, the file list and the total. The zip `open_url` needs no token (#592): fetch it (prefixing a relative URL with the server address) and unpack it into `exports/` in the session's working directory; it unpacks into one folder named after the job id. `auth_required: true` would mean a gated zip, to hand to the person. Refuses a running job, and an existing export without `overwrite=true` | diff --git a/docs/SERVER.md b/docs/SERVER.md index 66578a465..e2457d59e 100644 --- a/docs/SERVER.md +++ b/docs/SERVER.md @@ -390,8 +390,8 @@ server's refusal when a job is running: | Route | What it does | | --- | --- | -| `POST /api/jobs` | Queue a run: `{"workflow_path": ...}` or an inline `{"workflow": {...}, "base_dir": ...}`, plus `arguments` for variable overrides. `workflow_path` accepts a stored workflow name as listed by `/api/workflows` (with or without `.json`, nested names included), or a relative/absolute path that still resolves under `--workflow-dir` - confined the same way the `/api/workflows` CRUD routes are; a path that names a real file outside that directory is rejected with 400, not opened. Answers with argument warnings from signature checking. Takes an optional `acknowledged_cost`: `true` is recorded as `acknowledged: boolean`; the object `{fingerprint, minutes, downloads}` from a validate answer's `plan` is `bound` - the server re-plans the run for the arguments given and answers **409** when the fingerprint differs or a repo in `downloads_required` (pipeline `model_name`s and the repos task steps fetch) is not in `downloads` (a download that has since vanished is not a refusal); the body is `{"detail": {message, reason: "fingerprint" \| "downloads" \| "unplannable", acknowledged, plan, acknowledge}}` with the current plan, so the caller re-quotes from it, and `acknowledge` - the `{fingerprint, minutes, downloads}` to resend - whenever there is a plan. A `null` in `downloads` (a URL with no repo) is ignored. The validate `plan` sent unedited is bound too: when `downloads` is absent, its `downloads_required` repos (and `estimate.minutes`) are what was acknowledged; an explicit `downloads`, even `[]`, wins. `minutes` is recorded, never compared. Nothing is required: the web UI and every caller that sends nothing are `acknowledged: none`, and every job answer and history row carries `acknowledged` (and `acknowledged_cost` when bound). `POST /api/jobs/{id}/rerun` takes the same field and checks against the stored spec; a fresh seed does not change a fingerprint. | -| `GET /api/jobs?workspace=&status=&limit=` | Queue + history summaries, oldest first, with `total` beside them. `status` narrows to one state or a comma-separated set (`queued`, `running`, `succeeded`, `failed`, `cancelled`; anything else is a 400); `limit` keeps the newest N, and `total` still reports how many matched, so a bounded answer cannot be mistaken for a complete one. Each summary carries `device`, the card the job ran on (`"cuda:1 NVIDIA GeForce RTX 3090"`; null while queued and for older jobs), and `rerun_of`, present on a job started by rerun: the id of the job it reran; absent for a fresh submit. A failed or cancelled job with an error carries `reason`, the error's first line clipped to 160 characters with a trailing `…` (the full error stays on the detail); a restart tombstone also carries `restart_batch`, its dead server's `server_instance` - the key a restart batch groups by. Both are absent, never null, otherwise. No parameters means every job, which is what the web UI polls | +| `POST /api/jobs` | Queue a run: `{"workflow_path": ...}` or an inline `{"workflow": {...}, "base_dir": ...}`, plus `arguments` for variable overrides. `workflow_path` accepts a stored workflow name as listed by `/api/workflows` (with or without `.json`, nested names included), or a relative/absolute path that still resolves under `--workflow-dir` - confined the same way the `/api/workflows` CRUD routes are; a path that names a real file outside that directory is rejected with 400, not opened. Answers with argument warnings from signature checking. Takes an optional `acknowledged_cost`: `true` is recorded as `acknowledged: boolean`; the object `{fingerprint, minutes, downloads}` from a validate answer's `plan` is `bound` - the server re-plans the run for the arguments given and answers **409** when the fingerprint differs or a repo in `downloads_required` (pipeline `model_name`s and the repos task steps fetch) is not in `downloads` (a download that has since vanished is not a refusal); the body is `{"detail": {message, reason: "fingerprint" \| "downloads" \| "unplannable", acknowledged, plan, acknowledge}}` with the current plan, so the caller re-quotes from it, and `acknowledge` - the `{fingerprint, minutes, downloads}` to resend - whenever there is a plan. A `null` in `downloads` (a URL with no repo) is ignored. The validate `plan` sent unedited is bound too: when `downloads` is absent, its `downloads_required` repos (and `estimate.minutes`) are what was acknowledged; an explicit `downloads`, even `[]`, wins. `minutes` is recorded, never compared. Nothing is required: the web UI and every caller that sends nothing are `acknowledged: none`, and every job answer and history row carries `acknowledged` (and `acknowledged_cost` when bound). `POST /api/jobs/{id}/rerun` takes the same field and checks against the stored spec; a fresh seed does not change a fingerprint. Takes optional `request` and `item` (both or neither, each matching `^[a-z0-9][a-z0-9-]{0,63}$`) linking the job to an item of that workspace's requests ledger; a link the ledger cannot admit is refused **422** with `detail: {code, message}`, `code` one of `unknown_request` (no such request, or no workspace root), `request_closed` (done or abandoned), `unknown_item`, `item_dropped`. The job summary and detail carry `request` and `item` when set (absent otherwise). A rerun inherits the link; when it no longer admits, the rerun is queued unlinked with a `rerun_ledger_link_` warning. | +| `GET /api/jobs?workspace=&status=&request=&item=&limit=` | Queue + history summaries, oldest first, with `total` beside them. `request` keeps the jobs linked to that request, and `item` (with `request`) those linked to that item. `status` narrows to one state or a comma-separated set (`queued`, `running`, `succeeded`, `failed`, `cancelled`; anything else is a 400); `limit` keeps the newest N, and `total` still reports how many matched, so a bounded answer cannot be mistaken for a complete one. Each summary carries `device`, the card the job ran on (`"cuda:1 NVIDIA GeForce RTX 3090"`; null while queued and for older jobs), and `rerun_of`, present on a job started by rerun: the id of the job it reran; absent for a fresh submit. A failed or cancelled job with an error carries `reason`, the error's first line clipped to 160 characters with a trailing `…` (the full error stays on the detail); a restart tombstone also carries `restart_batch`, its dead server's `server_instance` - the key a restart batch groups by. Both are absent, never null, otherwise. No parameters means every job, which is what the web UI polls | | `GET /api/jobs/{id}` | Full detail: spec, events, manifest, error. A manifest entry for a step served from the step cache carries `reused: true`. Every entry carries `subfolder` - the in-run subfolder the step's `result.subfolder` chose, `''` for none. A `for_each` step appears in the manifest as its members (`shot@wide_open`, `shot@closeup`), because the manifest records what ran; the run's `workflow.json` keeps the `for_each` form, because it records what was asked Carries `output_kinds`: each manifest file mapped to its media kind (`image`, `video`, `audio`, `text`, or null), and each file-carrying run event (`step_end`) carries the same map for its own files. The entry of a pipeline step that ran carries `timing` (see [Step timing](WORKSPACES.md#step-timing)). Carries `rerun_of` - present on a job started by rerun: the id of the job it reran; absent for a fresh submit. Carries `host_memory_job_peak_committed_mb`, the job's peak committed host memory (anonymous + shared + device-mapped pages, the figure the host-RAM gate projects from), null until a reading lands (#1214). | | `DELETE /api/jobs/{id}/run` | Delete the run directory a finished job wrote, whole, from the output root the job ran against (no workspace selector applies): `{job_id, run_dir, deleted, run_swept}`. 404 for an unknown job or one with no run directory, 409 for one still queued or running | | `GET /api/jobs/{id}/workflow` | The workflow the job ran: `{id, definition, realized, seed_variable}`. `seed_variable` names the variable a `new_seed` rerun would draw into (null when the workflow has none), read from the workflow as written rather than the realized copy, whose seed is pinned. `realized: true` is the copy the run itself wrote (`workflow.json` in its run directory), with arguments, seed, prompts and `output:latest` pinned; `false` falls back to the submitted definition, which is what a job from before run tracking has. 404 means neither is readable - the job itself still is. The equivalent MCP tool is `get_job_workflow` (see [MCP.md](MCP.md#diagnose)) | @@ -961,6 +961,18 @@ The editor's forms come from these; they are just as usable from scripts: path so output subfolders survive; the gallery's bulk download. An unknown or out-of-directory name 404s the whole request rather than yielding a partial archive +- `GET /api/workspaces/{name}/requests[/{id}]`, `PUT + /api/workspaces/{name}/requests/{id}` — the requests ledger + ([WORKSPACES.md](WORKSPACES.md#requests)). Reads derive from the jobs linked + through `POST /api/jobs` `request`/`item`: each item carries `status` + (`dropped`, `done`, `running`, `queued`, `failed`, `planned`), `attempts` + (`[{job, status, note?, minutes}]`, oldest first), `result` (`{job, run_id}` + or null), `accepted_missing` (only when true) and `spent_minutes`; the + request view and each list row carry `spent_minutes` and + `remaining_minutes`. An item's `accepted` on write takes `{"job": id}` or a + bare job id of a succeeded job linked to that request and item, stored as + `{job, run_id}`. `GET /api/gallery?request=` lists only files of runs + whose jobs are linked to that request. - `GET /api/workspaces`, `POST /api/workspaces` (`{"name": ...}`), `DELETE /api/workspaces/{name}?acknowledged=true` — the workspaces on this server ([layout](WORKSPACES.md#several-workspaces-on-one-server)). Delete diff --git a/docs/WORKSPACES.md b/docs/WORKSPACES.md index 81250a2e0..84fcb499d 100644 --- a/docs/WORKSPACES.md +++ b/docs/WORKSPACES.md @@ -324,11 +324,11 @@ Read it with `get_request(request=None)` (MCP) or `GET arguments, accepted, comment}`, matched across writes by `key`. An item left out of a write is deleted, or kept as `dropped` (moved to the end) when jobs link to it; writing a dropped key again un-drops it. Each item - reads back with a derived `status`: `planned` or `dropped` until jobs - link to items. A field not listed is refused. + reads back with derived fields (below). A field not listed is refused + on write, apart from the derived ones, which are ignored. - **`depends_on`** names other keys of the same request, at most 16, never the item itself, and never in a cycle. -- **`accepted`** names a job linked to the item that succeeded. +- **`accepted`** names a succeeded job linked to that request and item: `{"job": ""}` or the bare job id, stored as `{job, run_id}`. - **`comment`** is the user's: an agent's write that omits it keeps it. - **Keys** (request ids and item keys) match `^[a-z0-9][a-z0-9-]{0,63}$`. - **Caps.** Titles 200 characters, prompt and goal 20000, comment 4000; @@ -337,6 +337,26 @@ Read it with `get_request(request=None)` (MCP) or `GET values only, names as variable names, strings at most 20000. No text carries control characters. +**Linking jobs.** `run_workflow(request="/")` (or +`request` and `item` in the `POST /api/jobs` body) links the job to that +item. The client refuses anything but one `/` between two valid keys before +any call; the server refuses 422 with `unknown_request`, `request_closed`, +`unknown_item` or `item_dropped`. A rerun inherits the link; if it no longer +admits, the rerun still queues, unlinked, with a `rerun_ledger_link_` +warning. `get_job` and `list_jobs` show `request`/`item` on a linked job. + +**Derived, never stored.** Each read works the item out from its linked +jobs. `status` is the first that applies: `dropped`, `done` (a linked job +succeeded), `running`, `queued`, `failed` (every linked job failed or was +cancelled), `planned` (none). `attempts` lists the jobs oldest first as +`{job, status, note?, minutes}`; `result` is the accepted job's `{job, +run_id}`, else the latest succeeded job whose run still exists, else null; +`accepted_missing: true` appears when the accepted job's run is gone. +`spent_minutes` sums the attempts' minutes, per item and per request, and the +request's `remaining_minutes` sums the estimates of items neither done nor +dropped. To keep a take, read `get_request`, then write the plan back with +`set_request` and that item's `accepted: {"job": ""}`. + A server started from loose directories has a default workspace with no root folder: its ledger reads as empty and a write is refused with 409 `no_workspace_root`. From e815f5d806bf7eaa539442010d52238db1061abd Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 14:10:59 -0600 Subject: [PATCH 304/412] docs: #1451 close-out - design record for the per-segment chain view Moves plan v2 into docs/proposals/complete/chain-segments-view-complete.md (stages #1474-#1476: what was built, deviations, bounces, deferred) and adds the shipped entry to todo.md. Co-Authored-By: Claude Opus 5.5 --- .../complete/chain-segments-view-complete.md | 133 ++++++++++++++++++ docs/proposals/todo.md | 9 ++ 2 files changed, 142 insertions(+) create mode 100644 docs/proposals/complete/chain-segments-view-complete.md diff --git a/docs/proposals/complete/chain-segments-view-complete.md b/docs/proposals/complete/chain-segments-view-complete.md new file mode 100644 index 000000000..dce8f48f7 --- /dev/null +++ b/docs/proposals/complete/chain-segments-view-complete.md @@ -0,0 +1,133 @@ +# A per-segment view of a chain: measures, a segment table, repair and continue (#1451) + +Written by model `claude-opus-5-5` via provider `anthropic` (close-out session, +2026-11-19). Don filed the idea on 2026-11-18, from a UI support assessment of +v0.19.0..develop (0e85aabc). Plan v2 is the plan comment on #1451 and holds the full +sweep. This file records what was built, the deviations, and what stays open. + +## Verdict: build smaller (three stages, A → B → C) + +- **Who gains:** + - MCP sessions driving chains. Before this, a passing segment recorded only + `attempts`, `face_drop` and `words`. Its jump, look, cut and texture ratios, and + every ceiling, were computed and then dropped. + - Don in the browser. The job page showed one chip parsed from phase text, and a + finished job showed nothing. +- **Corrections to the idea:** + - The data had to be on the manifest, not in an event: a finished job keeps 200 + events and its SSE stream is empty. + - A chain that died records no shots, so it can't be resumed from the page. + - No still is written per segment. The thumbnail is the segment's mp4 or the take + seeked to the segment's start. +- **Cut (Q2):** live rows while a chain runs, resuming a died chain, and "resume from + here" on an arbitrary row. Only **Continue the chain** was kept. +- **Rejected alternative:** a structured `chain_segment` event (see the first + correction). + +## Plan history + +- **v1 (2026-11-18).** Three stages. The advisor approved it on Don's behalf at + 2026-11-19T05:10Z, with every question's default and four adjustments: + - acceptance runs on mini-ai with LTX-2.5, no H3; + - Repair is enabled only for the H3 family (the only `repair-segment` template is + `templates/minimax/repair-segment`); + - Continue needs the workflow to declare variables for both `stop_after` and + `resume_from`; + - `audio_dbfs` stays a top-level shot key and is mirrored into `measures`. +- **v2 (2026-11-19).** Wrote the ruling into the plan. No scope change. + +**Rulings (advisor, all defaults):** Q1 [default] `measures` on every checked shot; +Q2 [scope] cut as listed; Q3 [scope] the tester verifies B and C with vitest, +playwright, both themes' screenshots and a real job page; Q4 [none] names as proposed. + +## What was built + +### Stage A (#1474): `measures` on chain shot records (engine + REST schema) + +Commit `6fde2e5d`, merged to `develop` at `34949ebf`. + +- `chain_check.measures_record`, called from `chain.py` `_record_check`, writes + `shot["measures"]` on every checked segment, from the kept attempt, pass or fail. + Each entry is `{value, ceiling, bound, warn_only, failed}`: + - the ceiling is the `SegmentCheck` value in force (so an override shows), or `null` + when the measure has none; + - `warn_only` comes from `WARN_ONLY` (texture and face_drop); + - `failed` is the check's own verdict, not a fresh comparison; + - `words` is its similarity against `words_similarity_min`, `bound: "min"`; + - `audio_dbfs` stays top-level and is mirrored with `bound: "min"`. +- A chain with the check off gets no key. Segment 1 carries only what it measured + (`{audio_dbfs}` or `{}`). +- `dw/server/api_models.py` types `ManifestEntry.shots` as `list[ShotRecord]` + (`extra="allow"`, with `ShotMeasure`), regenerated into `ui/src/lib/generated/`. +- MCP is unchanged: `get_job` and `get_gallery_metadata` pass the key through. +- The architecture review passed: `measures_record` lives in `chain_check.py`, the + module the map already names as the owner. + +### Stage B (#1475): the segment table on the job page (UI, read-only) + +Commit `0d27adec`, merged to `develop` at `249ce1b8`. + +- `ui/src/lib/job/ChainSegments.svelte`, mounted once on `JobPage.svelte` after + Results. The pure rows are in `ui/src/lib/chainRows.ts`. A step is chained when its + shots carry `planned_segments`. +- Each row has: + - a lazy thumbnail (the `segment_file`, otherwise the take at `start_frame / fps`); + - attempts "n of m", plus "kept seed N"; + - one cell per measure (`value ≤ ceiling`, `≥` for a min bound, or "(no ceiling)"), + with a pass, warn or fail verdict read from the engine's fields; + - `resumed` and `(repaired)` marks. +- The header reads "k of N planned". Unknown measure names render generically, after + the known ones. +- **Deviations:** + - "m" and the fps come from the job's definition and arguments, not the shot. When + they're missing, the cell reads "n attempts" and the seek uses the segment's share + of the take. + - Segment 1 with `{}` reads "nothing measured", and a job before stage A reads + "not recorded". + +### Stage C (#1476): Repair and Continue (UI over existing routes) + +Commit `9b7a940e` (merge `8e50f369`), with the bounce fix `fd59627d` (merge +`adedc601`). + +- **Repair this segment** (`ui/src/lib/chainActions.ts` `repairAction`): + - **Family rule:** the chain step's `model_name` (a literal, or a `variable:` + resolved against the job) must equal a `model_name` that + `templates/minimax/repair-segment` loads. The template is read live, so no + family is hard-coded. + - Disabled reasons, in this order: no template for the family; segment 1; a + repaired take; segments not kept. + - Enabled, it writes a one-shot `dw-workflow-prefill` to sessionStorage and opens + the template with `chain_take` and `segment` filled. Nothing runs until Run. +- **Continue the chain** (`continueAction`), shown once above the table when the take + is short of its plan, every row has a segment file, and `stop_after` and + `resume_from` are both declared variables. It prices the rerun with `POST + /api/validate?sizes=false`, confirms with the estimate, then POSTs + `/api/jobs/{id}/rerun` with the last segment as `resume_from` and `stop_after` + null. It isn't limited to H3. + +## Verification and bounces + +Everything was verified on mini-ai (MPS) with the tester's `chain-1451` fixture, an +LTX-2.5 chain at 256², 25 frames, 3 segments, `jump_ratio_max` 6.5. No H3 was run. +The enabled Repair path was checked on a mocked H3 job. + +| Stage | Cases | Bounces | Notes | +|---|---|---|---| +| A #1474 | C-F1073 to C-F1078 | 0 | Parked once: C-F1078's REST/OpenAPI clause couldn't be run with the tester's tools. dkackman/harnest#253 made it MCP-only, and then it passed. | +| B #1475 | C-F1079 to C-F1082, SE-F073 part 1 | 0 | C-F1080's "no `cut_ratio` cell" contradicted C-F1079 and C-F1082; amended in dkackman/harnest#259. SE-F073 part 2 was retargeted to #1476 (dkackman/harnest#260). | +| C #1476 | C-F1083 to C-F1087 | 1 | C-F1086: the Continue confirm had no estimate. The plan cited a "confirm-and-estimate flow", but Run again has none, so the fix prices the rerun through validate. | + +No stage comment reported a `usage:` figure, so cost is not recorded. The plan's +estimate was about $13 ($4, $5, $4). + +## Deferred, and what brings each back + +- **Live rows during a running chain:** if Don asks. It needs a per-segment event with + path redaction and relative paths. +- **Resuming a chain that died:** if the engine writes a partial manifest on failure. +- **Resume from an arbitrary row:** if a field report asks. +- **Repair for other families:** when a `repair-segment` template exists for one. The + family rule reads the template, so Repair enables with no UI change. +- **Repair of two adjacent segments** (#1231): a later row action. +- **Per-shot audio drift** (#1442): any new `measures` entry renders by name. diff --git a/docs/proposals/todo.md b/docs/proposals/todo.md index 6eeafc883..f81511791 100644 --- a/docs/proposals/todo.md +++ b/docs/proposals/todo.md @@ -37,6 +37,15 @@ remaining deferred fix is recorded in ## Shipped since the ranking +- **A per-segment view of a chain** (#1451, stages #1474-#1476), closed + 2026-11-19. Every checked chain shot carries `measures` (`{value, ceiling, + bound, warn_only, failed}` per measure, from the kept attempt), typed as + `ShotRecord` in the REST schema. The job page shows a segment table: a + thumbnail, attempts, each measure against its ceiling, and resumed/repaired + marks. Repair (H3 family only, matched by the template's `model_name`) opens + `minimax/repair-segment` pre-filled, and Continue the chain prices and reruns + a `stop_after` take from its last segment. Live rows, died-chain resume and + per-row resume were cut: `complete/chain-segments-view-complete.md`. - **Catalog LoRA suggestions in the LoRA editor** (#1456, stage #1480), closed 2026-11-19. For a literal `owner/name` base, the editor lists the catalog's non-rejected entries for that base (and literal partition), proven first, with From 8cdaead820b60f111e7a96f16c479ee97ea14ebc Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 15:17:37 -0600 Subject: [PATCH 305/412] refactor(server): #1482 - keep JobManager.submit under 150 lines with the ledger link Co-Authored-By: Claude Opus 5.5 --- dw/server/jobs.py | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/dw/server/jobs.py b/dw/server/jobs.py index 9cd9994d4..4e694ac2c 100644 --- a/dw/server/jobs.py +++ b/dw/server/jobs.py @@ -337,7 +337,6 @@ def submit( `note` is the run's note, already cleaned (`admitted_note`): kept on the job and written into the run directory when the run opens. - `request` and `item` link the job to a requests-ledger item (#1458). `rerun_of` is the job this one reruns, recorded so the list can say so; @@ -386,20 +385,13 @@ def submit( if acknowledged_cost is not None: spec["acknowledged_cost"] = acknowledged_cost spec["output_dir"] = job_output_dir - if asset_dir: - spec["asset_dir"] = asset_dir spec["warnings"] = list(warnings or []) - if note: - spec["note"] = note - if rerun_of: - spec["rerun_of"] = rerun_of - if overrides: - spec["overrides"] = overrides - # The requests-ledger link, already checked by admission (a rerun's - # inherited one is not - `rerun` warns instead) - if request and item: - spec["request"] = request - spec["item"] = item + # Each recorded only when given + optional = dict(asset_dir=asset_dir, note=note, rerun_of=rerun_of) + optional["overrides"] = overrides + if request and item: # admission checked it; a rerun's, `rerun` warns on + optional.update(request=request, item=item) + spec.update({key: value for key, value in optional.items() if value}) job = Job(spec) job.host_ram_need = host_ram_need From fcdd5271a3101d7e4b45f96470e3732f7b72a534 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 15:28:19 -0600 Subject: [PATCH 306/412] fix(ledger): #1482 - one owner for the key rule and the run-exists check; Admission row names where the link is refused Architecture review of stage 2: - dw_mcp/diagnose.py no longer copies validate_ledger_key; it splits on exactly one '/' and the server's JobRequest 422 refuses a bad key. - JobManager._linked uses outputs.job_run_directory for run_exists. - ARCHITECTURE Admission row names routes/jobs.py: submit_job and JobManager._link_warnings; MCP.md and the Requests guide match (a rerun keeps its link). Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 2 +- docs/MCP.md | 2 +- docs/WORKSPACES.md | 10 +++++----- dw/server/jobs.py | 4 +--- dw_mcp/diagnose.py | 17 ++++++----------- tests/test_mcp_server.py | 25 ++++++++++++++++++++++++- 6 files changed, 38 insertions(+), 22 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index acd582d7b..138c850cd 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -116,7 +116,7 @@ one to open. | Pipeline limits | `dw/pipeline_limits.py`: `pipeline_limit_errors` | Only what the pipeline would refuse is refused: a literal H3 `num_frames`, `width` or `height` outside the limits read off `MiniMaxH3ModularPipeline`. A diffusers that renames the class or a property makes it check nothing. | `tests/test_pipeline_limits.py` | | Step-value checks | `dw/step_value_checks.py`: `fps_errors`, `cache_errors`, `null_media_errors`, `select_errors`, `chain_prompts_errors`, `chain_length_errors` | The only caller of these checks is the error registry. | `dw/validation.py`: `ERROR_CHECKS` | | Command result type | `dw/scalar_result_validation.py`: `scalar_result_errors`, `unsaved_json_warnings`; a command declares it on `register_command` (`returns`, `result_content_type`) | A command's required `result` content_type (`application/json` for a json command, `result_content_type` for a fixed container such as `export_timeline`'s .otioz) is checked here from its own declaration, never by a second walk or a command-name match elsewhere. A JSON-answering task step with no `result` block and no later `previous_result:` reader (resolved by `step_cache.reference_resolves_to`) gets a validate warning, since its answer is dropped (#1366). | `tests/test_content_types.py::TestExportTimelineContentType::test_a_wellformed_but_wrong_type_is_refused_naming_otioz`; `tests/test_scalar_result_validation.py::TestUnsavedJsonWarnings::test_probe_without_result_warns` | -| Admission | `dw/server/admission.py`: `admit` | Validate, submit, rerun and enhance load and check a request once, and `JobManager.submit` does not check it again; a `request`/`item` link is validated in that one step too (`unknown_request`, `request_closed`, `unknown_item`, `item_dropped`, 422). | `tests/test_admission.py::test_a_submit_expands_once` | +| Admission | `dw/server/admission.py`: `admit` | Validate, submit, rerun and enhance load and check a request once, and `JobManager.submit` does not check it again. A `request`/`item` link's key shape is checked in `JobRequest` (`validate_ledger_key`, 422; `dw_mcp` only splits on the one `/`), and the ledger lookup (`dw/ledger.py: link_problem`: `unknown_request`, `request_closed`, `unknown_item`, `item_dropped`, 422) refuses it in `dw/server/routes/jobs.py: submit_job` before admission runs; a rerun's inherited link is not refused but warned (`JobManager._link_warnings`). | `tests/test_admission.py::test_a_submit_expands_once` | | Presets | `dw/presets.py`: `apply_presets`, `effective_variables`, `preset_errors` | A `presets` bundle sets the variables the caller did not pass, through `set_variables` right before the caller's own arguments fold, so an explicit argument wins and a bundle value is validated like a caller's. The fold applies the default bundle with no usable arguments. Every reader of a written definition's variables for some arguments (constraint checks, argument warnings, host-RAM key, VRAM inheritance, observed-cost buckets, the estimate's defaults) goes through `effective_variables`; a reader of an expanded definition reads its folded `variables`. | `tests/test_presets.py::test_a_caller_value_beats_the_bundle`, `tests/test_presets.py::test_no_arguments_and_the_default_selector_have_one_fingerprint`, `tests/test_presets.py::test_a_bundle_value_breaking_a_rule_is_an_error_at_the_bundle` | | Variable constraints | `dw/variable_constraints.py`: `apply_constraints`; the grid arithmetic `aligned` / `aligned_down` | A model's rule about a value is declared in the workflow's `variable_constraints`, and it is checked at validation and again before anything loads. `plan_cuts` (and its static check) rounds render lengths through `aligned` / `aligned_down`, never its own copy, so a planned `num_frames` is one the template's constraint accepts; `crop_face_track` pads its crops to the step's `modulus`/`remainder` grid through `aligned` too (`padding_to_grid`), and `detect_cuts` rounds each cut's `render_frames` through `aligned` (`scene_cuts.render_frames`). | `tests/test_variable_constraints.py::TestTheGrid::test_without_snap_an_off_grid_value_is_refused_not_rounded`, `tests/test_variable_constraints.py::TestTheGrid::test_plan_cuts_rounds_through_the_constraint_owner`, `tests/test_face_track.py::TestPadding::test_padding_to_grid_rounds_through_the_constraint_owner`, `tests/test_variable_constraints.py::TestTheRunTimePass::test_an_illegal_value_is_refused_before_anything_loads` | | Bound acknowledgement | `dw/plan.py`: `fingerprint`, `dw/server/admission.py`: `check_bound_acknowledgement` | A bound `acknowledged_cost` is refused with 409 when the plan's fingerprint or its required downloads changed. The fingerprint is keyed only by what can change the output: `DOCUMENTATION_KEYS` (`cost`, `cost_drivers`, `vram_estimate`, descriptions, catalog shape/traits), a constraint's `reason` and a result's role, subfolder and file name are left out, of the workflow and of each composed child; every schema key is sorted into left out or kept. A number digests by value, not spelling (`12.0` as `12`), and the seed stays out (#85). | `tests/test_plan.py::TestFingerprintKeys::test_the_exclusion_lists_are_pinned`, `tests/test_plan.py::TestTheCatalogH3Template::test_a_client_round_trip_keeps_it`, `tests/test_plan.py::TestFingerprintKeys::test_every_top_level_schema_key_is_sorted`, `tests/test_server.py::TestBoundRerun::test_a_rerun_bound_to_a_stale_plan_is_refused`, `tests/test_server.py::TestBoundAcknowledgement::test_a_matching_fingerprint_queues` | diff --git a/docs/MCP.md b/docs/MCP.md index b3ba0324b..2551727d7 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -271,7 +271,7 @@ enhancers and the LoRA catalog. | Tool | Purpose | | --- | --- | -| `run_workflow(workflow_path=None, inline_workflow=None, workflow=None, name=None, arguments=None, acknowledged_cost=False, workspace=None, wait_seconds=0, note=None, request=None)` | Queue a workflow. Exactly one of `workflow_path` (a catalog name from `list_workflows`, with or without `.json`, or a path on the server) or `inline_workflow` (an object or JSON-encoded string); `validate_workflow`'s spellings `name` and `workflow` are accepted too. `arguments` overrides variables by name and is checked as `validate_workflow` checks it; a bad one is refused before queueing. `acknowledged_cost` is `true` or the bound `{fingerprint, minutes, downloads}` from the validate plan; a 409 means the plan changed and carries the new estimate. Returns once queued, unless `wait_seconds` > 0: then it waits as `wait_for_job(job_id, timeout_seconds=wait_seconds)` would, under the same cap, and adds that wait's fields. `note` says what the run tests (see `set_note`). `request` is `"/"`: it links the job to that ledger item (one `/`, both halves meeting the key rule, refused before any call otherwise; the server's 422 `unknown_request`, `request_closed`, `unknown_item` or `item_dropped` is shown as its message). See `get_guide("workspaces", section="Requests")` | +| `run_workflow(workflow_path=None, inline_workflow=None, workflow=None, name=None, arguments=None, acknowledged_cost=False, workspace=None, wait_seconds=0, note=None, request=None)` | Queue a workflow. Exactly one of `workflow_path` (a catalog name from `list_workflows`, with or without `.json`, or a path on the server) or `inline_workflow` (an object or JSON-encoded string); `validate_workflow`'s spellings `name` and `workflow` are accepted too. `arguments` overrides variables by name and is checked as `validate_workflow` checks it; a bad one is refused before queueing. `acknowledged_cost` is `true` or the bound `{fingerprint, minutes, downloads}` from the validate plan; a 409 means the plan changed and carries the new estimate. Returns once queued, unless `wait_seconds` > 0: then it waits as `wait_for_job(job_id, timeout_seconds=wait_seconds)` would, under the same cap, and adds that wait's fields. `note` says what the run tests (see `set_note`). `request` is `"/"`: it links the job to that ledger item (exactly one `/`, refused before any call otherwise; each half must meet the key rule, a 422 from the server before anything queues, as is the server's 422 `unknown_request`, `request_closed`, `unknown_item` or `item_dropped` is shown as its message). See `get_guide("workspaces", section="Requests")` | | `get_job(job_id)` | Status, warnings, output manifest, error and traceback. Each manifest entry's `subfolder` is the one the step declared. A running job carries `progress`; a job held for host RAM or behind busy cards carries `waiting_for` (#869). `host_memory_job_peak_committed_mb` is the job's peak committed host memory, the figure the host-RAM gate projects from (null until a reading lands, #1214) | | `get_job_workflow(job_id)` | The workflow the job ran (`GET /api/jobs/{id}/workflow`, [SERVER.md](SERVER.md#jobs-api)). `realized: true` pins every mutable input (arguments, seed, prompts, `output:latest`); `false` is the submitted definition of a job from before run tracking. `seed_variable` names the variable `rerun_job(new_seed=true)` draws into. Pass it to `save_workflow` to keep it | | `export_job(job_id, overwrite=False)` | Gather a finished job into `/exports//` **on the server machine**: the realized workflow, the manifest, the job row, a README, and copies of its assets, earlier-run inputs and outputs (`total_bytes` is what was copied). Returns the directory, a zip URL, the file list and the total. The zip `open_url` needs no token (#592): fetch it (prefixing a relative URL with the server address) and unpack it into `exports/` in the session's working directory; it unpacks into one folder named after the job id. `auth_required: true` would mean a gated zip, to hand to the person. Refuses a running job, and an existing export without `overwrite=true` | diff --git a/docs/WORKSPACES.md b/docs/WORKSPACES.md index 84fcb499d..d92e3202b 100644 --- a/docs/WORKSPACES.md +++ b/docs/WORKSPACES.md @@ -339,11 +339,11 @@ Read it with `get_request(request=None)` (MCP) or `GET **Linking jobs.** `run_workflow(request="/")` (or `request` and `item` in the `POST /api/jobs` body) links the job to that -item. The client refuses anything but one `/` between two valid keys before -any call; the server refuses 422 with `unknown_request`, `request_closed`, -`unknown_item` or `item_dropped`. A rerun inherits the link; if it no longer -admits, the rerun still queues, unlinked, with a `rerun_ledger_link_` -warning. `get_job` and `list_jobs` show `request`/`item` on a linked job. +item. The client refuses anything but exactly one `/` before any call; the +server refuses 422, before anything queues, a half that isn't a valid key, or +a link with `unknown_request`, `request_closed`, `unknown_item` or +`item_dropped`. A rerun inherits the link; if it no longer admits, the rerun +still queues and keeps the link, with a `rerun_ledger_link_` warning. `get_job` and `list_jobs` show `request`/`item` on a linked job. **Derived, never stored.** Each read works the item out from its linked jobs. `status` is the first that applies: `dropped`, `done` (a linked job diff --git a/dw/server/jobs.py b/dw/server/jobs.py index 4e694ac2c..7d3b3ce85 100644 --- a/dw/server/jobs.py +++ b/dw/server/jobs.py @@ -718,9 +718,7 @@ def _linked(self, job_id, row, run_dir, output_dir): if run_dir: try: root = validate_output_path(output_dir or self.output_dir, None) - exists = os.path.isdir( - validate_path(os.path.join(root, run_dir), root, allow_create=True) - ) + exists = job_run_directory(root, run_dir) is not None except SecurityError: exists = False return { diff --git a/dw_mcp/diagnose.py b/dw_mcp/diagnose.py index d81b452a4..e0d45f47f 100644 --- a/dw_mcp/diagnose.py +++ b/dw_mcp/diagnose.py @@ -10,7 +10,6 @@ import logging import math import os -import re import time from dw_mcp.client import DwApiError, api_path, clip_note, workflow_source @@ -87,23 +86,19 @@ def _acknowledgement_body(acknowledged_cost): return {"acknowledged_cost": bool(acknowledged_cost)} -# The ledger's key rule, copied because dw_mcp imports no dw module -# (dw.security.validate_ledger_key) -LEDGER_KEY = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}\Z") - - def _ledger_link(request): """`"/"` as the POST body's `request` and `item`, - or None for no link. Refused here, before any HTTP call, when it is not - that form.""" + or None for no link. Refused here, before any HTTP call, when it has + not exactly one '/'. Each half's key rule is the server's alone + (dw.security.validate_ledger_key): a bad key is its 422, before + anything queues.""" if request is None or request == "": return None parts = request.split("/") if isinstance(request, str) else [] - if len(parts) != 2 or not all(LEDGER_KEY.match(part) for part in parts): + if len(parts) != 2: raise DwApiError( f'`request` must be "/": exactly one ' - f"'/', each half 1-64 of a-z, 0-9 and dash, starting with a " - f"letter or digit (got {request!r})." + f"'/' (got {request!r})." ) return {"request": parts[0], "item": parts[1]} diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index ead823532..bca4cb919 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -1721,7 +1721,7 @@ async def test_run_workflow_request_is_an_optional_nullable_string(): @pytest.mark.asyncio -@pytest.mark.parametrize("bad", ["demo", "a/b/c", "Demo/cat", "demo/", "/cat"]) +@pytest.mark.parametrize("bad", ["demo", "a/b/c", "demo//cat"]) async def test_run_workflow_refuses_a_malformed_request_before_any_call(bad): calls = [] @@ -1740,6 +1740,29 @@ def handler(request): assert calls == [] +@pytest.mark.asyncio +@pytest.mark.parametrize("key", ["Demo/cat", "demo/", "/cat"]) +async def test_run_workflow_leaves_the_key_rule_to_the_server(key): + # one owner of the key rule (dw.security.validate_ledger_key): the + # client splits on the one '/', and the server's 422 refuses the key + sent = [] + + def handler(request): + sent.append(json.loads(request.content)) + return httpx.Response( + 422, json={"detail": [{"msg": "Request must be a ledger key"}]} + ) + + with pytest.raises(Exception): + await server_over(handler).call_tool( + "run_workflow", + {"workflow_path": "w.json", "acknowledged_cost": True, "request": key}, + ) + + request_id, item = key.split("/") + assert [(body["request"], body["item"]) for body in sent] == [(request_id, item)] + + @pytest.mark.asyncio async def test_run_workflow_sends_the_request_and_item_split(): sent = [] From 1ca8db65c3d8fa41d2301848a6157f9b74107cc9 Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 18:34:26 -0600 Subject: [PATCH 307/412] feat(ui): #1483 - Requests UI: request page, chips, filters, breadcrumb and the comment box - Requests section (routes, sidebar, App) and an open-requests panel on the overview - Request page: prompt and goal, items in order with badge, thumbnail, attempts, estimate and a comment box; spent vs remaining; revision history - The comment box is the page's one edit: PUT at the read revision, stale 409 shown with a Reload - JobsPage `req` hash filter with a removable chip, and a request > item row chip - Gallery request filter chip - JobHeader breadcrumb to the request; "request no longer exists" on 404 - Ledger routes join the UI contract list; ui/CLAUDE.md sections; ARCHITECTURE row Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 1 + tests/test_api_contract.py | 3 + ui/CLAUDE.md | 6 + ui/src/App.svelte | 6 + ui/src/lib/Sidebar.svelte | 2 + ui/src/lib/api.ts | 57 +++++- ui/src/lib/cardMemory.test.ts | 6 +- ui/src/lib/gallery/RequestFilter.svelte | 80 ++++++++ ui/src/lib/job/JobHeader.svelte | 45 +++++ ui/src/lib/job/JobHeader.test.ts | 70 +++++++ ui/src/lib/pages/GalleryPage.svelte | 11 +- ui/src/lib/pages/GalleryPage.test.ts | 46 ++++- ui/src/lib/pages/JobsPage.svelte | 68 ++++++- ui/src/lib/pages/JobsPage.test.ts | 69 ++++++- ui/src/lib/pages/OverviewPage.svelte | 72 +++++-- ui/src/lib/pages/OverviewPage.test.ts | 45 +++++ ui/src/lib/pages/RequestPage.svelte | 200 ++++++++++++++++++ ui/src/lib/pages/RequestPage.test.ts | 219 ++++++++++++++++++++ ui/src/lib/pages/RequestsPage.svelte | 105 ++++++++++ ui/src/lib/pages/RequestsPage.test.ts | 48 +++++ ui/src/lib/request/RequestItem.svelte | 258 ++++++++++++++++++++++++ ui/src/lib/requestFilter.test.ts | 17 ++ ui/src/lib/requestFilter.ts | 16 ++ ui/src/lib/requestResult.ts | 41 ++++ ui/src/lib/routes.test.ts | 15 ++ ui/src/lib/routes.ts | 1 + ui/src/lib/serverinfo.ts | 4 +- ui/src/lib/types.ts | 9 + 28 files changed, 1493 insertions(+), 27 deletions(-) create mode 100644 ui/src/lib/gallery/RequestFilter.svelte create mode 100644 ui/src/lib/job/JobHeader.test.ts create mode 100644 ui/src/lib/pages/RequestPage.svelte create mode 100644 ui/src/lib/pages/RequestPage.test.ts create mode 100644 ui/src/lib/pages/RequestsPage.svelte create mode 100644 ui/src/lib/pages/RequestsPage.test.ts create mode 100644 ui/src/lib/request/RequestItem.svelte create mode 100644 ui/src/lib/requestFilter.test.ts create mode 100644 ui/src/lib/requestFilter.ts create mode 100644 ui/src/lib/requestResult.ts diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 138c850cd..447c778e6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -239,6 +239,7 @@ one to open. | The editors' document | `ui/src/lib/editorShell.svelte.ts`: `DocumentEditor` | The workflow and prompt editors keep one rule each for the view (remembered per editor), the JSON draft (a failed parse pins it), dirty against the last load or save, the save path, and the tab-close guard. | `ui/src/lib/editorShell.test.ts`, `ui/src/lib/pages/PromptEditorPage.test.ts`, `ui/src/lib/pages/EditorPage.test.ts` | | UI polling | `ui/src/lib/poll.ts`: `poll`, `sleep` | A page that refreshes on a timer starts it through `poll` and stops it with the function `poll` returns. | `ui/src/lib/poll.test.ts` | | Workspace state in the UI | `ui/src/lib/workspaceState.svelte.ts`: `workspace` | The current workspace is one `$state`; `api.ts` reads it from here, so the request layer imports no page state. | `import_cycles` in `ui/scripts/arch-metrics.mjs` | +| Requests in the UI | `ui/src/lib/pages/RequestPage.svelte`: `saveComment`, `ui/src/lib/request/RequestItem.svelte`, `ui/src/lib/requestFilter.ts`, `ui/src/lib/job/JobHeader.svelte` | The request page reads the ledger and edits nothing but an item's comment: it PUTs the plan back as read (no `prompt`) at the revision it read, `by: "user"`, and a 409 `stale_revision` is shown on the item with the draft kept, never retried over. Jobs and Gallery narrow to a request with one `req` hash value (`` or `/`, the server's `request`/`item` filters); a job's header links its request, as plain text with "request no longer exists" once `getRequest` is 404. | `ui/src/lib/pages/RequestPage.test.ts`, `ui/src/lib/job/JobHeader.test.ts`, `ui/src/lib/requestFilter.test.ts` | | The UI's response contract | `dw/server/api_models.py` (the models; it re-exports `dw/server/api_models_base.py`: `ApiModel`, `send_rejected_responses`, and the library routes' models in `dw/server/api_models_library.py`); `scripts/dump_openapi.py` | Every JSON route `api.ts` calls declares a response model, and `types.ts` re-exports the types generated from it (`ui/src/lib/generated/`). The payload does not change: an absent key stays absent (`response_model_exclude_unset`), a sometimes-sent key is `sometimes()`. Runtime is lenient - an undeclared key passes and a rejected response is logged and sent as built; tests, the e2e server and the dump run strict (`DW_STRICT_RESPONSES=1`). The document is generated under the FastAPI and Pydantic `constraints-openapi.txt` pins: CI installs them, and the dump refuses to write under others. | `tests/test_api_contract.py`, `tests/test_ui_twins.py::test_every_json_route_the_ui_calls_declares_its_response`, CI's "Response contract" step | | Where `--live` appears | `ui/src/app.css` (its header) | `--live` marks machine state only and `--select` the user's place only (focus ring, sidebar), each in the files `ui/scripts/design-rules.test.ts` lists. | `ui/scripts/design-rules.test.ts` | | UI architecture ratchet | `ui/scripts/arch-metrics.mjs` | No metric rises above `docs/stabilization/ui/baseline.json`. | the `ui` job in `.github/workflows/ci.yml`; `npm run preflight` | diff --git a/tests/test_api_contract.py b/tests/test_api_contract.py index 1aa93927a..36e3e7f8e 100644 --- a/tests/test_api_contract.py +++ b/tests/test_api_contract.py @@ -173,6 +173,9 @@ def test_the_committed_document_is_current(): ("get", "/api/workspaces"), ("post", "/api/workspaces"), ("delete", "/api/workspaces/{name}"), + ("get", "/api/workspaces/{name}/requests"), + ("get", "/api/workspaces/{name}/requests/{request_id}"), + ("put", "/api/workspaces/{name}/requests/{request_id}"), ("get", "/api/workflows"), ("put", "/api/workflows/{name}"), ("patch", "/api/workflows/{name}"), diff --git a/ui/CLAUDE.md b/ui/CLAUDE.md index 0090ac5c6..41570c86f 100644 --- a/ui/CLAUDE.md +++ b/ui/CLAUDE.md @@ -4,6 +4,12 @@ Guidance for the web UI single-page app. Build and dev setup are in ui/README.md Checks, from `ui/`: `npm run check`, `npm run lint`, `npm test`, and `npx playwright test` (it starts its own server - do not have `dw.serve` on the same port). Server response types come from `src/lib/generated/` - `python scripts/dump_openapi.py` then `npm run gen:api` - never written by hand. +## Sections + +A workspace's views are `#/ws//
`, listed in `WS_SECTIONS` (`src/lib/routes.ts`), routed in `src/App.svelte` and named in `src/lib/Sidebar.svelte`: overview, workflows, jobs, requests, gallery, compare, assets and edit. A new section goes in all three. + +- **requests**: the workspace's requests ledger. `requests/` is one request, whose only edit is an item's comment (`docs/ARCHITECTURE.md`, *Requests in the UI*). + ## Rules for new UI - Show the proof: a list of things that produce images shows the images. diff --git a/ui/src/App.svelte b/ui/src/App.svelte index 6b2d648b0..3e2282217 100644 --- a/ui/src/App.svelte +++ b/ui/src/App.svelte @@ -39,6 +39,8 @@ import WorkflowPage from './lib/pages/WorkflowPage.svelte' import JobsPage from './lib/pages/JobsPage.svelte' import JobPage from './lib/pages/JobPage.svelte' + import RequestsPage from './lib/pages/RequestsPage.svelte' + import RequestPage from './lib/pages/RequestPage.svelte' import EditorPage from './lib/pages/EditorPage.svelte' import PromptsPage from './lib/pages/PromptsPage.svelte' import PromptEditorPage from './lib/pages/PromptEditorPage.svelte' @@ -381,6 +383,10 @@ jobId={view.rest[0]} /> {:else if view.section === 'jobs'} + {:else if view.section === 'requests' && view.rest[0]} + {:else if view.section === 'requests'} {:else if view.section === 'workflows' && view.rest.length} diff --git a/ui/src/lib/Sidebar.svelte b/ui/src/lib/Sidebar.svelte index 805da98de..95191b77a 100644 --- a/ui/src/lib/Sidebar.svelte +++ b/ui/src/lib/Sidebar.svelte @@ -2,6 +2,7 @@ import { onMount, untrack } from 'svelte' import { BookCopy, + ClipboardList, ChevronDown, ChevronRight, Database, @@ -82,6 +83,7 @@ { section: 'overview', label: 'Overview', icon: LayoutDashboard }, { section: 'workflows', label: 'Workflows', icon: Layers }, { section: 'jobs', label: 'Jobs', icon: ListTodo }, + { section: 'requests', label: 'Requests', icon: ClipboardList }, { section: 'gallery', label: 'Gallery', icon: Images }, { section: 'assets', label: 'Assets', icon: FolderOpen }, { section: 'edit', label: 'Editor', icon: SquarePen }, diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 76fde7eeb..35123f01b 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -23,6 +23,9 @@ import type { JobMoved, JobWorkflow, Kept, + LedgerItem, + LedgerList, + LedgerRequest, LoraList, MemoryInfo, ModelCache, @@ -169,6 +172,18 @@ function isValidateRequest( ) } +/** A request's plan as PUT sends it: the read view's items go back as they + * came (the server ignores their derived fields), `prompt` is left out + * because it is write-once. */ +export type RequestWriteBody = { + title: string + goal: string + items: LedgerItem[] + revision: number + why: string + state?: LedgerRequest['state'] +} + export const api = { listWorkflows: () => request('/api/workflows'), /** The workflow plus where it came from, read off the response headers @@ -188,10 +203,20 @@ export const api = { // workspace and a workspace's Jobs page can name its own. `status` is one // state or a comma-separated set ('succeeded,failed,cancelled'); `limit` // keeps the newest N of what matched. - listJobs: (workspace?: string, limit?: number, status?: string) => { + // `requestId` (with `item`) narrows to the jobs linked to a requests-ledger + // request, or one item of it + listJobs: ( + workspace?: string, + limit?: number, + status?: string, + requestId?: string, + item?: string, + ) => { const query = new URLSearchParams() if (workspace) query.set('workspace', workspace) if (status) query.set('status', status) + if (requestId) query.set('request', requestId) + if (requestId && item) query.set('item', item) if (limit) query.set('limit', String(limit)) const qs = query.toString() return request(qs ? `/api/jobs?${qs}` : '/api/jobs', undefined, { @@ -355,9 +380,12 @@ export const api = { // `roles` narrows to those roles server-side (repeated `role` parameters; // a null role counts as final there). The page filters on the client, so // it asks for none - gallery: (roles?: string[]) => { + // `requestId` narrows to the runs whose job is linked to that + // requests-ledger request (in the selected workspace) + gallery: (roles?: string[], requestId?: string) => { const params = new URLSearchParams({ limit: '100000' }) for (const role of roles ?? []) params.append('role', role) + if (requestId) params.set('request', requestId) return request(`/api/gallery?${params}`) }, // `workspace`, when given, names the file's own workspace and wins over @@ -420,6 +448,31 @@ export const api = { request(`/api/assets/${encodePath(name)}`, { method: 'DELETE', }), + // The requests ledger. Unscoped: the workspace is in the path + listRequests: (workspace: string) => + request( + `/api/workspaces/${encodeURIComponent(workspace)}/requests`, + undefined, + { scope: false }, + ), + getRequest: (workspace: string, id: string) => + request( + `/api/workspaces/${encodeURIComponent(workspace)}/requests/${encodeURIComponent(id)}`, + undefined, + { scope: false }, + ), + /** Write the whole plan back as read, at the revision it was read at, + * by the user. A stale revision is a 409 ApiError. */ + putRequest: (workspace: string, id: string, body: RequestWriteBody) => + request( + `/api/workspaces/${encodeURIComponent(workspace)}/requests/${encodeURIComponent(id)}`, + { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ by: 'user', ...body }), + }, + { scope: false }, + ), listWorkspaces: () => request('/api/workspaces'), createWorkspace: (name: string) => request('/api/workspaces', { diff --git a/ui/src/lib/cardMemory.test.ts b/ui/src/lib/cardMemory.test.ts index ce97e8839..e6b6bc73b 100644 --- a/ui/src/lib/cardMemory.test.ts +++ b/ui/src/lib/cardMemory.test.ts @@ -54,7 +54,11 @@ it('shows free only when the card reported a total, and reserved when available' const a = card('cuda:0', 1024) const withFree = { ...a, - info: { ...a.info, gpu_memory_free_mb: 20480, gpu_memory_reserved_mb: 2048 }, + info: { + ...a.info, + gpu_memory_free_mb: 20480, + gpu_memory_reserved_mb: 2048, + }, } const unmeasured = { ...card('cuda:1', 1024), diff --git a/ui/src/lib/gallery/RequestFilter.svelte b/ui/src/lib/gallery/RequestFilter.svelte new file mode 100644 index 000000000..694de1eab --- /dev/null +++ b/ui/src/lib/gallery/RequestFilter.svelte @@ -0,0 +1,80 @@ + + +{#if request} + + request {request} + + +{:else if requests.length} + +{/if} + + diff --git a/ui/src/lib/job/JobHeader.svelte b/ui/src/lib/job/JobHeader.svelte index c0b0ff598..a3bee075e 100644 --- a/ui/src/lib/job/JobHeader.svelte +++ b/ui/src/lib/job/JobHeader.svelte @@ -38,6 +38,34 @@ declared?: Record | null } = $props() + // The request this job was run for (requests ledger). `gone` once the + // server says 404 - the request or its whole workspace was deleted; while + // it loads, or on any other error, the link shows + let requestTitle = $state('') + let requestGone = $state(false) + // Derived primitives, so a poll that replaces `job` with an equal one + // does not fetch the request again + const requestWs = $derived(job?.workspace) + const requestId = $derived(job?.request) + $effect(() => { + const ws = requestWs + const id = requestId + requestTitle = '' + requestGone = false + if (!ws || !id) return + let live = true + api.getRequest(ws, id).then( + (found) => { + if (live) requestTitle = found.title + }, + (e) => { + if (live && e instanceof ApiError && e.status === 404) + requestGone = true + }, + ) + return () => (live = false) + }) + // What a rerun changed, as the server stored it: absent on a plain rerun const overrideKeys = $derived(Object.keys(job?.overrides ?? {})) @@ -156,6 +184,23 @@ > {/if} {/if} + {#if job.request} + + {#if requestGone} + {job.request}{job.item ? ` › ${job.item}` : ''} + request no longer exists + {:else} + {job.request}{job.item ? ` › ${job.item}` : ''} + {/if} + + {/if} {#if cancelPending} { + const real = await original() + return { ApiError: real.ApiError, api: { getRequest: vi.fn() } } +}) +vi.mock('../toast', () => ({ notify: { error: vi.fn(), success: vi.fn() } })) + +afterEach(() => { + cleanup() + vi.mocked(api.getRequest).mockReset() +}) + +const job = (over: Partial = {}): JobDetail => + ({ + id: 'j1', + workflow: 'tiny', + workspace: 'default', + status: 'succeeded', + ...over, + }) as JobDetail + +const header = (j: JobDetail) => + render(JobHeader, { + job: j, + jobId: j.id, + seed: undefined, + runVersion: undefined, + running: false, + cancelPending: false, + seedVariable: null, + }) + +it('links request › item to the request page, titled with the request', async () => { + vi.mocked(api.getRequest).mockResolvedValue({ + id: 'r1', + title: 'Spring campaign', + } as never) + header(job({ request: 'r1', item: 'hero' })) + const link = screen.getByRole('link', { name: 'r1 › hero' }) + expect(link.getAttribute('href')).toBe('#/ws/default/requests/r1') + await waitFor(() => + expect(link.getAttribute('title')).toBe('Spring campaign'), + ) + expect(api.getRequest).toHaveBeenCalledWith('default', 'r1') +}) + +it('shows plain text, no link, once the request is gone', async () => { + vi.mocked(api.getRequest).mockRejectedValue(new ApiError('gone', 404)) + header(job({ request: 'r1', item: 'hero', workspace: 'old (deleted)' })) + await waitFor(() => + expect(screen.getByText('request no longer exists')).toBeTruthy(), + ) + expect(screen.queryByRole('link', { name: /r1/ })).toBeNull() + expect(screen.getByText('r1 › hero')).toBeTruthy() +}) + +it('keeps the link on other errors, and shows nothing for an unlinked job', async () => { + vi.mocked(api.getRequest).mockRejectedValue(new ApiError('boom', 500)) + header(job({ request: 'r1', item: 'hero' })) + await waitFor(() => expect(api.getRequest).toHaveBeenCalled()) + expect(screen.getByRole('link', { name: 'r1 › hero' })).toBeTruthy() + cleanup() + header(job()) + expect(screen.queryByText(/›/)).toBeNull() +}) diff --git a/ui/src/lib/pages/GalleryPage.svelte b/ui/src/lib/pages/GalleryPage.svelte index 9b1127734..ed551dbee 100644 --- a/ui/src/lib/pages/GalleryPage.svelte +++ b/ui/src/lib/pages/GalleryPage.svelte @@ -19,6 +19,7 @@ } from '../types' import { workspace } from '../workspace.svelte' import { go } from '../router.svelte' + import RequestFilter from '../gallery/RequestFilter.svelte' import GalleryDetail from '../gallery/GalleryDetail.svelte' import { AssessCache } from '../gallery/assess.svelte' import RoleTag from '../gallery/RoleTag.svelte' @@ -49,9 +50,13 @@ const assessCache = new AssessCache() let inputs = $state([]) + // The requests-ledger request the gallery is narrowed to (RequestFilter + // keeps it in step with the hash); the listing asks the server for it + let reqId = $state('') + function loadListing() { return api - .gallery() + .gallery(undefined, reqId || undefined) .then((result) => { files = result.files // The editors' output: completions read the same listing @@ -67,6 +72,7 @@ $effect(() => { // Read inside the effect so switching workspaces refetches the gallery void workspace.current + void reqId void loadListing() }) @@ -74,7 +80,7 @@ const roleOf = (f: GalleryFile): OutputRole => f.role ?? 'final' let starredOnly = $state(false) const filterActive = $derived( - filter !== '' || roles.length < 2 || starredOnly, + filter !== '' || roles.length < 2 || starredOnly || reqId !== '', ) // Finals lead inside a run only: the server's order (newest first) holds // between runs, so runs sit where their newest file put them. The sort is @@ -321,6 +327,7 @@ title="only the files you starred">Starred + {#if error}

Could not read the gallery: {error}

{/if} diff --git a/ui/src/lib/pages/GalleryPage.test.ts b/ui/src/lib/pages/GalleryPage.test.ts index e67fe8c1d..e3df02aeb 100644 --- a/ui/src/lib/pages/GalleryPage.test.ts +++ b/ui/src/lib/pages/GalleryPage.test.ts @@ -37,8 +37,18 @@ const listing = vi.hoisted(() => ({ files: [] as GalleryFile[] })) // Resolves on a macrotask so that a re-triggering effect cannot starve the // timers this test waits on - the failure then shows as a call count +const listRequests = vi.hoisted(() => + vi.fn(() => + Promise.resolve({ + workspace: 'default', + requests: [{ id: 'r1', title: 'Spring campaign' }] as unknown[], + }), + ), +) const gallery = vi.hoisted(() => - vi.fn( + vi.fn< + (roles?: string[], request?: string) => Promise<{ files: GalleryFile[] }> + >( () => new Promise<{ files: GalleryFile[] }>((resolve) => setTimeout(() => resolve({ files: listing.files }), 0), @@ -61,7 +71,8 @@ const galleryMetadata = vi.hoisted(() => vi.mock('../api', () => ({ setNote: (t: string, n: string | null) => setNote(t, n), api: { - gallery: () => gallery(), + gallery: (roles?: string[], request?: string) => gallery(roles, request), + listRequests: () => listRequests(), galleryThumbnailUrl: (name: string) => `/thumb/${name}`, galleryUrl: (name: string) => `/outputs/${name}`, outputDownloadUrl: (name: string) => `/download/${name}`, @@ -84,6 +95,7 @@ afterEach(() => { // queries find two of everything cleanup() gallery.mockClear() + location.hash = '#/ws/default/gallery' deleteOutput.mockClear() setStarred.mockClear() archiveOutputs.mockClear() @@ -629,3 +641,33 @@ it("shows the open file's level findings from its metadata", async () => { const region = await screen.findByRole('region', { name: 'Findings' }) await waitFor(() => expect(region.textContent).toContain('near-silent')) }) + +it('with req in the hash, asks for that request and shows a removable chip', async () => { + location.hash = '#/ws/default/gallery?req=r1' + await renderGallery() + expect(gallery).toHaveBeenLastCalledWith(undefined, 'r1') + const chip = screen.getByTestId('req-filter') + expect(chip.querySelector('a')?.getAttribute('href')).toBe( + '#/ws/default/requests/r1', + ) + await fireEvent.click(screen.getByLabelText('remove the request filter')) + await waitFor(() => + expect(gallery).toHaveBeenLastCalledWith(undefined, undefined), + ) + expect(screen.queryByTestId('req-filter')).toBeNull() +}) + +it('offers a request picker, and picking one reloads narrowed', async () => { + await renderGallery() + const picker = await screen.findByLabelText('filter by request') + await fireEvent.change(picker, { target: { value: 'r1' } }) + await waitFor(() => expect(gallery).toHaveBeenLastCalledWith(undefined, 'r1')) + expect(screen.getByTestId('req-filter')).toBeTruthy() +}) + +it('hides the picker when the workspace has no requests', async () => { + listRequests.mockResolvedValueOnce({ workspace: 'default', requests: [] }) + await renderGallery() + await Promise.resolve() + expect(screen.queryByLabelText('filter by request')).toBeNull() +}) diff --git a/ui/src/lib/pages/JobsPage.svelte b/ui/src/lib/pages/JobsPage.svelte index 6d01c82d0..156aedbb6 100644 --- a/ui/src/lib/pages/JobsPage.svelte +++ b/ui/src/lib/pages/JobsPage.svelte @@ -4,13 +4,14 @@ import { queueWait } from '../jobTimes' import { poll } from '../poll' import { onMount } from 'svelte' - import { ChevronDown, ChevronUp, ChevronsUp, Inbox } from '@lucide/svelte' + import { ChevronDown, ChevronUp, ChevronsUp, Inbox, X } from '@lucide/svelte' import { api } from '../api' import Empty from '../Empty.svelte' import { notify } from '../toast' import type { JobSummary } from '../types' import { wsHref } from '../routes' import { hashQuery, setHashQuery } from '../router.svelte' + import { parseRequestFilter } from '../requestFilter' import { loadWorkspaces, workspace } from '../workspace.svelte' import { rerunRestartBatchWithConfirm, @@ -33,12 +34,17 @@ // point of that view; a workspace's own Jobs page filters by // `workspace.current` instead. let workspaceFilter = $state(initial.ws ?? '') + // Server-side too: `req=` or `req=/` asks the server for + // the jobs linked to that requests-ledger request (or one item of it) + let reqFilter = $state(initial.req ?? '') + const requestScope = $derived(parseRequestFilter(reqFilter)) $effect(() => setHashQuery({ status: statusFilter, q: nameFilter, ws: scope === 'all' ? workspaceFilter : '', + req: reqFilter, }), ) // The route's view is unchanged when the Jobs nav link lands on the bare @@ -50,18 +56,31 @@ statusFilter = query.status ?? '' nameFilter = query.q ?? '' workspaceFilter = query.ws ?? '' + reqFilter = query.req ?? '' } window.addEventListener('hashchange', sync) return () => window.removeEventListener('hashchange', sync) }) const filtered = $derived( - !!statusFilter || !!nameFilter || (scope === 'all' && !!workspaceFilter), + !!statusFilter || + !!nameFilter || + !!requestScope.request || + (scope === 'all' && !!workspaceFilter), ) function clearFilters() { statusFilter = '' nameFilter = '' workspaceFilter = '' + reqFilter = '' } + const listJobs = (filter: string) => + api.listJobs( + filter || undefined, + undefined, + undefined, + requestScope.request || undefined, + requestScope.item || undefined, + ) // Only worth a picker once there is a choice - a single-workspace server // has nothing to filter by @@ -80,9 +99,10 @@ // the filter (or the scope's own workspace) changes, rather than the // interval quietly polling stale const filter = scope === 'all' ? workspaceFilter : workspace.current + void requestScope return poll(async () => { try { - jobs = (await api.listJobs(filter || undefined)).jobs.reverse() + jobs = (await listJobs(filter)).jobs.reverse() error = '' } catch (e) { error = e instanceof Error ? e.message : String(e) @@ -131,13 +151,15 @@ // Same filter the poll uses - refreshing without it would flash every // workspace's jobs into a view the user had narrowed to one const filter = scope === 'all' ? workspaceFilter : workspace.current - jobs = (await api.listJobs(filter || undefined)).jobs.reverse() + jobs = (await listJobs(filter)).jobs.reverse() } catch (e) { const msg = e instanceof Error ? e.message : String(e) notify.error(msg) } } + const requestLabel = (f: { request: string; item: string }) => + f.item ? `${f.request} › ${f.item}` : f.request const when = (t: number | null) => (t ? formatMtime(t) : '—') const waitOf = (job: JobSummary) => queueWait(job, Date.now() / 1000) // The row shows the compact start; hovering gives it to the second, with @@ -184,6 +206,27 @@ placeholder="filter by workflow…" bind:value={nameFilter} /> + {#if requestScope.request} + + {requestLabel(requestScope)} + + + {/if} {#if error}

Could not reach the server: {error}

{/if} @@ -240,6 +283,18 @@ >rerun
{/if} + {#if job.request} + {requestLabel({ + request: job.request, + item: job.item ?? '', + })} + {/if} {#if scope === 'all' && (workspace.names?.length ?? 0) > 1} {job.workspace} @@ -441,6 +496,11 @@ border-radius: 4px; padding: 0 0.3rem; } + .active-filter { + display: inline-flex; + align-items: center; + gap: 0.25rem; + } .qmove { display: inline-flex; gap: 0.1rem; diff --git a/ui/src/lib/pages/JobsPage.test.ts b/ui/src/lib/pages/JobsPage.test.ts index 5072e9756..d56f4b65f 100644 --- a/ui/src/lib/pages/JobsPage.test.ts +++ b/ui/src/lib/pages/JobsPage.test.ts @@ -18,8 +18,20 @@ const data = vi.hoisted(() => ({ vi.mock('../api', () => ({ api: { rerunRestartBatch: data.rerunRestartBatch, - listJobs: () => - Promise.resolve({ jobs: [...data.jobs], total: data.jobs.length }), + // Filters by request/item the way the server does + listJobs: ( + _ws?: string, + _limit?: number, + _status?: string, + request?: string, + item?: string, + ) => { + const jobs = (data.jobs as JobSummary[]).filter( + (j) => + (!request || j.request === request) && (!item || j.item === item), + ) + return Promise.resolve({ jobs, total: jobs.length }) + }, // The listing names the default workspace, as the server's always does: // a route parse that found it missing would redirect to overview listWorkspaces: () => @@ -394,3 +406,56 @@ it('an empty preview says so, with Close only, and hides the banner', async () = // only the preview: nothing was queued expect(data.rerunRestartBatch.mock.calls).toEqual([['t1']]) }) + +const linked = () => [ + summary({ id: 'a', workflow: 'wf-a', request: 'r1', item: 'hero' }), + summary({ id: 'b', workflow: 'wf-b', request: 'r1', item: 'alt' }), + summary({ id: 'c', workflow: 'wf-c' }), +] + +it('chips a linked job with request › item and leaves an unlinked one bare', async () => { + location.hash = '#/ws/default/jobs' + data.jobs = linked() + render(JobsPage) + await waitFor(() => expect(screen.getByText('wf-c')).toBeTruthy()) + expect(screen.getByText('r1 › hero')).toBeTruthy() + expect(screen.getAllByText(/r1 ›/)).toHaveLength(2) +}) + +it('narrows to a request, then to one item, and clearing restores the list', async () => { + location.hash = '#/ws/default/jobs?req=r1' + data.jobs = linked() + render(JobsPage) + await waitFor(() => expect(screen.getByText('wf-a')).toBeTruthy()) + expect(screen.queryByText('wf-c')).toBeNull() + expect(screen.getByText('wf-b')).toBeTruthy() + const chip = screen.getByTestId('req-filter') + expect(chip.querySelector('a')?.getAttribute('href')).toBe( + '#/ws/default/requests/r1', + ) + cleanup() + + location.hash = '#/ws/default/jobs?req=r1%2Fhero' + render(JobsPage) + await waitFor(() => expect(screen.getByText('wf-a')).toBeTruthy()) + expect(screen.queryByText('wf-b')).toBeNull() + + await fireEvent.click(screen.getByLabelText('remove the request filter')) + await waitFor(() => expect(screen.getByText('wf-c')).toBeTruthy()) + expect(screen.getByText('wf-b')).toBeTruthy() + expect(screen.queryByTestId('req-filter')).toBeNull() +}) + +it('a req that arrives on the hash refetches at once, not on the next tick', async () => { + location.hash = '#/ws/default/jobs' + data.jobs = linked() + render(JobsPage) + await waitFor(() => expect(screen.getByText('wf-c')).toBeTruthy()) + location.hash = '#/ws/default/jobs?req=r1%2Falt' + window.dispatchEvent(new HashChangeEvent('hashchange')) + await waitFor(() => expect(screen.queryByText('wf-a')).toBeNull(), { + timeout: 1000, + }) + expect(screen.getByText('wf-b')).toBeTruthy() + expect(screen.queryByText('wf-c')).toBeNull() +}) diff --git a/ui/src/lib/pages/OverviewPage.svelte b/ui/src/lib/pages/OverviewPage.svelte index b44f1575e..bf848b0da 100644 --- a/ui/src/lib/pages/OverviewPage.svelte +++ b/ui/src/lib/pages/OverviewPage.svelte @@ -1,5 +1,6 @@ + +

all requests

+ +{#if missing} +

This request no longer exists.

+{:else if error} +

Could not load the request: {error}

+{:else if request === null} + +{:else} +
+

{request.title}

+ {request.state} + revision {request.revision} +
+

+ {request.id} · + its jobs + · + its outputs +

+ + {#if request.prompt} +
+

Asked

+

{request.prompt}

+
+ {/if} +
+

Goal

+

{request.goal}

+

+ {formatMinutes(request.spent_minutes)} spent · {formatMinutes( + request.remaining_minutes, + )} remaining +

+
+ +

Items

+
    + {#each request.items as item (item.key)} + saveComment(item.key, text)} + onreload={load} + /> + {/each} +
+ +

History

+
    + {#each history as entry (entry.revision)} +
  • + r{entry.revision} + {when(entry.at)} + {entry.by} + {entry.why} + {#if entry.goal}

    + goal: {entry.goal} +

    {/if} +
  • + {/each} +
+{/if} + + diff --git a/ui/src/lib/pages/RequestPage.test.ts b/ui/src/lib/pages/RequestPage.test.ts new file mode 100644 index 000000000..2d46be1f1 --- /dev/null +++ b/ui/src/lib/pages/RequestPage.test.ts @@ -0,0 +1,219 @@ +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/svelte' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import RequestPage from './RequestPage.svelte' +import { workspace } from '../workspaceState.svelte' +import type { LedgerRequest } from '../types' + +const data = vi.hoisted(() => ({ + request: null as unknown, + getError: null as { status: number; message: string } | null, + getJob: vi.fn(), + putRequest: vi.fn(), +})) +vi.mock('../api', () => ({ + ApiError: class ApiError extends Error { + status: number + constructor(message: string, status = 500) { + super(message) + this.name = 'ApiError' + this.status = status + } + }, + outputUrl: (path: string) => `/outputs/${path}`, + api: { + getRequest: vi.fn(async () => { + if (data.getError) { + const { ApiError } = await import('../api') + throw new ApiError(data.getError.message, data.getError.status) + } + return data.request + }), + getJob: (id: string) => data.getJob(id), + putRequest: (...args: unknown[]) => data.putRequest(...args), + }, +})) +vi.mock('../toast', () => ({ notify: { error: vi.fn(), success: vi.fn() } })) + +const make = (): LedgerRequest => + ({ + id: 'r1', + title: 'Launch posters', + state: 'open', + revision: 3, + prompt: 'make me\n three posters', + goal: 'Three finished posters', + spent_minutes: 5, + remaining_minutes: 7, + items: [ + { + key: 'a', + title: 'First poster', + depends_on: [], + estimate_minutes: 2, + workflow: 'poster', + arguments: {}, + dropped: false, + accepted: null, + comment: { text: 'nice', at: '2026-01-02T03:04:05Z' }, + status: 'done', + attempts: [{ job: 'job-a', status: 'succeeded', minutes: 1.5 }], + result: { job: 'job-a', run_id: 'run-a' }, + spent_minutes: 1.5, + }, + { + key: 'b', + title: 'Second poster', + depends_on: ['a'], + estimate_minutes: null, + workflow: 'poster', + arguments: {}, + dropped: false, + accepted: null, + comment: null, + status: 'planned', + attempts: [], + result: null, + spent_minutes: 0, + }, + ], + history: [ + { + revision: 1, + at: '2026-01-01T00:00:00Z', + by: 'agent', + why: 'opened', + goal: 'First goal', + }, + { revision: 3, at: '2026-01-03T00:00:00Z', by: 'user', why: 'commented' }, + ], + }) as unknown as LedgerRequest + +beforeEach(() => { + workspace.current = 'studio' + data.request = make() + data.getError = null + data.getJob.mockReset() + data.getJob.mockResolvedValue({ + id: 'job-a', + workspace: 'studio', + manifest: [{ step: 's', files: ['a.png'], role: 'final', reused: false }], + output_kinds: { 'a.png': 'image' }, + }) + data.putRequest.mockReset() +}) +afterEach(cleanup) + +it('renders the ask, items in order with badges, attempts, totals and history', async () => { + const { container } = render(RequestPage, { requestId: 'r1' }) + await screen.findByText('Launch posters') + expect(screen.getByText(/three posters/).textContent).toBe( + 'make me\n three posters', + ) + expect(screen.getByText('Three finished posters')).toBeTruthy() + const titles = [...container.querySelectorAll('.item .title')].map( + (e) => e.textContent, + ) + expect(titles).toEqual(['First poster', 'Second poster']) + const badges = [...container.querySelectorAll('.item .status')].map( + (e) => e.textContent, + ) + expect(badges).toEqual(['done', 'planned']) + expect(screen.getByText(/est\. ~2 min/)).toBeTruthy() + expect(screen.getByText(/est\. —/)).toBeTruthy() + expect(screen.getByRole('link', { name: 'job-a' }).getAttribute('href')).toBe( + '#/ws/studio/jobs/job-a', + ) + expect(screen.getByText(/~5 min spent/)).toBeTruthy() + expect(screen.getByText(/~7 min remaining/)).toBeTruthy() + const history = [...container.querySelectorAll('.history li')].map( + (e) => e.querySelector('.num')?.textContent, + ) + expect(history).toEqual(['r3', 'r1']) + expect(screen.getByText(/goal: First goal/)).toBeTruthy() + // the result thumbnail links to the job + await waitFor(() => + expect(container.querySelector('.result img')?.getAttribute('src')).toBe( + '/outputs/a.png', + ), + ) +}) + +it('says a missing request no longer exists', async () => { + data.getError = { status: 404, message: 'not found' } + render(RequestPage, { requestId: 'gone' }) + await screen.findByText(/no longer exists/i) +}) + +async function openComment(label: string) { + await screen.findByText('Launch posters') + const buttons = screen.getAllByRole('button', { name: label }) + return buttons[0] +} + +it('saves a comment at the read revision, changing only that item', async () => { + data.putRequest.mockImplementation((_ws, _id, body) => + Promise.resolve({ ...make(), revision: body.revision + 1 }), + ) + render(RequestPage, { requestId: 'r1' }) + await fireEvent.click(await openComment('Add comment')) + const box = screen.getByLabelText('Comment on b') + await fireEvent.input(box, { target: { value: 'needs more red' } }) + await fireEvent.click(screen.getByRole('button', { name: 'Save' })) + await waitFor(() => expect(data.putRequest).toHaveBeenCalled()) + const [ws, id, body] = data.putRequest.mock.calls[0] + expect(ws).toBe('studio') + expect(id).toBe('r1') + expect(body).not.toHaveProperty('prompt') + expect(body).toMatchObject({ + title: 'Launch posters', + goal: 'Three finished posters', + revision: 3, + why: 'comment on b', + state: 'open', + }) + const expected = make().items + expect(body.items[0]).toEqual(expected[0]) + expect(body.items[1]).toEqual({ + ...expected[1], + comment: { text: 'needs more red' }, + }) + await screen.findByText('revision 4') +}) + +it('a stale write shows the message and keeps the draft', async () => { + const { ApiError } = await import('../api') + data.putRequest.mockRejectedValue( + new ApiError( + 'This request changed since you opened it (now revision 5) — reload to see it', + 409, + ), + ) + render(RequestPage, { requestId: 'r1' }) + await fireEvent.click(await openComment('Add comment')) + const box = screen.getByLabelText('Comment on b') as HTMLTextAreaElement + await fireEvent.input(box, { target: { value: 'my draft' } }) + await fireEvent.click(screen.getByRole('button', { name: 'Save' })) + await screen.findByText(/now revision 5/) + expect(screen.getByRole('button', { name: 'Reload' })).toBeTruthy() + expect( + (screen.getByLabelText('Comment on b') as HTMLTextAreaElement).value, + ).toBe('my draft') +}) + +it('links to its jobs and outputs through the req filter', async () => { + data.request = make() + render(RequestPage, { requestId: 'r1' }) + const jobs = await screen.findByText('its jobs') + expect(jobs.getAttribute('href')).toBe( + `#/ws/${workspace.current}/jobs?req=r1`, + ) + expect(screen.getByText('its outputs').getAttribute('href')).toBe( + `#/ws/${workspace.current}/gallery?req=r1`, + ) +}) diff --git a/ui/src/lib/pages/RequestsPage.svelte b/ui/src/lib/pages/RequestsPage.svelte new file mode 100644 index 000000000..4c6d0e2aa --- /dev/null +++ b/ui/src/lib/pages/RequestsPage.svelte @@ -0,0 +1,105 @@ + + +

Requests

+

+ What was asked for in this workspace, as a plan of items and the jobs made for + each. +

+ +{#if error} +

Could not load requests: {error}

+{:else if requests === null} + +{:else if requests.length === 0} + {#snippet icon()}{/snippet}No + requests yet — an agent opens one with set_request. +{:else} +
    + {#each requests as req (req.id)} +
  • +
    + {req.title} + {req.state} +
    +
    + {req.id} + {req.items} {req.items === 1 ? 'item' : 'items'} + {#if statusCounts(req.status_counts)}{statusCounts(req.status_counts)}{/if} + {formatMinutes(req.spent_minutes)} spent · {formatMinutes( + req.remaining_minutes, + )} remaining +
    +
  • + {/each} +
+{/if} + + diff --git a/ui/src/lib/pages/RequestsPage.test.ts b/ui/src/lib/pages/RequestsPage.test.ts new file mode 100644 index 000000000..b32812cc4 --- /dev/null +++ b/ui/src/lib/pages/RequestsPage.test.ts @@ -0,0 +1,48 @@ +import { cleanup, render, screen, waitFor } from '@testing-library/svelte' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import RequestsPage from './RequestsPage.svelte' +import { workspace } from '../workspaceState.svelte' + +const data = vi.hoisted(() => ({ requests: [] as unknown[] })) +vi.mock('../api', () => ({ + api: { + listRequests: () => + Promise.resolve({ workspace: 'studio', requests: data.requests }), + }, +})) + +beforeEach(() => { + workspace.current = 'studio' +}) +afterEach(cleanup) + +it('lists each request with a link, counts and minutes', async () => { + data.requests = [ + { + id: 'r1', + title: 'Launch posters', + state: 'open', + revision: 2, + items: 3, + status_counts: { done: 2, planned: 1 }, + spent_minutes: 4, + remaining_minutes: 2, + updated_at: null, + }, + ] + render(RequestsPage) + const link = await screen.findByRole('link', { name: 'Launch posters' }) + expect(link.getAttribute('href')).toBe('#/ws/studio/requests/r1') + expect(screen.getByText('r1')).toBeTruthy() + expect(screen.getByText('open')).toBeTruthy() + expect(screen.getByText('3 items')).toBeTruthy() + expect(screen.getByText('2 done · 1 planned')).toBeTruthy() + expect(screen.getByText(/~4 min spent/)).toBeTruthy() + expect(screen.getByText(/~2 min remaining/)).toBeTruthy() +}) + +it('says how requests get opened when there are none', async () => { + data.requests = [] + render(RequestsPage) + await waitFor(() => expect(screen.getByText(/set_request/)).toBeTruthy()) +}) diff --git a/ui/src/lib/request/RequestItem.svelte b/ui/src/lib/request/RequestItem.svelte new file mode 100644 index 000000000..ff810e153 --- /dev/null +++ b/ui/src/lib/request/RequestItem.svelte @@ -0,0 +1,258 @@ + + +
  • +
    + {item.status} + {item.title} + {item.key} + + est. {item.estimate_minutes == null + ? '—' + : formatMinutes(item.estimate_minutes)} +
    + +
    + {#if thumb && item.result} + + result of {item.title} + + {/if} +
    + {#if item.depends_on?.length} +

    + depends on {#each item.depends_on as dep, i (dep)}{#if i}, + {/if}{dep}{/each} +

    + {/if} + {#if item.accepted_missing} +

    + accepted run missing — showing the latest succeeded run instead +

    + {/if} + {#if item.attempts.length} +
      + {#each item.attempts as attempt (attempt.job)} +
    • + {attempt.job} + {attempt.status} + {attempt.minutes == null + ? '—' + : formatMinutes(attempt.minutes)} + {#if attempt.note}{attempt.note}{/if} +
    • + {/each} +
    + {/if} + +
    + {#if editing} + +
    + + +
    + {#if stale} + + {/if} + {:else} + {#if item.comment} +

    {item.comment.text}

    +

    + {formatExact(Date.parse(item.comment.at) / 1000)} +

    + {/if} + + {/if} +
    +
    +
    +
  • + + diff --git a/ui/src/lib/requestFilter.test.ts b/ui/src/lib/requestFilter.test.ts new file mode 100644 index 000000000..3ebbf6e77 --- /dev/null +++ b/ui/src/lib/requestFilter.test.ts @@ -0,0 +1,17 @@ +import { expect, it } from 'vitest' +import { formatRequestFilter, parseRequestFilter } from './requestFilter' + +it('parses a request id with and without an item', () => { + expect(parseRequestFilter('r1')).toEqual({ request: 'r1', item: '' }) + expect(parseRequestFilter('r1/shot-2')).toEqual({ + request: 'r1', + item: 'shot-2', + }) + expect(parseRequestFilter(undefined)).toEqual({ request: '', item: '' }) +}) + +it('formats what it parses, and nothing without a request', () => { + expect(formatRequestFilter({ request: 'r1', item: 'a' })).toBe('r1/a') + expect(formatRequestFilter({ request: 'r1', item: '' })).toBe('r1') + expect(formatRequestFilter({ request: '', item: 'a' })).toBe('') +}) diff --git a/ui/src/lib/requestFilter.ts b/ui/src/lib/requestFilter.ts new file mode 100644 index 000000000..8623f50c6 --- /dev/null +++ b/ui/src/lib/requestFilter.ts @@ -0,0 +1,16 @@ +// The `req` hash filter shared by the Jobs and Gallery pages: `` is a +// whole requests-ledger request, `/` one item of it. Ids and item +// keys are slugs, so the first `/` is the separator. +export type RequestFilter = { request: string; item: string } + +export function parseRequestFilter(value: string | undefined): RequestFilter { + const text = (value ?? '').trim() + const slash = text.indexOf('/') + if (slash < 0) return { request: text, item: '' } + return { request: text.slice(0, slash), item: text.slice(slash + 1) } +} + +export function formatRequestFilter(filter: RequestFilter): string { + if (!filter.request) return '' + return filter.item ? `${filter.request}/${filter.item}` : filter.request +} diff --git a/ui/src/lib/requestResult.ts b/ui/src/lib/requestResult.ts new file mode 100644 index 000000000..71f7c8096 --- /dev/null +++ b/ui/src/lib/requestResult.ts @@ -0,0 +1,41 @@ +import { groupResultFiles } from './results' +import type { JobDetail, LedgerItemStatus } from './types' + +const IMAGE_EXT = /\.(png|jpe?g|webp|gif)$/i + +/** The one image that stands for a job in a request: the first image of its + * final step (or of any step, for a run whose manifest names no roles). Null + * when the job made none. */ +export function firstImage(job: JobDetail): string | null { + const groups = groupResultFiles(job.manifest, []) + const ordered = [ + ...groups.filter((g) => g.role === 'final'), + ...groups.filter((g) => g.role !== 'final'), + ] + for (const group of ordered) { + const found = group.files.find( + (file) => + (job.output_kinds?.[file] ?? + (IMAGE_EXT.test(file) ? 'image' : null)) === 'image', + ) + if (found) return found + } + return null +} + +/** "2 done · 1 planned": the counts in the order a plan reads. */ +const STATUS_ORDER: LedgerItemStatus[] = [ + 'done', + 'running', + 'queued', + 'planned', + 'failed', + 'dropped', +] +export function statusCounts(counts: Record): string { + const known = STATUS_ORDER.filter((s) => counts[s]) + const rest = Object.keys(counts).filter( + (s) => counts[s] && !(STATUS_ORDER as string[]).includes(s), + ) + return [...known, ...rest].map((s) => `${counts[s]} ${s}`).join(' · ') +} diff --git a/ui/src/lib/routes.test.ts b/ui/src/lib/routes.test.ts index 8cb5cc644..5d596a2f2 100644 --- a/ui/src/lib/routes.test.ts +++ b/ui/src/lib/routes.test.ts @@ -16,6 +16,21 @@ describe('parseView', () => { rest: ['abc'], }) }) + it('reads the requests list and one request', () => { + expect(parseView(['ws', 'studio', 'requests'])).toEqual({ + kind: 'ws', + workspace: 'studio', + section: 'requests', + rest: [], + }) + expect(parseView(['ws', 'studio', 'requests', 'r-1'])).toEqual({ + kind: 'ws', + workspace: 'studio', + section: 'requests', + rest: ['r-1'], + }) + expect(wsHref('studio', 'requests', 'r-1')).toBe('#/ws/studio/requests/r-1') + }) it('defaults a bare workspace, or an unknown section, to overview', () => { expect(parseView(['ws', 'studio'])).toMatchObject({ section: 'overview' }) expect(parseView(['ws', 'studio', 'nope'])).toMatchObject({ diff --git a/ui/src/lib/routes.ts b/ui/src/lib/routes.ts index a2727231c..ee46814b4 100644 --- a/ui/src/lib/routes.ts +++ b/ui/src/lib/routes.ts @@ -7,6 +7,7 @@ export const WS_SECTIONS = [ 'overview', 'workflows', 'jobs', + 'requests', 'gallery', 'compare', 'assets', diff --git a/ui/src/lib/serverinfo.ts b/ui/src/lib/serverinfo.ts index c58b453fa..93c33c24a 100644 --- a/ui/src/lib/serverinfo.ts +++ b/ui/src/lib/serverinfo.ts @@ -91,6 +91,8 @@ export function runtimeText(info: ServerInfo): string { return [ `host: ${info.hostname}`, `dw: ${info.version}`, - ...runtimeRows(info.runtime).map((r) => `${r.name}: ${r.value ?? r.absent}`), + ...runtimeRows(info.runtime).map( + (r) => `${r.name}: ${r.value ?? r.absent}`, + ), ].join('\n') } diff --git a/ui/src/lib/types.ts b/ui/src/lib/types.ts index 3fddae60e..a636e5bf5 100644 --- a/ui/src/lib/types.ts +++ b/ui/src/lib/types.ts @@ -78,6 +78,15 @@ export type AssetList = Schemas['AssetList'] export type Uploaded = Schemas['Uploaded'] export type Kept = Schemas['Kept'] export type AssetDeleted = Schemas['AssetDeleted'] +// The requests ledger (dw/ledger.py): a workspace's list, one request's +// derived view, and its parts +export type LedgerList = Schemas['LedgerList'] +export type LedgerSummary = Schemas['LedgerSummary'] +export type LedgerRequest = Schemas['LedgerRequest'] +export type LedgerItem = Schemas['LedgerItem'] +export type LedgerAttempt = Schemas['LedgerAttempt'] +export type LedgerHistoryEntry = Schemas['LedgerHistoryEntry'] +export type LedgerItemStatus = LedgerItem['status'] export type PipelineParameter = Schemas['PipelineParameter'] export type PipelineDescription = Schemas['PipelineDescription'] export type PipelineNames = Schemas['PipelineNames'] From f502680ff441713ab931eecf40d15c51d2502acb Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Thu, 19 Nov 2026 19:01:25 -0600 Subject: [PATCH 308/412] feat(ui): #1483 - the gallery's request filter keeps the item MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit req=/ on the gallery hash now narrows to that item's runs: the chip reads " › ", the hash keeps the item, and GET /api/gallery takes `item` beside `request` (422 without one, like /api/jobs). A filtered gallery that matches nothing says so instead of "Nothing generated yet". Co-Authored-By: Claude Opus 5.5 --- docs/SERVER.md | 4 +-- dw/server/job_history.py | 20 +++++++------ dw/server/routes/gallery.py | 20 +++++++++---- tests/test_ledger_job_link.py | 20 +++++++++++++ ui/src/lib/api.test.ts | 8 ++++++ ui/src/lib/api.ts | 6 ++-- ui/src/lib/gallery/RequestFilter.svelte | 38 ++++++++++++++++--------- ui/src/lib/generated/api-schema.ts | 2 ++ ui/src/lib/generated/openapi.json | 18 ++++++++++++ ui/src/lib/pages/GalleryPage.svelte | 13 +++++++-- ui/src/lib/pages/GalleryPage.test.ts | 34 ++++++++++++++++++---- 11 files changed, 144 insertions(+), 39 deletions(-) diff --git a/docs/SERVER.md b/docs/SERVER.md index e2457d59e..2b4104239 100644 --- a/docs/SERVER.md +++ b/docs/SERVER.md @@ -971,8 +971,8 @@ The editor's forms come from these; they are just as usable from scripts: request view and each list row carry `spent_minutes` and `remaining_minutes`. An item's `accepted` on write takes `{"job": id}` or a bare job id of a succeeded job linked to that request and item, stored as - `{job, run_id}`. `GET /api/gallery?request=` lists only files of runs - whose jobs are linked to that request. + `{job, run_id}`. `GET /api/gallery?request=[&item=]` lists only + files of runs whose jobs are linked to that request (or that item of it). - `GET /api/workspaces`, `POST /api/workspaces` (`{"name": ...}`), `DELETE /api/workspaces/{name}?acknowledged=true` — the workspaces on this server ([layout](WORKSPACES.md#several-workspaces-on-one-server)). Delete diff --git a/dw/server/job_history.py b/dw/server/job_history.py index 6be84a4b7..cb3c38ade 100644 --- a/dw/server/job_history.py +++ b/dw/server/job_history.py @@ -606,15 +606,19 @@ def request_jobs(self, workspace, request): ).fetchall() return [dict(row) for row in rows] - def run_ids_for_request(self, workspace, request): - """The run ids of `workspace`'s jobs linked to `request` - what the - run-based gallery filters by.""" + def run_ids_for_request(self, workspace, request, item=None): + """The run ids of `workspace`'s jobs linked to `request` (and, with + `item`, to that item of it) - what the run-based gallery filters by.""" + sql = ( + "SELECT run_id FROM jobs WHERE workspace = ? AND request = ?" + " AND run_id IS NOT NULL" + ) + params = [workspace, request] + if item: + sql += " AND item = ?" + params.append(item) with self._lock, self._connect() as connection: - rows = connection.execute( - "SELECT run_id FROM jobs WHERE workspace = ? AND request = ?" - " AND run_id IS NOT NULL", - (workspace, request), - ).fetchall() + rows = connection.execute(sql, params).fetchall() return {row["run_id"] for row in rows} def device_ordinal(self, job_id): diff --git a/dw/server/routes/gallery.py b/dw/server/routes/gallery.py index 779e2bc1e..5d369832f 100644 --- a/dw/server/routes/gallery.py +++ b/dw/server/routes/gallery.py @@ -197,6 +197,11 @@ def gallery( description="Only the files of runs whose job is linked to this " "requests-ledger request in this workspace", ), + item: Optional[str] = Query( + default=None, + description="With `request`: only the files of runs whose job is " + "linked to this item of it", + ), ws: Workspace = Depends(selected_workspace), ): """A page of media files in the output directory, newest first. @@ -246,11 +251,14 @@ def gallery( status_code=400, detail=f"unknown role {unknown}; roles are {list(ROLES)}", ) - if request_id: - try: - validate_ledger_key(request_id, "request") - except InvalidInputError as e: - raise HTTPException(status_code=422, detail=str(e)) + if item and not request_id: + raise HTTPException(status_code=422, detail="item needs request") + for value, what in ((request_id, "request"), (item, "item")): + if value: + try: + validate_ledger_key(value, what) + except InvalidInputError as e: + raise HTTPException(status_code=422, detail=str(e)) if only_orphans: entries = _orphan_entries(ws.outputs) offset = max(0, offset) @@ -284,7 +292,7 @@ def gallery( # A run belongs to the request its job was linked to; the history's # run_id column is the map from one to the other runs = request.app.state.job_manager.history.run_ids_for_request( - ws.name, request_id + ws.name, request_id, item ) entries = [e for e in entries if e["run_id"] in runs] offset = max(0, offset) diff --git a/tests/test_ledger_job_link.py b/tests/test_ledger_job_link.py index 920c51b16..055124c2c 100644 --- a/tests/test_ledger_job_link.py +++ b/tests/test_ledger_job_link.py @@ -408,6 +408,26 @@ def test_the_gallery_filters_by_request(self, planned): assert done assert planned.get("/api/gallery?request=Demo").status_code == 422 + def test_the_gallery_filters_by_item(self, planned): + a = submit(planned, item_key="a") + b = submit(planned, item_key="b") + for j in (a, b): + finish(planned, j) + + def runs(query): + r = planned.get(f"/api/gallery?{query}") + assert r.status_code == 200, r.text + return {e["run_id"] for e in r.json()["files"]} + + run_of = { + j["id"]: planned.manager.get(j["id"]).run_dir.split("/")[-1] for j in (a, b) + } + assert runs("request=cats") == {run_of[a["id"]], run_of[b["id"]]} + assert runs("request=cats&item=b") == {run_of[b["id"]]} + assert runs("request=cats&item=a") == {run_of[a["id"]]} + assert planned.get("/api/gallery?item=a").status_code == 422 + assert planned.get("/api/gallery?request=cats&item=B").status_code == 422 + # --- derived state -------------------------------------------------------- diff --git a/ui/src/lib/api.test.ts b/ui/src/lib/api.test.ts index 5bd722218..073d8e546 100644 --- a/ui/src/lib/api.test.ts +++ b/ui/src/lib/api.test.ts @@ -220,6 +220,14 @@ describe('gallery listing and thumbnails', () => { expect(calls[0][0]).toBe('/api/gallery?limit=100000') }) + it('narrows to a request item, and sends no item without a request', async () => { + const calls = stubFetch({ ok: true, body: {} }) + await api.gallery(undefined, 'r1', 'alpha') + await api.gallery(undefined, undefined, 'alpha') + expect(calls[0][0]).toBe('/api/gallery?limit=100000&request=r1&item=alpha') + expect(calls[1][0]).toBe('/api/gallery?limit=100000') + }) + it('builds a thumbnail URL that keeps folder separators', () => { expect(api.galleryThumbnailUrl('ltx/wf-gen.0-0.0.png')).toBe( '/api/gallery/ltx/wf-gen.0-0.0.png/thumbnail', diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 35123f01b..e8af9c6cb 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -381,11 +381,13 @@ export const api = { // a null role counts as final there). The page filters on the client, so // it asks for none // `requestId` narrows to the runs whose job is linked to that - // requests-ledger request (in the selected workspace) - gallery: (roles?: string[], requestId?: string) => { + // requests-ledger request (in the selected workspace), and `item` to one + // item of it + gallery: (roles?: string[], requestId?: string, item?: string) => { const params = new URLSearchParams({ limit: '100000' }) for (const role of roles ?? []) params.append('role', role) if (requestId) params.set('request', requestId) + if (requestId && item) params.set('item', item) return request(`/api/gallery?${params}`) }, // `workspace`, when given, names the file's own workspace and wins over diff --git a/ui/src/lib/gallery/RequestFilter.svelte b/ui/src/lib/gallery/RequestFilter.svelte index 694de1eab..36c869c79 100644 --- a/ui/src/lib/gallery/RequestFilter.svelte +++ b/ui/src/lib/gallery/RequestFilter.svelte @@ -1,25 +1,32 @@ + +
    +
    + {#if verdict} + {verdict.text} + {/if} + {#if checking}checking…{/if} +
    + {#if planLines.length} +
      + {#each planLines as line, i (i)} +
    • {line.text}
    • + {/each} +
    + {/if} + {#if checkError || findings.length} +
      + {#if checkError}
    • {checkError}
    • {/if} + {#each findings as finding, i (i)} +
    • {finding.text}
    • + {/each} +
    + {/if} +
    + + From 1b10b84080d0f9f777e19e73770214142f3dbd0b Mon Sep 17 00:00:00 2001 From: Don Kackman Date: Fri, 20 Nov 2026 11:39:16 -0600 Subject: [PATCH 332/412] refactor(ui): the frame and pickable-tile rules move to frames.css Loaded straight after app.css, ahead of every component's scoped styles as before. No rule of the two files sets the same property on one element, so the order between them changes nothing. files_over_size_ceiling 1 -> 0. Co-Authored-By: Claude Fable 5.2 --- ui/src/app.css | 87 ++------------------------------------------- ui/src/frames.css | 89 +++++++++++++++++++++++++++++++++++++++++++++++ ui/src/main.ts | 1 + 3 files changed, 92 insertions(+), 85 deletions(-) create mode 100644 ui/src/frames.css diff --git a/ui/src/app.css b/ui/src/app.css index 85b18e3ae..3d1c1d0ac 100644 --- a/ui/src/app.css +++ b/ui/src/app.css @@ -460,91 +460,8 @@ a.danger:hover { max-width: 68ch; } -/* A contact-sheet frame. Every place the app shows something a workflow - produced - a catalog card's proof, a workflow's recent outputs, a job's - results, a gallery tile - uses this, so a picture reads the same wherever - it turns up. The picture fills the frame edge to edge: no inner padding - and no rounding on the image itself, which is what makes it read as a - proof on a sheet rather than as another rounded card. Set the size on - the frame; the media inside always fills it. */ -.frame { - display: block; - position: relative; - background: var(--panel-2); - border: 1px solid var(--line); - border-radius: var(--radius-frame); - overflow: hidden; -} -.frame > img, -.frame > video { - display: block; - width: 100%; - height: 100%; - object-fit: cover; -} -/* Marks a still as a video's first frame: grids show a clip as its - thumbnail, never as a
    MeasuresActions
    {row.index} @@ -178,6 +272,19 @@ {:else if columns(table).length || anyChecked(table)} + + {#if !action.enabled}{action.reason}{/if} +