From b5778ef9d55dcd91ddd07b8afda80ccdcf200648 Mon Sep 17 00:00:00 2001 From: Ted H Date: Sat, 14 Nov 2026 20:12:02 -0500 Subject: [PATCH 1/7] Port the compute platform: five lanes, Colab work sessions, provider console Bring the public code to the owner's current version: per-form execution on Local, Google Colab, AutoIP, Comfy Cloud and RunningHub; Colab work sessions with a lease sweeper; per-user write-only provider keys; hosted estimates and settlement; owner receipts for uploaded inputs; an egress guard for user-supplied URLs. Private subsystems stay out of the public tree. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/check.yml | 52 +- .gitleaks.toml | 26 + manifests/app_guides/catalog.json | 32 +- manifests/app_guides/en.json | 11 +- scripts/app_graph_catalog.py | 22 +- scripts/build_docs.py | 4 +- scripts/colab_allocation_diagnostics.py | 34 + scripts/colab_bridge.py | 133 +- scripts/colab_lease_sweeper.py | 107 ++ scripts/colab_private_diagnostics.py | 23 + scripts/colab_remote/native_contracts.py | 238 +++ scripts/colab_remote/native_runner.py | 314 ++++ scripts/colab_remote/native_schema.py | 31 + scripts/colab_remote/native_voice_node.py | 78 + scripts/colab_remote/native_voice_worker.py | 31 + scripts/colab_remote/native_voxcpm_worker.py | 22 + scripts/colab_remote/remote_job.py | 19 +- scripts/colab_rpc_transport.py | 88 + scripts/colab_session_archive.py | 51 + scripts/colab_session_bootstrap.py | 35 + scripts/colab_session_dependencies.py | 91 + scripts/colab_session_diagnostics.py | 177 ++ scripts/colab_session_inputs.py | 27 + scripts/colab_session_overlays/NOTICE | 2 + scripts/colab_session_overlays/NOTICE.md | 9 + .../breezy-frontend.patch | 28 + .../breezy-inference.patch | 159 ++ .../breezy-inventory.json | 212 +++ .../comfy-node-supplements.json | 125 ++ scripts/colab_session_overlays/registry.json | 36 + .../speaker_similarity.py | 82 + .../colab_session_overlays/vhs-audio.patch | 16 + .../voice-environments.json | 1631 +++++++++++++++++ scripts/colab_session_overlays/voxcpm_tts.py | 1117 +++++++++++ scripts/colab_session_probe.py | 299 +++ scripts/colab_session_voice.py | 289 +++ scripts/colab_session_watchdog.py | 81 + scripts/colab_session_worker.py | 397 ++++ scripts/colab_transport_diagnostics.py | 39 + scripts/colab_upload_diagnostics.py | 30 + scripts/dance_animate_baseline.json | 2 +- scripts/review_r36_support.py | 79 + scripts/review_r37_fixture.py | 64 + scripts/review_r38_fixture.py | 68 + .../web-comfyui-colab-lease-sweeper.service | 12 + .../web-comfyui-colab-lease-sweeper.timer | 11 + webui/character_angles.py | 47 + webui/colab_inputs.py | 26 + webui/colab_service.py | 743 +++++++- webui/colab_sessions.py | 1019 ++++++++++ webui/compute_collector.py | 162 ++ webui/compute_execution.py | 3 + webui/compute_parity/__init__.py | 2 + webui/compute_parity/adapters.py | 523 ++++++ webui/compute_parity/autoip_duration.py | 65 + webui/compute_parity/cloud_inventory.py | 33 + webui/compute_parity/cloud_usage.py | 17 + webui/compute_parity/colab.py | 147 ++ webui/compute_parity/consent.py | 18 + webui/compute_parity/contracts.py | 48 + webui/compute_parity/diagnostics.py | 139 ++ .../hosted-model-aliases-r29b.json | 34 + webui/compute_parity/hosted_estimates.py | 63 + webui/compute_parity/hosted_readiness.py | 92 + webui/compute_parity/http.py | 29 + webui/compute_parity/journal.py | 183 ++ webui/compute_parity/lifecycle.py | 82 + webui/compute_parity/local.py | 56 + webui/compute_parity/local_closure.py | 66 + webui/compute_parity/local_measurements.json | 1 + webui/compute_parity/materials.py | 84 + webui/compute_parity/measurement_mapping.py | 21 + .../compute_parity/measurement_mappings.json | 4 + webui/compute_parity/model_aliases.py | 50 + webui/compute_parity/owner_credentials.py | 25 + webui/compute_parity/persona.py | 36 + webui/compute_parity/private_assets.py | 25 + webui/compute_parity/product.py | 160 ++ webui/compute_parity/provisioning.py | 200 ++ webui/compute_parity/quality.py | 28 + webui/compute_parity/quotes.py | 82 + webui/compute_parity/readiness.py | 62 + webui/compute_parity/registration.py | 53 + webui/compute_parity/revalidation.py | 34 + .../compute_parity/reviewed_predispatch.json | 10 + webui/compute_parity/runninghub_native.py | 27 + webui/compute_parity/runtime.py | 64 + webui/compute_parity/transport.py | 179 ++ webui/compute_pipeline.py | 10 +- webui/compute_preferences.py | 69 +- webui/compute_refresh.py | 20 + webui/compute_routing.py | 108 +- webui/compute_web.py | 72 +- webui/egress_guard.py | 250 +++ webui/hosted_compute.py | 35 +- webui/hosted_compute_http.py | 9 +- webui/library_service.py | 4 +- webui/material_collector.py | 4 +- webui/orchestrator/task_wrapper.py | 5 + webui/orchestrator/tasks.py | 19 +- webui/orchestrator/worker.py | 3 +- webui/provider_connection_probe.py | 46 + webui/provider_console.py | 434 +++++ webui/provider_console_backfill.py | 109 ++ webui/provider_console_migration.py | 273 +++ webui/provider_fabric/h3_worker.py | 76 +- webui/provider_fabric/service.py | 4 + webui/quality_rejection.py | 18 + webui/qwen_image21.py | 2 +- webui/server.py | 796 ++++++-- webui/static/app.js | 383 ++-- webui/static/colab.js | 9 +- webui/static/compute-parity.js | 47 + webui/static/compute-pipeline.js | 4 +- webui/static/compute-placement.css | 1 + webui/static/compute-placement.js | 91 +- webui/static/compute-settings.css | 70 +- webui/static/compute-settings.js | 383 ++-- webui/static/guide-translations-en.js | 11 +- webui/static/index.html | 15 +- webui/static/translations-en.js | 4 + webui/voxcpm_tts.py | 10 +- 122 files changed, 13818 insertions(+), 752 deletions(-) create mode 100644 .gitleaks.toml create mode 100644 scripts/colab_allocation_diagnostics.py create mode 100644 scripts/colab_lease_sweeper.py create mode 100644 scripts/colab_private_diagnostics.py create mode 100644 scripts/colab_remote/native_contracts.py create mode 100644 scripts/colab_remote/native_runner.py create mode 100644 scripts/colab_remote/native_schema.py create mode 100644 scripts/colab_remote/native_voice_node.py create mode 100644 scripts/colab_remote/native_voice_worker.py create mode 100644 scripts/colab_remote/native_voxcpm_worker.py create mode 100644 scripts/colab_rpc_transport.py create mode 100644 scripts/colab_session_archive.py create mode 100644 scripts/colab_session_bootstrap.py create mode 100644 scripts/colab_session_dependencies.py create mode 100644 scripts/colab_session_diagnostics.py create mode 100644 scripts/colab_session_inputs.py create mode 100644 scripts/colab_session_overlays/NOTICE create mode 100644 scripts/colab_session_overlays/NOTICE.md create mode 100644 scripts/colab_session_overlays/breezy-frontend.patch create mode 100644 scripts/colab_session_overlays/breezy-inference.patch create mode 100644 scripts/colab_session_overlays/breezy-inventory.json create mode 100644 scripts/colab_session_overlays/comfy-node-supplements.json create mode 100644 scripts/colab_session_overlays/registry.json create mode 100644 scripts/colab_session_overlays/speaker_similarity.py create mode 100644 scripts/colab_session_overlays/vhs-audio.patch create mode 100644 scripts/colab_session_overlays/voice-environments.json create mode 100644 scripts/colab_session_overlays/voxcpm_tts.py create mode 100644 scripts/colab_session_probe.py create mode 100644 scripts/colab_session_voice.py create mode 100644 scripts/colab_session_watchdog.py create mode 100644 scripts/colab_session_worker.py create mode 100644 scripts/colab_transport_diagnostics.py create mode 100644 scripts/colab_upload_diagnostics.py create mode 100644 scripts/review_r36_support.py create mode 100644 scripts/review_r37_fixture.py create mode 100644 scripts/review_r38_fixture.py create mode 100644 scripts/systemd/web-comfyui-colab-lease-sweeper.service create mode 100644 scripts/systemd/web-comfyui-colab-lease-sweeper.timer create mode 100644 webui/character_angles.py create mode 100644 webui/colab_inputs.py create mode 100644 webui/colab_sessions.py create mode 100644 webui/compute_collector.py create mode 100644 webui/compute_parity/__init__.py create mode 100644 webui/compute_parity/adapters.py create mode 100644 webui/compute_parity/autoip_duration.py create mode 100644 webui/compute_parity/cloud_inventory.py create mode 100644 webui/compute_parity/cloud_usage.py create mode 100644 webui/compute_parity/colab.py create mode 100644 webui/compute_parity/consent.py create mode 100644 webui/compute_parity/contracts.py create mode 100644 webui/compute_parity/diagnostics.py create mode 100644 webui/compute_parity/hosted-model-aliases-r29b.json create mode 100644 webui/compute_parity/hosted_estimates.py create mode 100644 webui/compute_parity/hosted_readiness.py create mode 100644 webui/compute_parity/http.py create mode 100644 webui/compute_parity/journal.py create mode 100644 webui/compute_parity/lifecycle.py create mode 100644 webui/compute_parity/local.py create mode 100644 webui/compute_parity/local_closure.py create mode 100644 webui/compute_parity/local_measurements.json create mode 100644 webui/compute_parity/materials.py create mode 100644 webui/compute_parity/measurement_mapping.py create mode 100644 webui/compute_parity/measurement_mappings.json create mode 100644 webui/compute_parity/model_aliases.py create mode 100644 webui/compute_parity/owner_credentials.py create mode 100644 webui/compute_parity/persona.py create mode 100644 webui/compute_parity/private_assets.py create mode 100644 webui/compute_parity/product.py create mode 100644 webui/compute_parity/provisioning.py create mode 100644 webui/compute_parity/quality.py create mode 100644 webui/compute_parity/quotes.py create mode 100644 webui/compute_parity/readiness.py create mode 100644 webui/compute_parity/registration.py create mode 100644 webui/compute_parity/revalidation.py create mode 100644 webui/compute_parity/reviewed_predispatch.json create mode 100644 webui/compute_parity/runninghub_native.py create mode 100644 webui/compute_parity/runtime.py create mode 100644 webui/compute_parity/transport.py create mode 100644 webui/compute_refresh.py create mode 100644 webui/egress_guard.py create mode 100644 webui/provider_connection_probe.py create mode 100644 webui/provider_console.py create mode 100644 webui/provider_console_backfill.py create mode 100644 webui/provider_console_migration.py create mode 100644 webui/quality_rejection.py create mode 100644 webui/static/compute-parity.js diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 25d2cd9..0a6a353 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -62,12 +62,56 @@ jobs: test_tmp="$(mktemp -d "$HOME/agent-work/tmp/pytest/public-ci-XXXXXX")" trap 'rm -rf "$test_tmp"' EXIT export TMPDIR="$test_tmp" - python -m pytest -q --basetemp="$test_tmp/bt" tests scripts/test_app_guide_catalog.py scripts/test_app_graph_catalog.py scripts/test_hardware_catalog.py scripts/test_demo_catalog.py scripts/test_guide_translations.py scripts/test_community_workflows.py scripts/test_community_workflow_sources.py scripts/test_moss_trainer.py scripts/test_workflow_library.py scripts/test_workflow_guides.py scripts/test_autoip_oct22.py scripts/test_autoip_contract.py scripts/test_autoip_worker.py scripts/test_autoip_quote.py scripts/test_provider_autoip_profiles.py + python -m pytest -q --basetemp="$test_tmp/bt" tests scripts/test_app_guide_catalog.py scripts/test_app_graph_catalog.py scripts/test_hardware_catalog.py scripts/test_demo_catalog.py scripts/test_guide_translations.py scripts/test_community_workflows.py scripts/test_community_workflow_sources.py scripts/test_moss_trainer.py scripts/test_workflow_library.py scripts/test_workflow_guides.py scripts/test_autoip_oct22.py scripts/test_autoip_contract.py scripts/test_autoip_worker.py scripts/test_autoip_quote.py scripts/test_provider_autoip_profiles.py \ + scripts/test_character_original.py \ + scripts/test_collector_r35_integration.py \ + scripts/test_compute_collector.py \ + scripts/test_compute_parity_hosted_h1.py \ + scripts/test_compute_parity_p1.py \ + scripts/test_compute_r29.py \ + scripts/test_compute_r29b.py \ + scripts/test_compute_r29c.py \ + scripts/test_compute_r30.py \ + scripts/test_compute_r31.py \ + scripts/test_compute_r32.py \ + scripts/test_compute_r33.py \ + scripts/test_compute_r34.py \ + scripts/test_compute_r35.py \ + scripts/test_compute_r36.py \ + scripts/test_compute_r36b.py \ + scripts/test_compute_r36c.py \ + scripts/test_compute_r37.py \ + scripts/test_compute_r38.py \ + scripts/test_compute_r39.py \ + scripts/test_compute_r40.py \ + scripts/test_compute_r40b.py \ + scripts/test_compute_r40c.py \ + scripts/test_compute_r40v4.py \ + scripts/test_compute_r40v5.py scripts/test_egress_guard.py scripts/test_security_s1.py scripts/test_security_s1d.py scripts/test_compute_r40v6_robustness.py scripts/test_compute_r40v6_unsent_faults.py scripts/test_compute_r40v6_voice_toolchain.py scripts/test_h3_provider_worker.py \ + scripts/test_compute_r40v5_log_stats.py \ + scripts/test_compute_r40v5_restart_hold.py \ + scripts/test_compute_r40v5_worker_yield.py \ + scripts/test_review2_fixes_r35.py \ + scripts/test_review2_original_r35.py \ + scripts/test_review2_safety_r35.py \ + scripts/test_review3_boundaries_r35.py \ + scripts/test_review3_grace_r35.py \ + scripts/test_review_r35.py \ + scripts/test_review_r36c.py \ + scripts/test_review_r37.py \ + scripts/test_review_r38_caps.py \ + scripts/test_review_r38_diagnostics.py \ + scripts/test_review_r38_faults.py \ + scripts/test_review_r38b_edges.py \ + scripts/test_session_safety_r35.py - name: JavaScript syntax run: | node --check webui/static/app.js node --check webui/static/workflow-library.js node --check webui/static/colab.js + node --check webui/static/compute-parity.js + node --check scripts/test_compute_r32_poll.cjs + node --check scripts/test_session_controls_r38.js node --check webui/docs/docs.js node --check webui/docs/explorers.js node --check webui/docs/tour.js @@ -77,6 +121,10 @@ jobs: node --check webui/static/guide-translations-en.js node --check webui/docs/landing.js node --check webui/docs/hardware.js + - name: Offline JavaScript regressions + run: | + node scripts/test_compute_r32_poll.cjs + node scripts/test_session_controls_r38.js browser: runs-on: ubuntu-latest steps: @@ -102,4 +150,4 @@ jobs: browser_test_tmp="$(mktemp -d "$HOME/agent-work/tmp/pytest/browser-ci-XXXXXX")" trap 'rm -rf "$browser_test_tmp"' EXIT export TMPDIR="$browser_test_tmp" - python -m pytest -q --basetemp="$browser_test_tmp/bt" scripts/test_docs_browser.py scripts/test_landing_browser.py scripts/test_tour_browser.py scripts/test_explorers_browser.py scripts/test_hardware_catalog.py scripts/test_i18n_browser.py tests/test_portrait_browser.py tests/test_colab_browser.py tests/test_workflow_review_browser.py + python -m pytest -q --basetemp="$browser_test_tmp/bt" scripts/test_docs_browser.py scripts/test_landing_browser.py scripts/test_tour_browser.py scripts/test_explorers_browser.py scripts/test_hardware_catalog.py scripts/test_i18n_browser.py tests/test_portrait_browser.py tests/test_colab_browser.py tests/test_workflow_review_browser.py tests/test_provider_console_browser.py diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 0000000..8dc8343 --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,26 @@ +# Gitleaks settings for this repository: all default rules, plus one reviewed exception. +# The Colab overlay manifests map file paths to SHA-256 digests of pinned upstream files. +# File names such as "api.py" or "...ArgsEntry.py" next to a 64-character hex digest trip +# the generic-api-key and sentry-access-token rules. For those two rules only, a value that +# is exactly 64 lowercase hex characters in one of these two files is allowed; everything +# else, in these files or elsewhere, is still reported. +[extend] +useDefault = true + +[[rules]] +id = "generic-api-key" +[[rules.allowlists]] +description = "SHA-256 file digests in the Colab overlay manifests" +condition = "AND" +paths = ['''(^|/)scripts/colab_session_overlays/(breezy-inventory|voice-environments)\.json$'''] +regexTarget = "secret" +regexes = ['''^[0-9a-f]{64}$'''] + +[[rules]] +id = "sentry-access-token" +[[rules.allowlists]] +description = "SHA-256 file digests in the Colab overlay manifests" +condition = "AND" +paths = ['''(^|/)scripts/colab_session_overlays/(breezy-inventory|voice-environments)\.json$'''] +regexTarget = "secret" +regexes = ['''^[0-9a-f]{64}$'''] diff --git a/manifests/app_guides/catalog.json b/manifests/app_guides/catalog.json index 6f76b51..29c4be5 100644 --- a/manifests/app_guides/catalog.json +++ b/manifests/app_guides/catalog.json @@ -82,22 +82,32 @@ }, "character-angles": { "source": "webui/server.py", - "symbol": "instantid_prompt", - "summary": "SDXL + InstantID 將真人正臉特徵與 ControlNet 條件用於候選肖像生成。", + "symbol": "qwen21_angles_prompt", + "source_files": [ + "webui/qwen_image21.py" + ], + "summary": "Qwen-Image 2.1 指令改圖:以同一張真人臉照片逐張生成不同朝向的半身肖像候選,指令要求保留原圖身份與色彩。", "steps": [ - "準備單一、清楚、近正面的真人臉照片。", - "InsightFace 分析臉部;InstantID 與 ControlNet 將參考特徵加入 SDXL。", - "依場景/角度描述採樣候選圖,使用 checkpoint 內附 VAE。" + "上傳單一、清楚、近正面的真人臉照片,輸入場景/角度描述與候選張數(1–6)。", + "每張候選都以原始照片為 ,再加上一個固定視角,依序為:左朝向三分之二側臉、右朝向三分之二側臉、正面、左側輪廓、右側輪廓、正面微抬頭(鏡頭略低於視線)。", + "每張以 1024 解析度設定分別採樣、解碼並儲存,種子逐張加 1;不會把上一張生成圖當成下一張的參考。" ], "techniques": [ - "InstantID", - "InsightFace", - "ControlNet", - "SDXL" + "Qwen-Image 2.1", + "TextEncodeQwenImage21", + "圖文條件", + "VAE 解碼" ], "requirements": [ - "動漫、插畫、多人或遮擋臉不適用;需 antelopev2 模型目錄。" - ] + "只接受單一、清楚、近正面的真人臉照片;動漫角色、插畫、多人照與遮擋臉孔不適用。", + "需要支援 TextEncodeQwenImage21 的 ComfyUI 版本及對應權重;模型不隨 repo 發布。", + "寫真候選不保證臉部完全一致,請比較原始參考。" + ], + "model_directories": { + "qwen_image_2.1_int8_convrot.safetensors": "diffusion_models", + "qwen3vl_8b_int8_convrot.safetensors": "text_encoders", + "qwen_image_2.1_vae_bf16.safetensors": "vae" + } }, "clipmode-character-photoshoot": { "source": "webui/server.py", diff --git a/manifests/app_guides/en.json b/manifests/app_guides/en.json index 7013775..d238312 100644 --- a/manifests/app_guides/en.json +++ b/manifests/app_guides/en.json @@ -28,11 +28,12 @@ "每張圖依序加入 IPAdapterAdvanced;採樣後用 checkpoint 內附 VAE 解碼。": "Chain an IPAdapterAdvanced node for each image; after sampling, decode with the checkpoint's bundled VAE.", "IPAdapter 參考條件串接": "Chained IPAdapter reference conditioning", "不能保證保留同一張臉、服裝或人物身分;不是精準換裝入口。": "The same face, clothing, or identity is not guaranteed. This is not a precise clothing-replacement tool.", - "SDXL + InstantID 將真人正臉特徵與 ControlNet 條件用於候選肖像生成。": "SDXL + InstantID uses a real person's frontal facial features and ControlNet conditioning to generate portrait candidates.", - "準備單一、清楚、近正面的真人臉照片。": "Prepare a clear, nearly frontal photo of a single real person's face.", - "InsightFace 分析臉部;InstantID 與 ControlNet 將參考特徵加入 SDXL。": "InsightFace analyzes the face; InstantID and ControlNet add reference features to SDXL.", - "依場景/角度描述採樣候選圖,使用 checkpoint 內附 VAE。": "Sample candidates from the scene/angle description, using the checkpoint's bundled VAE.", - "動漫、插畫、多人或遮擋臉不適用;需 antelopev2 模型目錄。": "Not suitable for anime, illustrations, multiple people, or obscured faces. Requires the antelopev2 model directory.", + "Qwen-Image 2.1 指令改圖:以同一張真人臉照片逐張生成不同朝向的半身肖像候選,指令要求保留原圖身份與色彩。": "Qwen-Image 2.1 instruction editing: from one real face photo, each candidate is generated separately as a half-body portrait at a different head angle; the instruction asks to keep the original identity and colors.", + "上傳單一、清楚、近正面的真人臉照片,輸入場景/角度描述與候選張數(1–6)。": "Upload one clear, near-frontal photo of a real person's face, then enter the scene/angle description and the number of candidates (1–6).", + "每張候選都以原始照片為 ,再加上一個固定視角,依序為:左朝向三分之二側臉、右朝向三分之二側臉、正面、左側輪廓、右側輪廓、正面微抬頭(鏡頭略低於視線)。": "Every candidate uses the original photo as plus one fixed view, in this order: left-facing three-quarter, right-facing three-quarter, frontal, left profile, right profile, frontal with the head slightly raised (camera just below eye level).", + "每張以 1024 解析度設定分別採樣、解碼並儲存,種子逐張加 1;不會把上一張生成圖當成下一張的參考。": "Each candidate is sampled at the 1024 resolution setting, decoded and saved on its own, with the seed increased by 1 per candidate; a generated image is never used as the reference for the next one.", + "只接受單一、清楚、近正面的真人臉照片;動漫角色、插畫、多人照與遮擋臉孔不適用。": "Only one clear, near-frontal photo of a real person's face is accepted; anime characters, illustrations, group photos and covered faces are not suitable.", + "寫真候選不保證臉部完全一致,請比較原始參考。": "Portrait candidates do not guarantee identical facial identity; compare the original reference.", "角色入口的 SDXL Beta 寫真:真人使用角色原圖做 InstantID 與 ReActor,動漫使用已綁定的角色 LoRA。": "The character page's SDXL Beta photoshoot uses the original character image with InstantID and ReActor for realistic characters, or a bound character LoRA for anime characters.", "由角色頁選擇角色、場景、比例及種子。": "Choose the character, scene, aspect ratio, and seed on the character page.", "伺服器綁定身份圖片與模型;真人走 InstantID / ReActor,動漫走既有角色 LoRA。": "The server binds identity images and models. Realistic characters use InstantID / ReActor; anime characters use their existing character LoRA.", diff --git a/scripts/app_graph_catalog.py b/scripts/app_graph_catalog.py index 29589d8..e234966 100644 --- a/scripts/app_graph_catalog.py +++ b/scripts/app_graph_catalog.py @@ -172,7 +172,7 @@ def ip_blend(source): return diagram(raw,'webui/server.py#'+symbol,['代表分支:兩張參考圖,依實際迴圈建立兩個 IPAdapterAdvanced;第三張會再串接一組。']) -def qwen(source,edit): +def qwen(source,edit,path='webui/qwen_image21.py#compile_prompt',notes=None): raw,fn,scope=primary_graph(source,'compile_prompt') scope.update(edit=edit,node_id='11',i=1) branch=next(n for n in fn.body if isinstance(n,ast.If) and isinstance(n.test,ast.Name) and n.test.id=='edit') @@ -197,11 +197,22 @@ def qwen(source,edit): id=source.value(target.value.slice,scope) if id in raw: for keyword in stmt.value.keywords:raw[id]['inputs'][keyword.arg]=source.value(keyword.value,scope) - return diagram(raw,'webui/qwen_image21.py#compile_prompt',[ + return diagram(raw,path,notes if notes is not None else [ '代表分支:一張輸入圖片;實際改圖支援依序加入最多四張。' if edit else '文生圖分支:ResolutionSelector 決定空白 latent 尺寸。', '這是應用程式 builder 的連線,並非官方參考 JSON 的逐字複本。']) +def angles_delegation(source): + """Check, without running it, that each angle candidate is one Qwen edit of the face upload.""" + fn=source.function('qwen21_angles_prompt') + calls=[n for n in ast.walk(fn) if isinstance(n,ast.Call) and isinstance(n.func,ast.Name) and n.func.id=='compile_qwen21_prompt'] + def edit_call(call): + keywords={k.arg:k.value for k in call.keywords} + return (len(call.args)==2 and isinstance(keywords.get('edit'),ast.Constant) and keywords['edit'].value is True + and ast.unparse(call.args[1])=="{'image': face}") + if len(calls)!=1 or not edit_call(calls[0]):raise ValueError('character-angles Qwen edit delegation changed') + + def h3_first_frame(source,fn,raw,conditioning): """Read the reviewed keyframe loop at index zero, without executing it.""" def matches(node,expression): @@ -347,6 +358,12 @@ def graphs(root,app_catalog): id=feature['id'] if id in result:continue if id.startswith('h3-'):result[id]=h3(native,id);continue + if id=='character-angles': + angles_delegation(server) + result[id]=qwen(qwen_source,True,'webui/server.py#qwen21_angles_prompt',[ + '代表一張候選:每張候選各自以原始照片執行一次 Qwen 2.1 改圖,並加上自己的固定視角指令;不會串接前一張生成圖。', + '這是應用程式 builder 的連線,並非官方參考 JSON 的逐字複本。']) + continue if id in {'qwen21-edit','qwen21-text2img'}:result[id]=qwen(qwen_source,id=='qwen21-edit');continue symbol=guides[id].get('builder_symbol') raw,_,_=primary_graph(server,symbol,largest=id=='clipmode-character-photoshoot',scope={'model_ref':['1',0]} if id=='text2img' else None) @@ -366,6 +383,7 @@ def graphs(root,app_catalog): '顯示預設羽化關閉的九節點流程;開啟羽化會加入五個節點,混合邊緣並以內縮遮罩還原主體內部像素。': 'Shows the default nine-node graph with feathering off. Enabling feathering adds five nodes, blends edge pixels and restores the subject interior using an eroded mask.', '代表分支:兩張參考圖,依實際迴圈建立兩個 IPAdapterAdvanced;第三張會再串接一組。': 'Representative branch: two references create two chained IPAdapterAdvanced nodes using the actual loop. A third reference adds another pair.', '代表分支:一張輸入圖片;實際改圖支援依序加入最多四張。': 'Representative branch: one input image. Editing supports up to four images in sequence.', + '代表一張候選:每張候選各自以原始照片執行一次 Qwen 2.1 改圖,並加上自己的固定視角指令;不會串接前一張生成圖。': 'Shows one candidate: each candidate runs one Qwen 2.1 edit on the original photo with its own fixed view instruction. A generated image is never chained into the next.', '文生圖分支:ResolutionSelector 決定空白 latent 尺寸。': 'Text-to-image branch: ResolutionSelector determines the empty latent dimensions.', '這是應用程式 builder 的連線,並非官方參考 JSON 的逐字複本。': 'These are application builder connections, not a verbatim copy of the official reference JSON.', 'Stock 代表分支;Sage/EasyCache/TeaCache 的可選包裝不在此圖。': 'Representative Stock branch. Optional Sage, EasyCache and TeaCache wrappers are not shown.', diff --git a/scripts/build_docs.py b/scripts/build_docs.py index d673e79..b670a2a 100644 --- a/scripts/build_docs.py +++ b/scripts/build_docs.py @@ -28,6 +28,7 @@ ASSETS = { 'webui/static/colab.js': 'assets/colab.js', 'webui/static/colab.css': 'assets/colab.css', + 'webui/static/compute-parity.js': 'assets/compute-parity.js', **{'webui/static/'+name+suffix: 'assets/'+name+suffix for name in ('compute-placement', 'compute-settings', 'compute-pipeline') for suffix in ('.js', '.css')}, @@ -37,6 +38,7 @@ 'webui/docs/hardware.js': 'assets/hardware.js', 'webui/docs/hardware.css': 'assets/hardware.css', 'webui/docs/autoip-referral.svg': 'assets/autoip-referral.svg', + 'webui/docs/runninghub-referral.svg': 'assets/runninghub-referral.svg', 'webui/docs/docs.css': 'assets/docs.css', 'webui/docs/docs.js': 'assets/docs.js', 'webui/docs/explorers.js': 'assets/explorers.js', @@ -128,7 +130,7 @@ def site_html(root): html = html.replace('class="auth-gate"', 'class="auth-gate hidden"') policy = "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; object-src 'none'; base-uri 'self'; form-action 'none'" html = html.replace('', '\n\n\n\n') - banner = '''''' + banner = '''''' html = html.replace('', '' + banner, 1) html = html.replace('\n \n \n \n \n - + - - - - + + + + + diff --git a/webui/static/translations-en.js b/webui/static/translations-en.js index f21a8ff..7e43703 100644 --- a/webui/static/translations-en.js +++ b/webui/static/translations-en.js @@ -177,6 +177,7 @@ AI 指令改圖|Instruction-based image editing 動漫場景寫真|Anime scene composition AI 參考圖融合|Reference image blending 真人臉參考肖像|Face-reference portraits +Qwen 2.1 · 保留原圖身份與色彩的多角度肖像|Qwen 2.1 · Multi-angle portraits that keep the original identity and colors 角色身份寫真|Character identity portraits AI 圖生影片|Image to video 首尾幀影片|First/last-frame video @@ -200,6 +201,7 @@ Qwen 2.1 指令改圖|Qwen 2.1 image editing 聲音生成 · 簡報配音 · 聲音庫|Speech generation · Presentation voiceover · Voice library Flux Kontext 重新生成式編輯|Regenerative editing with Flux Kontext 角色原圖合成 · 不會轉成真人|Original character compositing · Keeps the illustrated style +角色原圖|Original character image 保留人物原貌 · AI 去背合成|Keep the original subject · AI background compositing 人物原圖|Original subject image 背景參考圖|Background reference @@ -516,6 +518,7 @@ API 金鑰|API key 上傳一段目標影片與一張來源臉部照片,ReActor 會逐格把影片中的臉換成來源臉,可選 GFPGAN/CodeFormer 修復臉部,輸出為動畫 webp。|Upload a target video and source face. ReActor swaps faces frame by frame, with optional GFPGAN or CodeFormer restoration, and outputs animated WebP. 依圖片 1 的比例輸出;參考圖請按順序加入,指令以 至 指定。|Output uses image 1's aspect ratio. Add references in sequence and refer to them as through . 只接受單一、清楚、近正面的真人臉照片;動漫角色、插畫、多人照與遮擋臉孔不適用。|Use one clear, nearly frontal real face. Anime, illustrations, group photos and obscured faces are not supported. +只接受單一、清楚、近正面的真人臉照片;動漫角色、插畫、多人照與遮擋臉孔不適用。保留原圖色彩,逐張生成不同朝向的候選肖像。|Use one clear, nearly frontal real face. Anime, illustrations, group photos and obscured faces are not supported. Keeps the original colors and generates each candidate portrait at a different facing. 可直接使用最多 9 圖、3 影片、3 音訊;六段提示詞與上傳 reference tag 必須一致。|Use up to 9 images, 3 videos and 3 audio clips. The six prompt sections must match the uploaded reference tags. 可直接描述中文海報與排版;PNG 輸出支援透明背景。|Describe Chinese posters and typography directly. PNG output supports transparent backgrounds. 可直接測試,不綁角色;Stock、Sage、EasyCache、TeaCache 都是明確選項。|Use without a bound character. Stock, Sage, EasyCache and TeaCache are explicit choices. @@ -863,6 +866,7 @@ Drive 狀態讀取失敗:此資料由安裝後的本機服務提供;說明 目標平台|Target platform 至少選一個參考|Select at least one reference +動作參考|Motion reference `; const map = Object.fromEntries(pairs.trim().split('\n').map(line => {const i=line.indexOf('|');return [line.slice(0,i),line.slice(i+1)];})); window.WebComfyEnglish = Object.freeze(map); diff --git a/webui/voxcpm_tts.py b/webui/voxcpm_tts.py index ab0873e..13d6880 100644 --- a/webui/voxcpm_tts.py +++ b/webui/voxcpm_tts.py @@ -1024,10 +1024,12 @@ def main() -> int: if accepted_path is None: cleanup_attempts(attempt_paths) best_label = f"{best_similarity:.3f}" if best_similarity >= 0 else "n/a" - raise ValueError( - f"speaker gate failed after {max_attempts} attempts; best similarity {best_label}, " - f"threshold {args.speaker_threshold:.3f}" - ) + from quality_rejection import QualityRejected + rejection=QualityRejected({'stage':'speaker_gate','best_similarity':best_similarity, + 'threshold':args.speaker_threshold,'attempts':len(gate_attempts)}) + diagnostic_path=Path(str(args.sidecar)+'.quality.json') + diagnostic_path.write_text(str(rejection));diagnostic_path.chmod(0o600) + raise rejection os.replace(accepted_path, args.output) cleanup_attempts(attempt_paths, keep=accepted_path) From e4bf5080c244cc61518c06afda1cd32d5c931777 Mon Sep 17 00:00:00 2001 From: Ted H Date: Sat, 14 Nov 2026 20:12:02 -0500 Subject: [PATCH 2/7] Port and adapt the tests for the compute platform Provider response fixtures are synthetic. Tests of removed settings screens are replaced by tests of the backend properties they protected. Co-Authored-By: Claude Fable 5.2 --- scripts/fixtures/r30/README.md | 18 + scripts/fixtures/r30/autoip-duration.json | 6 + scripts/fixtures/r30/autoip-settlement.json | 8 + scripts/fixtures/r30/cloud-job.json | 17 + scripts/fixtures/r30/cloud-jobs.json | 14 + scripts/fixtures/r30/cloud-redirect.json | 5 + scripts/fixtures/r30/cloud-workflow.json | 10 + scripts/fixtures/r30/colab-failure.json | 7 + .../r30/comfy_cloud-graph-schema.json | 1417 +++++++++++++ scripts/fixtures/r30/provenance.json | 10 + scripts/fixtures/r30/runninghub-absence.json | 7 + .../fixtures/r30/runninghub-graph-schema.json | 1806 +++++++++++++++++ .../fixtures/r30/runninghub-object-info.json | 216 ++ .../fixtures/r31/autoip-voice-25-to-50.json | 22 + .../fixtures/r34/runninghub-resize-node.json | 248 +++ scripts/test_app_graph_catalog.py | 51 +- scripts/test_character_original.py | 157 ++ scripts/test_collector_r35_integration.py | 128 ++ scripts/test_compute_collector.py | 492 +++++ scripts/test_compute_parity_hosted_h1.py | 59 + scripts/test_compute_parity_p1.py | 549 +++++ scripts/test_compute_r29.py | 291 +++ scripts/test_compute_r29b.py | 203 ++ scripts/test_compute_r29c.py | 29 + scripts/test_compute_r30.py | 325 +++ scripts/test_compute_r31.py | 302 +++ scripts/test_compute_r32.py | 220 ++ scripts/test_compute_r32_poll.cjs | 33 + scripts/test_compute_r33.py | 195 ++ scripts/test_compute_r34.py | 153 ++ scripts/test_compute_r35.py | 498 +++++ scripts/test_compute_r36.py | 310 +++ scripts/test_compute_r36b.py | 71 + scripts/test_compute_r36c.py | 97 + scripts/test_compute_r37.py | 199 ++ scripts/test_compute_r38.py | 163 ++ scripts/test_compute_r39.py | 136 ++ scripts/test_compute_r40.py | 23 + scripts/test_compute_r40b.py | 150 ++ scripts/test_compute_r40c.py | 153 ++ scripts/test_compute_r40v4.py | 226 +++ scripts/test_compute_r40v5.py | 155 ++ scripts/test_compute_r40v5_log_stats.py | 64 + scripts/test_compute_r40v5_restart_hold.py | 633 ++++++ scripts/test_compute_r40v5_worker_yield.py | 240 +++ scripts/test_compute_r40v6_robustness.py | 785 +++++++ scripts/test_compute_r40v6_unsent_faults.py | 363 ++++ scripts/test_compute_r40v6_voice_toolchain.py | 141 ++ scripts/test_docs_browser.py | 17 +- scripts/test_egress_guard.py | 303 +++ scripts/test_h3_provider_worker.py | 179 ++ scripts/test_hardware_catalog.py | 6 +- scripts/test_landing_browser.py | 18 + scripts/test_review2_fixes_r35.py | 223 ++ scripts/test_review2_original_r35.py | 421 ++++ scripts/test_review2_safety_r35.py | 140 ++ scripts/test_review3_boundaries_r35.py | 174 ++ scripts/test_review3_grace_r35.py | 95 + scripts/test_review_r35.py | 308 +++ scripts/test_review_r36c.py | 42 + scripts/test_review_r37.py | 182 ++ scripts/test_review_r38_caps.py | 56 + scripts/test_review_r38_diagnostics.py | 143 ++ scripts/test_review_r38_faults.py | 299 +++ scripts/test_review_r38b_edges.py | 330 +++ scripts/test_security_s1.py | 668 ++++++ scripts/test_security_s1d.py | 442 ++++ scripts/test_session_controls_r38.js | 18 + scripts/test_session_safety_r35.py | 227 +++ tests/conftest.py | 50 +- tests/test_colab_bridge.py | 16 +- tests/test_comfyui_api_proxy.py | 5 +- tests/test_compute_browser.py | 4 +- tests/test_compute_guided_browser.py | 160 +- tests/test_compute_http.py | 7 +- tests/test_compute_management_browser.py | 100 +- tests/test_compute_management_http.py | 38 +- tests/test_compute_preferences.py | 14 +- tests/test_compute_status.py | 4 +- tests/test_compute_web.py | 46 +- tests/test_demo_publication.py | 7 + tests/test_docs_site.py | 10 + tests/test_hosted_compute.py | 87 +- tests/test_hosted_compute_http.py | 11 + tests/test_provider_console.py | 342 ++++ tests/test_provider_console_backfill.py | 180 ++ tests/test_provider_console_browser.py | 84 + tests/test_provider_console_http.py | 107 + 88 files changed, 16732 insertions(+), 236 deletions(-) create mode 100644 scripts/fixtures/r30/README.md create mode 100644 scripts/fixtures/r30/autoip-duration.json create mode 100644 scripts/fixtures/r30/autoip-settlement.json create mode 100644 scripts/fixtures/r30/cloud-job.json create mode 100644 scripts/fixtures/r30/cloud-jobs.json create mode 100644 scripts/fixtures/r30/cloud-redirect.json create mode 100644 scripts/fixtures/r30/cloud-workflow.json create mode 100644 scripts/fixtures/r30/colab-failure.json create mode 100644 scripts/fixtures/r30/comfy_cloud-graph-schema.json create mode 100644 scripts/fixtures/r30/provenance.json create mode 100644 scripts/fixtures/r30/runninghub-absence.json create mode 100644 scripts/fixtures/r30/runninghub-graph-schema.json create mode 100644 scripts/fixtures/r30/runninghub-object-info.json create mode 100644 scripts/fixtures/r31/autoip-voice-25-to-50.json create mode 100644 scripts/fixtures/r34/runninghub-resize-node.json create mode 100644 scripts/test_character_original.py create mode 100644 scripts/test_collector_r35_integration.py create mode 100644 scripts/test_compute_collector.py create mode 100644 scripts/test_compute_parity_hosted_h1.py create mode 100644 scripts/test_compute_parity_p1.py create mode 100644 scripts/test_compute_r29.py create mode 100644 scripts/test_compute_r29b.py create mode 100644 scripts/test_compute_r29c.py create mode 100644 scripts/test_compute_r30.py create mode 100644 scripts/test_compute_r31.py create mode 100644 scripts/test_compute_r32.py create mode 100644 scripts/test_compute_r32_poll.cjs create mode 100644 scripts/test_compute_r33.py create mode 100644 scripts/test_compute_r34.py create mode 100644 scripts/test_compute_r35.py create mode 100644 scripts/test_compute_r36.py create mode 100644 scripts/test_compute_r36b.py create mode 100644 scripts/test_compute_r36c.py create mode 100644 scripts/test_compute_r37.py create mode 100644 scripts/test_compute_r38.py create mode 100644 scripts/test_compute_r39.py create mode 100644 scripts/test_compute_r40.py create mode 100644 scripts/test_compute_r40b.py create mode 100644 scripts/test_compute_r40c.py create mode 100644 scripts/test_compute_r40v4.py create mode 100644 scripts/test_compute_r40v5.py create mode 100644 scripts/test_compute_r40v5_log_stats.py create mode 100644 scripts/test_compute_r40v5_restart_hold.py create mode 100644 scripts/test_compute_r40v5_worker_yield.py create mode 100644 scripts/test_compute_r40v6_robustness.py create mode 100644 scripts/test_compute_r40v6_unsent_faults.py create mode 100644 scripts/test_compute_r40v6_voice_toolchain.py create mode 100644 scripts/test_egress_guard.py create mode 100644 scripts/test_h3_provider_worker.py create mode 100644 scripts/test_review2_fixes_r35.py create mode 100644 scripts/test_review2_original_r35.py create mode 100644 scripts/test_review2_safety_r35.py create mode 100644 scripts/test_review3_boundaries_r35.py create mode 100644 scripts/test_review3_grace_r35.py create mode 100644 scripts/test_review_r35.py create mode 100644 scripts/test_review_r36c.py create mode 100644 scripts/test_review_r37.py create mode 100644 scripts/test_review_r38_caps.py create mode 100644 scripts/test_review_r38_diagnostics.py create mode 100644 scripts/test_review_r38_faults.py create mode 100644 scripts/test_review_r38b_edges.py create mode 100644 scripts/test_security_s1.py create mode 100644 scripts/test_security_s1d.py create mode 100644 scripts/test_session_controls_r38.js create mode 100644 scripts/test_session_safety_r35.py create mode 100644 tests/test_provider_console.py create mode 100644 tests/test_provider_console_backfill.py create mode 100644 tests/test_provider_console_browser.py create mode 100644 tests/test_provider_console_http.py diff --git a/scripts/fixtures/r30/README.md b/scripts/fixtures/r30/README.md new file mode 100644 index 0000000..bbc4e1c --- /dev/null +++ b/scripts/fixtures/r30/README.md @@ -0,0 +1,18 @@ +# Provider response fixtures + +The JSON files in `scripts/fixtures/` are synthetic. They keep the response shapes of the +provider GET endpoints that the offline tests need. Identifiers, hashes, sizes and times +are made up. They contain no account data, media names, prompts or credentials. + +- `*-graph-schema.json`, `runninghub-object-info.json`, `../r34/runninghub-resize-node.json`: + node input schemas. Model lists are trimmed to the names the graphs use; upload lists + are empty. +- `runninghub-absence.json`: empty history and queue responses. +- `cloud-job.json`, `cloud-jobs.json`, `cloud-workflow.json`, `cloud-redirect.json`: + Comfy Cloud job, listing, executed-graph and output-redirect shapes. +- `autoip-settlement.json`, `autoip-duration.json`, `../r31/autoip-voice-25-to-50.json`: + AutoIP task, frame-count and pricing shapes. +- `colab-failure.json`: a failed Colab job with a released lease. + +Tests label hostile redirect and error bodies as synthetic as well. Offline tests do not +establish visual quality. diff --git a/scripts/fixtures/r30/autoip-duration.json b/scripts/fixtures/r30/autoip-duration.json new file mode 100644 index 0000000..3e118e7 --- /dev/null +++ b/scripts/fixtures/r30/autoip-duration.json @@ -0,0 +1,6 @@ +{ + "source_frames": 391, + "output_frames": 389, + "fps": 30, + "source": "synthetic" +} \ No newline at end of file diff --git a/scripts/fixtures/r30/autoip-settlement.json b/scripts/fixtures/r30/autoip-settlement.json new file mode 100644 index 0000000..98f408b --- /dev/null +++ b/scripts/fixtures/r30/autoip-settlement.json @@ -0,0 +1,8 @@ +{ + "status": "completed", + "credits_charged": 100, + "task_uuid": "00000000-0000-4000-8000-00000000a001", + "outputs": [ + {} + ] +} \ No newline at end of file diff --git a/scripts/fixtures/r30/cloud-job.json b/scripts/fixtures/r30/cloud-job.json new file mode 100644 index 0000000..b01638f --- /dev/null +++ b/scripts/fixtures/r30/cloud-job.json @@ -0,0 +1,17 @@ +{ + "id": "00000000-0000-4000-8000-00000000c001", + "status": "succeeded", + "urls": { + "cancel": "http://cloud.comfy.org/api/v2/jobs/00000000-0000-4000-8000-00000000c001/cancel", + "events": "http://cloud.comfy.org/api/v2/jobs/00000000-0000-4000-8000-00000000c001/events", + "self": "http://cloud.comfy.org/api/v2/jobs/00000000-0000-4000-8000-00000000c001" + }, + "outputs": [ + { + "id": "00000000-0000-4000-8000-00000000c002", + "size_bytes": 1048576, + "hash": "blake3:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + "url": "http://cloud.comfy.org/api/v2/assets/00000000-0000-4000-8000-00000000c002/content" + } + ] +} diff --git a/scripts/fixtures/r30/cloud-jobs.json b/scripts/fixtures/r30/cloud-jobs.json new file mode 100644 index 0000000..9d92f05 --- /dev/null +++ b/scripts/fixtures/r30/cloud-jobs.json @@ -0,0 +1,14 @@ +{ + "pagination": { + "has_more": false, + "limit": 100, + "offset": 0, + "total": 1 + }, + "jobs": [ + { + "id": "00000000-0000-4000-8000-00000000c001", + "status": "completed" + } + ] +} diff --git a/scripts/fixtures/r30/cloud-redirect.json b/scripts/fixtures/r30/cloud-redirect.json new file mode 100644 index 0000000..d2c98f1 --- /dev/null +++ b/scripts/fixtures/r30/cloud-redirect.json @@ -0,0 +1,5 @@ +{ + "status": 302, + "location": "https://storage.googleapis.com/comfy-cloud-assets/0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef.mp4", + "source": "synthetic" +} \ No newline at end of file diff --git a/scripts/fixtures/r30/cloud-workflow.json b/scripts/fixtures/r30/cloud-workflow.json new file mode 100644 index 0000000..fcc3fa0 --- /dev/null +++ b/scripts/fixtures/r30/cloud-workflow.json @@ -0,0 +1,10 @@ +{ + "workflow": { + "25": { + "class_type": "VHS_VideoCombine", + "inputs": { + "filename_prefix": "parity/00000000-0000-4000-8000-00000000d001" + } + } + } +} diff --git a/scripts/fixtures/r30/colab-failure.json b/scripts/fixtures/r30/colab-failure.json new file mode 100644 index 0000000..144921c --- /dev/null +++ b/scripts/fixtures/r30/colab-failure.json @@ -0,0 +1,7 @@ +{ + "phase": "failed", + "remote_phase": "failed", + "remote_diagnostics": {}, + "released": true, + "units_observed": 0.1 +} \ No newline at end of file diff --git a/scripts/fixtures/r30/comfy_cloud-graph-schema.json b/scripts/fixtures/r30/comfy_cloud-graph-schema.json new file mode 100644 index 0000000..83f1493 --- /dev/null +++ b/scripts/fixtures/r30/comfy_cloud-graph-schema.json @@ -0,0 +1,1417 @@ +{ + "UNETLoader": { + "input": { + "required": { + "unet_name": [ + [ + "wan2.1_14B_SCAIL_2_fp8_scaled.safetensors" + ] + ], + "weight_dtype": [ + [ + "default", + "fp8_e4m3fn", + "fp8_e4m3fn_fast", + "fp8_e5m2" + ], + { + "advanced": true + } + ] + } + } + }, + "LoraLoaderModelOnly": { + "input": { + "required": { + "model": [ + "MODEL" + ], + "lora_name": [ + [] + ], + "strength_model": [ + "FLOAT", + { + "default": 1.0, + "min": -100.0, + "max": 100.0, + "step": 0.01 + } + ] + } + } + }, + "ModelSamplingSD3": { + "input": { + "required": { + "model": [ + "MODEL" + ], + "shift": [ + "FLOAT", + { + "default": 3.0, + "min": 0.0, + "max": 100.0, + "step": 0.01 + } + ] + } + } + }, + "WanContextWindowsManual": { + "input": { + "required": { + "model": [ + "MODEL", + { + "tooltip": "The model to apply context windows to during sampling." + } + ], + "context_length": [ + "INT", + { + "tooltip": "The length of the context window in real frames. Must be 4*n + 1.", + "default": 81, + "min": 1, + "max": 16384, + "step": 4 + } + ], + "context_overlap": [ + "INT", + { + "tooltip": "The overlap of the context window in real frames.", + "default": 30, + "min": 0 + } + ], + "context_schedule": [ + "COMBO", + { + "tooltip": "Step-dependent scheduling algorithm for context windows.", + "default": "standard_uniform", + "multiselect": false, + "options": [ + "standard_static", + "standard_uniform", + "looped_uniform", + "batched" + ] + } + ], + "context_stride": [ + "INT", + { + "tooltip": "The stride of the context window; only applicable to uniform schedules.", + "advanced": true, + "default": 1, + "min": 1 + } + ], + "closed_loop": [ + "BOOLEAN", + { + "tooltip": "Whether to close the context window loop; only applicable to looped schedules.", + "advanced": true, + "default": false + } + ], + "fuse_method": [ + "COMBO", + { + "tooltip": "The method to use to fuse the context windows.", + "default": "pyramid", + "multiselect": false, + "options": [ + "pyramid", + "relative", + "flat", + "overlap-linear" + ] + } + ], + "freenoise": [ + "BOOLEAN", + { + "tooltip": "Whether to apply FreeNoise noise shuffling, improves window blending.", + "advanced": true, + "default": true + } + ], + "retain_first_frame": [ + "BOOLEAN", + { + "tooltip": "Retain the first I2V frame in every context window (may help retain initial reference).", + "default": false + } + ], + "split_conds_to_windows": [ + "BOOLEAN", + { + "tooltip": "Whether to split multiple conditionings (created by ConditionCombine) to each window based on region index.", + "advanced": true, + "default": false + } + ] + } + } + }, + "CLIPLoader": { + "input": { + "required": { + "clip_name": [ + [ + "umt5_xxl_fp8_e4m3fn_scaled.safetensors" + ] + ], + "type": [ + [ + "stable_diffusion", + "stable_cascade", + "sd3", + "stable_audio", + "mochi", + "ltxv", + "pixart", + "cosmos", + "lumina2", + "wan", + "hidream", + "chroma", + "ace", + "omnigen2", + "qwen_image", + "hunyuan_image", + "flux2", + "ovis", + "longcat_image", + "cogvideox", + "lens", + "pixeldit", + "ideogram4", + "boogu", + "krea2", + "joyimage", + "mage", + "minimax", + "yue2", + "flux3", + "moss_image", + "fibo2" + ] + ] + }, + "optional": { + "device": [ + [ + "default", + "cpu" + ], + { + "advanced": true + } + ] + } + } + }, + "CLIPTextEncode": { + "input": { + "required": { + "text": [ + "STRING", + { + "multiline": true, + "dynamicPrompts": true, + "tooltip": "The text to be encoded." + } + ], + "clip": [ + "CLIP", + { + "tooltip": "The CLIP model used for encoding the text." + } + ] + } + } + }, + "VAELoader": { + "input": { + "required": { + "vae_name": [ + [ + "wan_2.1_vae.safetensors" + ] + ] + } + } + }, + "CLIPVisionLoader": { + "input": { + "required": { + "clip_name": [ + [ + "clip_vision_h.safetensors" + ] + ] + } + } + }, + "LoadImage": { + "input": { + "required": { + "image": [ + [], + { + "image_upload": true + } + ] + } + } + }, + "ResizeImageMaskNode": { + "input": { + "required": { + "input": [ + "COMFY_MATCHTYPE_V3", + { + "template": { + "template_id": "input_type", + "allowed_types": "IMAGE,MASK" + } + } + ], + "resize_type": [ + "COMFY_DYNAMICCOMBO_V3", + { + "tooltip": "Select how to resize: by exact dimensions, scale factor, matching another image, etc.", + "options": [ + { + "key": "scale dimensions", + "inputs": { + "required": { + "width": [ + "INT", + { + "tooltip": "Target width in pixels. Set to 0 to auto-calculate from height while preserving aspect ratio.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ], + "height": [ + "INT", + { + "tooltip": "Target height in pixels. Set to 0 to auto-calculate from width while preserving aspect ratio.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ], + "crop": [ + "COMBO", + { + "tooltip": "How to handle aspect ratio mismatch: 'disabled' stretches to fit, 'center' crops to maintain aspect ratio.", + "default": "center", + "multiselect": false, + "options": [ + "disabled", + "center" + ] + } + ] + } + } + }, + { + "key": "scale by multiplier", + "inputs": { + "required": { + "multiplier": [ + "FLOAT", + { + "tooltip": "Scale factor (e.g., 2.0 doubles size, 0.5 halves size).", + "default": 1.0, + "min": 0.01, + "max": 8.0, + "step": 0.01 + } + ] + } + } + }, + { + "key": "scale longer dimension", + "inputs": { + "required": { + "longer_size": [ + "INT", + { + "tooltip": "The longer edge will be resized to this value. Aspect ratio is preserved.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ] + } + } + }, + { + "key": "scale shorter dimension", + "inputs": { + "required": { + "shorter_size": [ + "INT", + { + "tooltip": "The shorter edge will be resized to this value. Aspect ratio is preserved.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ] + } + } + }, + { + "key": "scale width", + "inputs": { + "required": { + "width": [ + "INT", + { + "tooltip": "Target width in pixels. Height auto-adjusts to preserve aspect ratio.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ] + } + } + }, + { + "key": "scale height", + "inputs": { + "required": { + "height": [ + "INT", + { + "tooltip": "Target height in pixels. Width auto-adjusts to preserve aspect ratio.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ] + } + } + }, + { + "key": "scale total pixels", + "inputs": { + "required": { + "megapixels": [ + "FLOAT", + { + "tooltip": "Target total megapixels (e.g., 1.0 \u2248 1024\u00d71024). Aspect ratio is preserved.", + "default": 1.0, + "min": 0.01, + "max": 16.0, + "step": 0.01 + } + ] + } + } + }, + { + "key": "match size", + "inputs": { + "required": { + "match": [ + "IMAGE,MASK", + { + "tooltip": "Resize input to match the dimensions of this reference image or mask." + } + ], + "crop": [ + "COMBO", + { + "tooltip": "How to handle aspect ratio mismatch: 'disabled' stretches to fit, 'center' crops to maintain aspect ratio.", + "default": "center", + "multiselect": false, + "options": [ + "disabled", + "center" + ] + } + ] + } + } + }, + { + "key": "scale to multiple", + "inputs": { + "required": { + "multiple": [ + "INT", + { + "tooltip": "Resize so width and height are divisible by this number. Useful for latent alignment (e.g., 8 or 64).", + "default": 8, + "min": 1, + "max": 16384, + "step": 1 + } + ] + } + } + } + ] + } + ], + "scale_method": [ + "COMBO", + { + "tooltip": "Interpolation algorithm. 'area' is best for downscaling, 'lanczos' for upscaling, 'nearest-exact' for pixel art.", + "default": "area", + "multiselect": false, + "options": [ + "nearest-exact", + "bilinear", + "area", + "bicubic", + "lanczos" + ] + } + ] + } + } + }, + "CLIPVisionEncode": { + "input": { + "required": { + "clip_vision": [ + "CLIP_VISION" + ], + "image": [ + "IMAGE" + ], + "crop": [ + [ + "center", + "none" + ] + ] + } + } + }, + "GetImageSize": { + "input": { + "required": { + "image": [ + "IMAGE", + {} + ] + }, + "hidden": { + "unique_id": [ + "UNIQUE_ID" + ] + } + } + }, + "VHS_LoadVideo": { + "input": { + "required": { + "video": [ + [] + ], + "force_rate": [ + "FLOAT", + { + "default": 0, + "min": 0, + "max": 60, + "step": 1, + "disable": 0 + } + ], + "custom_width": [ + "INT", + { + "default": 0, + "min": 0, + "max": 8192, + "disable": 0 + } + ], + "custom_height": [ + "INT", + { + "default": 0, + "min": 0, + "max": 8192, + "disable": 0 + } + ], + "frame_load_cap": [ + "INT", + { + "default": 0, + "min": 0, + "max": 9007199254740991, + "step": 1, + "disable": 0 + } + ], + "skip_first_frames": [ + "INT", + { + "default": 0, + "min": 0, + "max": 9007199254740991, + "step": 1 + } + ], + "select_every_nth": [ + "INT", + { + "default": 1, + "min": 1, + "max": 9007199254740991, + "step": 1 + } + ] + }, + "optional": { + "meta_batch": [ + "VHS_BatchManager" + ], + "vae": [ + "VAE" + ], + "format": [ + [ + "None", + "AnimateDiff", + "Mochi", + "LTXV", + "Hunyuan", + "Cosmos", + "Wan" + ], + { + "default": "AnimateDiff", + "formats": { + "None": {}, + "AnimateDiff": { + "target_rate": 8, + "dim": [ + 8, + 0, + 512, + 512 + ] + }, + "Mochi": { + "target_rate": 24, + "dim": [ + 16, + 0, + 848, + 480 + ], + "frames": [ + 6, + 1 + ] + }, + "LTXV": { + "target_rate": 24, + "dim": [ + 32, + 0, + 768, + 512 + ], + "frames": [ + 8, + 1 + ] + }, + "Hunyuan": { + "target_rate": 24, + "dim": [ + 16, + 0, + 848, + 480 + ], + "frames": [ + 4, + 1 + ] + }, + "Cosmos": { + "target_rate": 24, + "dim": [ + 16, + 0, + 1280, + 704 + ], + "frames": [ + 8, + 1 + ] + }, + "Wan": { + "target_rate": 16, + "dim": [ + 8, + 0, + 832, + 480 + ], + "frames": [ + 4, + 1 + ] + } + } + } + ] + }, + "hidden": { + "force_size": "STRING", + "unique_id": "UNIQUE_ID" + } + } + }, + "CheckpointLoaderSimple": { + "input": { + "required": { + "ckpt_name": [ + [ + "sam3.1_multiplex_fp16.safetensors" + ], + { + "tooltip": "The name of the checkpoint (model) to load." + } + ] + } + } + }, + "SAM3_VideoTrack": { + "input": { + "required": { + "images": [ + "IMAGE", + { + "display_name": "images", + "tooltip": "Video frames as batched images" + } + ], + "model": [ + "MODEL", + { + "display_name": "model" + } + ], + "detection_threshold": [ + "FLOAT", + { + "display_name": "detection_threshold", + "tooltip": "Score threshold for text-prompted detection.", + "default": 0.5, + "min": 0.0, + "max": 1.0, + "step": 0.01 + } + ], + "max_objects": [ + "INT", + { + "display_name": "max_objects", + "tooltip": "Max tracked objects. Initial masks count toward this limit. 0 uses the internal cap of 64.", + "default": 4, + "min": 0, + "max": 64 + } + ], + "detect_interval": [ + "INT", + { + "display_name": "detect_interval", + "tooltip": "Run detection every N frames (1=every frame). Higher values save compute.", + "default": 1, + "min": 1 + } + ] + }, + "optional": { + "initial_mask": [ + "MASK", + { + "display_name": "initial_mask", + "tooltip": "Mask(s) for the first frame to track (one per object)" + } + ], + "conditioning": [ + "CONDITIONING", + { + "display_name": "conditioning", + "tooltip": "Text conditioning for detecting new objects during tracking" + } + ] + } + } + }, + "SCAIL2ColoredMask": { + "input": { + "required": { + "driving_track_data": [ + "SAM3_TRACK_DATA", + { + "tooltip": "SAM3 track of the driving pose video. Will be rendered into the pose_video_mask output." + } + ], + "object_indices": [ + "STRING", + { + "tooltip": "Comma-separated list of person indices to include (e.g. '0,2,3'). Applied to both reference and pose video masks. Empty = all.", + "default": "", + "multiline": false + } + ], + "sort_by": [ + "COMBO", + { + "tooltip": "Order in which palette colors are assigned to the tracked objects (applied to both reference and pose video so each identity keeps the same color). Objects that appear in earlier frames always come first; within a frame, left_to_right = leftmost object (by centroid at first appearance) gets the first color, area = biggest object (by mask area at first appearance) gets the first color; none = keep SAM3's order.", + "default": "left_to_right", + "multiselect": false, + "options": [ + "none", + "left_to_right", + "area" + ] + } + ], + "replacement_mode": [ + "BOOLEAN", + { + "tooltip": "False = Animation Mode (pose_video_mask has black background, reference_image_mask has white background). True = Replacement Mode (pose_video_mask has white background, reference_image_mask has black background).", + "default": false + } + ] + }, + "optional": { + "ref_track_data": [ + "SAM3_TRACK_DATA,MASK", + { + "display_name": "reference_masks", + "tooltip": "SAM3 track of the reference image(s) (one identity per object, colored in batch order), or a plain MASK of the reference subject (rendered as a single identity)." + } + ] + } + } + }, + "WanSCAILToVideo": { + "input": { + "required": { + "positive": [ + "CONDITIONING", + {} + ], + "negative": [ + "CONDITIONING", + {} + ], + "vae": [ + "VAE", + {} + ], + "width": [ + "INT", + { + "default": 512, + "min": 32, + "max": 16384, + "step": 32 + } + ], + "height": [ + "INT", + { + "default": 896, + "min": 32, + "max": 16384, + "step": 32 + } + ], + "length": [ + "INT", + { + "default": 81, + "min": 1, + "max": 16384, + "step": 4 + } + ], + "batch_size": [ + "INT", + { + "default": 1, + "min": 1, + "max": 4096 + } + ], + "pose_strength": [ + "FLOAT", + { + "tooltip": "Strength of the pose latent.", + "default": 1.0, + "min": 0.0, + "max": 10.0, + "step": 0.01 + } + ], + "pose_start": [ + "FLOAT", + { + "tooltip": "Start step of the pose conditioning.", + "default": 0.0, + "min": 0.0, + "max": 1.0, + "step": 0.01 + } + ], + "pose_end": [ + "FLOAT", + { + "tooltip": "End step of the pose conditioning.", + "default": 1.0, + "min": 0.0, + "max": 1.0, + "step": 0.01 + } + ], + "video_frame_offset": [ + "INT", + { + "tooltip": "Cumulative output frame this chunk begins at. Wire from the previous chunk's video_frame_offset output.", + "default": 0, + "min": 0, + "max": 16384, + "step": 1 + } + ], + "previous_frame_count": [ + "INT", + { + "tooltip": "Tail frames of previous_frames to anchor. SCAIL-2 trained at 5 (81-frame chunks, 76-frame step).", + "default": 5, + "min": 1, + "max": 16384, + "step": 4 + } + ] + }, + "optional": { + "pose_video": [ + "IMAGE", + { + "tooltip": "Video used for pose conditioning. Will be downscaled to half the resolution of the main video." + } + ], + "pose_video_mask": [ + "IMAGE", + { + "tooltip": "SCAIL-2 only. Colored per-identity SAM3 mask video at the same resolution as pose_video." + } + ], + "replacement_mode": [ + "BOOLEAN", + { + "tooltip": "SCAIL-2 only. False = Animation Mode (pose_video_mask should have black background). True = Replacement Mode (pose_video_mask should have white background).", + "default": false + } + ], + "reference_image": [ + "IMAGE", + { + "tooltip": "Reference image. The first image is the primary reference (composite all identities onto it). SCAIL-2: extra batch images are used as additional views (back view, close-up, occluded background), each needing a matching reference_image_mask in that identity's color." + } + ], + "reference_image_mask": [ + "IMAGE", + { + "tooltip": "SCAIL-2 only. Colored reference mask, batch matching reference_image (first = primary reference mask, rest = identity masks for the additional reference_image)." + } + ], + "clip_vision_output": [ + "CLIP_VISION_OUTPUT", + { + "tooltip": "CLIP vision features for conditioning. Model is trained with stretch resize to aspect ratio." + } + ], + "previous_frames": [ + "IMAGE", + { + "tooltip": "SCAIL-2 only. Full decoded output of the previous chunk. Only the last previous_frame_count are used as the extension anchor." + } + ] + } + } + }, + "KSampler": { + "input": { + "required": { + "model": [ + "MODEL", + { + "tooltip": "The model used for denoising the input latent." + } + ], + "seed": [ + "INT", + { + "default": 0, + "min": 0, + "max": 18446744073709551615, + "control_after_generate": true, + "tooltip": "The random seed used for creating the noise." + } + ], + "steps": [ + "INT", + { + "default": 20, + "min": 1, + "max": 10000, + "tooltip": "The number of steps used in the denoising process." + } + ], + "cfg": [ + "FLOAT", + { + "default": 8.0, + "min": 0.0, + "max": 100.0, + "step": 0.1, + "round": 0.01, + "tooltip": "The Classifier-Free Guidance scale balances creativity and adherence to the prompt. Higher values result in images more closely matching the prompt however too high values will negatively impact quality." + } + ], + "sampler_name": [ + [ + "euler", + "euler_cfg_pp", + "euler_ancestral", + "euler_ancestral_cfg_pp", + "heun", + "heunpp2", + "exp_heun_2_x0", + "exp_heun_2_x0_sde", + "dpm_2", + "dpm_2_ancestral", + "lms", + "dpm_fast", + "dpm_adaptive", + "dpmpp_2s_ancestral", + "dpmpp_2s_ancestral_cfg_pp", + "dpmpp_sde", + "dpmpp_sde_gpu", + "dpmpp_2m", + "dpmpp_2m_cfg_pp", + "dpmpp_2m_sde", + "dpmpp_2m_sde_gpu", + "dpmpp_2m_sde_heun", + "dpmpp_2m_sde_heun_gpu", + "dpmpp_3m_sde", + "dpmpp_3m_sde_gpu", + "ddpm", + "lcm", + "ipndm", + "ipndm_v", + "deis", + "cfgpp_ud10_ab", + "res_multistep", + "res_multistep_cfg_pp", + "res_multistep_ancestral", + "res_multistep_ancestral_cfg_pp", + "gradient_estimation", + "gradient_estimation_cfg_pp", + "er_sde", + "seeds_2", + "seeds_3", + "sa_solver", + "sa_solver_pece", + "ddim", + "uni_pc", + "uni_pc_bh2", + "legacy_rk", + "rk", + "rk_beta", + "deis_3m_ode", + "deis_2m_ode", + "deis_3m", + "deis_2m", + "res_6s_ode", + "res_5s_ode", + "res_3s_ode", + "res_2s_ode", + "res_3m_ode", + "res_2m_ode", + "res_6s", + "res_5s", + "res_3s", + "res_2s", + "res_3m", + "res_2m" + ], + { + "tooltip": "The algorithm used when sampling, this can affect the quality, speed, and style of the generated output." + } + ], + "scheduler": [ + [ + "simple", + "sgm_uniform", + "karras", + "exponential", + "ddim_uniform", + "beta", + "normal", + "linear_quadratic", + "kl_optimal", + "bong_tangent", + "beta57" + ], + { + "tooltip": "The scheduler controls how noise is gradually removed to form the image." + } + ], + "positive": [ + "CONDITIONING", + { + "tooltip": "The conditioning describing the attributes you want to include in the image." + } + ], + "negative": [ + "CONDITIONING", + { + "tooltip": "The conditioning describing the attributes you want to exclude from the image." + } + ], + "latent_image": [ + "LATENT", + { + "tooltip": "The latent image to denoise." + } + ], + "denoise": [ + "FLOAT", + { + "default": 1.0, + "min": 0.0, + "max": 1.0, + "step": 0.01, + "tooltip": "The amount of denoising applied, lower values will maintain the structure of the initial image allowing for image to image sampling." + } + ] + } + } + }, + "VAEDecode": { + "input": { + "required": { + "samples": [ + "LATENT", + { + "tooltip": "The latent to be decoded." + } + ], + "vae": [ + "VAE", + { + "tooltip": "The VAE model used for decoding the latent." + } + ] + } + } + }, + "VHS_VideoCombine": { + "input": { + "required": { + "images": [ + "IMAGE" + ], + "frame_rate": [ + "FLOAT", + { + "default": 8, + "min": 1, + "step": 1 + } + ], + "loop_count": [ + "INT", + { + "default": 0, + "min": 0, + "max": 100, + "step": 1 + } + ], + "filename_prefix": [ + "STRING", + { + "default": "AnimateDiff" + } + ], + "format": [ + [ + "image/gif", + "image/webp", + "video/ffmpeg-gif", + "video/h264-mp4", + "video/h265-mp4", + "video/webm" + ], + { + "formats": { + "video/ffmpeg-gif": [ + [ + "dither", + [ + "bayer", + "heckbert", + "floyd_steinberg", + "sierra2", + "sierra2_4a", + "sierra3", + "burkes", + "atkinson", + "none" + ], + { + "default": "sierra2_4a" + }, + "[0:v] split [a][b]; [a] palettegen=reserve_transparent=on:transparency_color=ffffff [p]; [b][p] paletteuse=dither=$val" + ] + ], + "video/h264-mp4": [ + [ + "pix_fmt", + [ + "yuv420p", + "yuv420p10le" + ] + ], + [ + "crf", + "INT", + { + "default": 19, + "min": 0, + "max": 100, + "step": 1 + } + ], + [ + "save_metadata", + "BOOLEAN", + { + "default": true + } + ], + [ + "trim_to_audio", + "BOOLEAN", + { + "default": false + } + ] + ], + "video/h265-mp4": [ + [ + "pix_fmt", + [ + "yuv420p10le", + "yuv420p" + ] + ], + [ + "crf", + "INT", + { + "default": 22, + "min": 0, + "max": 100, + "step": 1 + } + ], + [ + "save_metadata", + "BOOLEAN", + { + "default": true + } + ] + ], + "video/webm": [ + [ + "pix_fmt", + [ + "yuv420p", + "yuva420p" + ] + ], + [ + "crf", + "INT", + { + "default": 20, + "min": 0, + "max": 100, + "step": 1 + } + ], + [ + "save_metadata", + "BOOLEAN", + { + "default": true + } + ], + [ + "trim_to_audio", + "BOOLEAN", + { + "default": false + } + ] + ], + "image/webp": [ + [ + "lossless", + "BOOLEAN", + { + "default": true + } + ] + ] + } + } + ], + "pingpong": [ + "BOOLEAN", + { + "default": false + } + ], + "save_output": [ + "BOOLEAN", + { + "default": true + } + ] + }, + "optional": { + "audio": [ + "AUDIO" + ], + "meta_batch": [ + "VHS_BatchManager" + ], + "vae": [ + "VAE" + ] + }, + "hidden": { + "prompt": "PROMPT", + "extra_pnginfo": "EXTRA_PNGINFO", + "unique_id": "UNIQUE_ID" + } + } + }, + "GetImageRangeFromBatch": { + "input": { + "required": { + "start_index": [ + "INT", + { + "default": 0, + "min": -1, + "max": 4096, + "step": 1 + } + ], + "num_frames": [ + "INT", + { + "default": 1, + "min": 1, + "max": 4096, + "step": 1 + } + ] + }, + "optional": { + "images": [ + "IMAGE" + ], + "masks": [ + "MASK" + ] + } + } + }, + "RepeatImageBatch": { + "input": { + "required": { + "image": [ + "IMAGE", + {} + ], + "amount": [ + "INT", + { + "default": 1, + "min": 1, + "max": 4096 + } + ] + } + } + }, + "BatchImagesNode": { + "input": { + "required": { + "images": [ + "COMFY_AUTOGROW_V3", + { + "template": { + "input": { + "required": { + "image": [ + "IMAGE", + {} + ] + } + }, + "prefix": "image", + "min": 1, + "max": 50 + } + } + ] + } + } + } +} diff --git a/scripts/fixtures/r30/provenance.json b/scripts/fixtures/r30/provenance.json new file mode 100644 index 0000000..3ff9788 --- /dev/null +++ b/scripts/fixtures/r30/provenance.json @@ -0,0 +1,10 @@ +{ + "at": 1794400000.0, + "method": "synthetic fixture: provider GET response shapes; identifiers, hashes, sizes and times are made up", + "sources": [ + "RunningHub /object_info /history /queue", + "Comfy Cloud /api/jobs and /workflow" + ], + "original_request": "00000000-0000-4000-8000-00000000d001", + "no_submissions": true +} diff --git a/scripts/fixtures/r30/runninghub-absence.json b/scripts/fixtures/r30/runninghub-absence.json new file mode 100644 index 0000000..b209f37 --- /dev/null +++ b/scripts/fixtures/r30/runninghub-absence.json @@ -0,0 +1,7 @@ +{ + "history": {}, + "queue": { + "queue_running": [], + "queue_pending": [] + } +} diff --git a/scripts/fixtures/r30/runninghub-graph-schema.json b/scripts/fixtures/r30/runninghub-graph-schema.json new file mode 100644 index 0000000..aa6ff8b --- /dev/null +++ b/scripts/fixtures/r30/runninghub-graph-schema.json @@ -0,0 +1,1806 @@ +{ + "UNETLoader": { + "input": { + "required": { + "unet_name": [ + [ + "wan2.1_14B_SCAIL_2_fp8_scaled.safetensors" + ] + ], + "weight_dtype": [ + [ + "default", + "fp8_e4m3fn", + "fp8_e4m3fn_fast", + "fp8_e5m2" + ], + { + "advanced": true + } + ] + } + } + }, + "LoraLoader": { + "input": { + "required": { + "model": [ + "MODEL", + { + "tooltip": "The diffusion model the LoRA will be applied to." + } + ], + "clip": [ + "CLIP", + { + "tooltip": "The CLIP model the LoRA will be applied to." + } + ], + "lora_name": [ + [ + "Wan21_I2V_14B_lightx2v_cfg_step_distill_lora_rank64_official.safetensors" + ], + { + "tooltip": "The name of the LoRA." + } + ], + "strength_model": [ + "FLOAT", + { + "default": 1.0, + "min": -100.0, + "max": 100.0, + "step": 0.01, + "tooltip": "How strongly to modify the diffusion model. This value can be negative." + } + ], + "strength_clip": [ + "FLOAT", + { + "default": 1.0, + "min": -100.0, + "max": 100.0, + "step": 0.01, + "tooltip": "How strongly to modify the CLIP model. This value can be negative." + } + ] + } + } + }, + "ModelSamplingSD3": { + "input": { + "required": { + "model": [ + "MODEL" + ], + "shift": [ + "FLOAT", + { + "default": 3.0, + "min": 0.0, + "max": 100.0, + "step": 0.01 + } + ] + } + } + }, + "WanContextWindowsManual": { + "input": { + "required": { + "model": [ + "MODEL", + { + "tooltip": "The model to apply context windows to during sampling." + } + ], + "context_length": [ + "INT", + { + "tooltip": "The length of the context window in real frames. Must be 4*n + 1.", + "default": 81, + "min": 1, + "max": 16384, + "step": 4 + } + ], + "context_overlap": [ + "INT", + { + "tooltip": "The overlap of the context window in real frames.", + "default": 30, + "min": 0 + } + ], + "context_schedule": [ + "COMBO", + { + "tooltip": "Step-dependent scheduling algorithm for context windows.", + "default": "standard_uniform", + "multiselect": false, + "options": [ + "standard_static", + "standard_uniform", + "looped_uniform", + "batched" + ] + } + ], + "context_stride": [ + "INT", + { + "tooltip": "The stride of the context window; only applicable to uniform schedules.", + "advanced": true, + "default": 1, + "min": 1 + } + ], + "closed_loop": [ + "BOOLEAN", + { + "tooltip": "Whether to close the context window loop; only applicable to looped schedules.", + "advanced": true, + "default": false + } + ], + "fuse_method": [ + "COMBO", + { + "tooltip": "The method to use to fuse the context windows.", + "default": "pyramid", + "multiselect": false, + "options": [ + "pyramid", + "relative", + "flat", + "overlap-linear" + ] + } + ], + "freenoise": [ + "BOOLEAN", + { + "tooltip": "Whether to apply FreeNoise noise shuffling, improves window blending.", + "advanced": true, + "default": true + } + ], + "retain_first_frame": [ + "BOOLEAN", + { + "tooltip": "Retain the first I2V frame in every context window (may help retain initial reference).", + "default": false + } + ], + "split_conds_to_windows": [ + "BOOLEAN", + { + "tooltip": "Whether to split multiple conditionings (created by ConditionCombine) to each window based on region index.", + "advanced": true, + "default": false + } + ] + } + } + }, + "CLIPLoader": { + "input": { + "required": { + "clip_name": [ + [ + "umt5_xxl_fp8_e4m3fn_scaled.safetensors" + ] + ], + "type": [ + [ + "stable_diffusion", + "stable_cascade", + "sd3", + "stable_audio", + "mochi", + "ltxv", + "pixart", + "cosmos", + "lumina2", + "wan", + "hidream", + "chroma", + "ace", + "omnigen2", + "qwen_image", + "hunyuan_image", + "flux2", + "ovis", + "longcat_image", + "cogvideox", + "lens", + "pixeldit", + "ideogram4", + "boogu", + "krea2", + "joyimage", + "mage", + "minimax", + "yue2", + "flux3", + "moss_image", + "fibo2" + ] + ] + }, + "optional": { + "device": [ + [ + "default", + "cpu" + ], + { + "advanced": true + } + ] + } + } + }, + "CLIPTextEncode": { + "input": { + "required": { + "text": [ + "STRING", + { + "multiline": true, + "dynamicPrompts": true, + "tooltip": "The text to be encoded." + } + ], + "clip": [ + "CLIP", + { + "tooltip": "The CLIP model used for encoding the text." + } + ] + } + } + }, + "VAELoader": { + "input": { + "required": { + "vae_name": [ + [ + "wan_2.1_vae.safetensors" + ] + ] + } + } + }, + "CLIPVisionLoader": { + "input": { + "required": { + "clip_name": [ + [ + "clip_vision_h.safetensors" + ] + ] + } + } + }, + "LoadImage": { + "input": { + "required": { + "image": [ + [], + { + "image_upload": true + } + ] + } + } + }, + "ResizeImageMaskNode": { + "input": { + "required": { + "input": [ + "COMFY_MATCHTYPE_V3", + { + "template": { + "template_id": "input_type", + "allowed_types": "IMAGE,MASK" + } + } + ], + "resize_type": [ + "COMFY_DYNAMICCOMBO_V3", + { + "tooltip": "Select how to resize: by exact dimensions, scale factor, matching another image, etc.", + "options": [ + { + "key": "scale dimensions", + "inputs": { + "required": { + "width": [ + "INT", + { + "tooltip": "Target width in pixels. Set to 0 to auto-calculate from height while preserving aspect ratio.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ], + "height": [ + "INT", + { + "tooltip": "Target height in pixels. Set to 0 to auto-calculate from width while preserving aspect ratio.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ], + "crop": [ + "COMBO", + { + "tooltip": "How to handle aspect ratio mismatch: 'disabled' stretches to fit, 'center' crops to maintain aspect ratio.", + "default": "center", + "multiselect": false, + "options": [ + "disabled", + "center" + ] + } + ] + } + } + }, + { + "key": "scale by multiplier", + "inputs": { + "required": { + "multiplier": [ + "FLOAT", + { + "tooltip": "Scale factor (e.g., 2.0 doubles size, 0.5 halves size).", + "default": 1.0, + "min": 0.01, + "max": 8.0, + "step": 0.01 + } + ] + } + } + }, + { + "key": "scale longer dimension", + "inputs": { + "required": { + "longer_size": [ + "INT", + { + "tooltip": "The longer edge will be resized to this value. Aspect ratio is preserved.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ] + } + } + }, + { + "key": "scale shorter dimension", + "inputs": { + "required": { + "shorter_size": [ + "INT", + { + "tooltip": "The shorter edge will be resized to this value. Aspect ratio is preserved.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ] + } + } + }, + { + "key": "scale width", + "inputs": { + "required": { + "width": [ + "INT", + { + "tooltip": "Target width in pixels. Height auto-adjusts to preserve aspect ratio.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ] + } + } + }, + { + "key": "scale height", + "inputs": { + "required": { + "height": [ + "INT", + { + "tooltip": "Target height in pixels. Width auto-adjusts to preserve aspect ratio.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ] + } + } + }, + { + "key": "scale total pixels", + "inputs": { + "required": { + "megapixels": [ + "FLOAT", + { + "tooltip": "Target total megapixels (e.g., 1.0 \u2248 1024\u00d71024). Aspect ratio is preserved.", + "default": 1.0, + "min": 0.01, + "max": 16.0, + "step": 0.01 + } + ] + } + } + }, + { + "key": "match size", + "inputs": { + "required": { + "match": [ + "IMAGE,MASK", + { + "tooltip": "Resize input to match the dimensions of this reference image or mask." + } + ], + "crop": [ + "COMBO", + { + "tooltip": "How to handle aspect ratio mismatch: 'disabled' stretches to fit, 'center' crops to maintain aspect ratio.", + "default": "center", + "multiselect": false, + "options": [ + "disabled", + "center" + ] + } + ] + } + } + }, + { + "key": "scale to multiple", + "inputs": { + "required": { + "multiple": [ + "INT", + { + "tooltip": "Resize so width and height are divisible by this number. Useful for latent alignment (e.g., 8 or 64).", + "default": 8, + "min": 1, + "max": 16384, + "step": 1 + } + ] + } + } + } + ] + } + ], + "scale_method": [ + "COMBO", + { + "tooltip": "Interpolation algorithm. 'area' is best for downscaling, 'lanczos' for upscaling, 'nearest-exact' for pixel art.", + "default": "area", + "multiselect": false, + "options": [ + "nearest-exact", + "bilinear", + "area", + "bicubic", + "lanczos" + ] + } + ] + } + } + }, + "CLIPVisionEncode": { + "input": { + "required": { + "clip_vision": [ + "CLIP_VISION" + ], + "image": [ + "IMAGE" + ], + "crop": [ + [ + "center", + "none" + ] + ] + } + } + }, + "GetImageSize": { + "input": { + "required": { + "image": [ + "IMAGE", + {} + ] + }, + "hidden": { + "unique_id": [ + "UNIQUE_ID" + ] + } + } + }, + "VHS_LoadVideo": { + "input": { + "required": { + "video": [ + "STRING", + { + "default": "None", + "vhs_path_extensions": [ + "webm", + "mp4", + "mkv", + "gif", + "mov" + ] + } + ], + "force_rate": [ + "INT", + { + "default": 0, + "min": 0, + "max": 60, + "step": 1 + } + ], + "force_size": [ + [ + "Disabled", + "Custom Height", + "Custom Width", + "Custom", + "256x?", + "?x256", + "256x256", + "512x?", + "?x512", + "512x512" + ] + ], + "custom_width": [ + "INT", + { + "default": 0, + "min": 0, + "max": 8192, + "step": 8 + } + ], + "custom_height": [ + "INT", + { + "default": 0, + "min": 0, + "max": 8192, + "step": 8 + } + ], + "frame_load_cap": [ + "INT", + { + "default": 0, + "min": 0, + "max": 9007199254740991, + "step": 1 + } + ], + "skip_first_frames": [ + "INT", + { + "default": 0, + "min": 0, + "max": 9007199254740991, + "step": 1 + } + ], + "select_every_nth": [ + "INT", + { + "default": 1, + "min": 1, + "max": 9007199254740991, + "step": 1 + } + ] + }, + "optional": { + "meta_batch": [ + "VHS_BatchManager" + ], + "vae": [ + "VAE" + ], + "format": [ + [ + "None", + "AnimateDiff", + "Mochi", + "LTXV", + "Hunyuan", + "Cosmos", + "Wan" + ], + { + "default": "AnimateDiff", + "formats": { + "None": {}, + "AnimateDiff": { + "target_rate": 8, + "dim": [ + 8, + 0, + 512, + 512 + ] + }, + "Mochi": { + "target_rate": 24, + "dim": [ + 16, + 0, + 848, + 480 + ], + "frames": [ + 6, + 1 + ] + }, + "LTXV": { + "target_rate": 24, + "dim": [ + 32, + 0, + 768, + 512 + ], + "frames": [ + 8, + 1 + ] + }, + "Hunyuan": { + "target_rate": 24, + "dim": [ + 16, + 0, + 848, + 480 + ], + "frames": [ + 4, + 1 + ] + }, + "Cosmos": { + "target_rate": 24, + "dim": [ + 16, + 0, + 1280, + 704 + ], + "frames": [ + 8, + 1 + ] + }, + "Wan": { + "target_rate": 16, + "dim": [ + 8, + 0, + 832, + 480 + ], + "frames": [ + 4, + 1 + ] + } + } + } + ] + }, + "hidden": { + "force_size": "STRING", + "unique_id": "UNIQUE_ID" + } + } + }, + "CheckpointLoaderSimple": { + "input": { + "required": { + "ckpt_name": [ + [ + "sam3.1_multiplex_fp16.safetensors" + ], + { + "tooltip": "The name of the checkpoint (model) to load." + } + ] + } + } + }, + "SAM3_VideoTrack": { + "input": { + "required": { + "images": [ + "IMAGE", + { + "display_name": "images", + "tooltip": "Video frames as batched images" + } + ], + "model": [ + "MODEL", + { + "display_name": "model" + } + ], + "detection_threshold": [ + "FLOAT", + { + "display_name": "detection_threshold", + "tooltip": "Score threshold for text-prompted detection.", + "default": 0.5, + "min": 0.0, + "max": 1.0, + "step": 0.01 + } + ], + "max_objects": [ + "INT", + { + "display_name": "max_objects", + "tooltip": "Max tracked objects. Initial masks count toward this limit. 0 uses the internal cap of 64.", + "default": 4, + "min": 0, + "max": 64 + } + ], + "detect_interval": [ + "INT", + { + "display_name": "detect_interval", + "tooltip": "Run detection every N frames (1=every frame). Higher values save compute.", + "default": 1, + "min": 1 + } + ] + }, + "optional": { + "initial_mask": [ + "MASK", + { + "display_name": "initial_mask", + "tooltip": "Mask(s) for the first frame to track (one per object)" + } + ], + "conditioning": [ + "CONDITIONING", + { + "display_name": "conditioning", + "tooltip": "Text conditioning for detecting new objects during tracking" + } + ] + } + } + }, + "SCAIL2ColoredMask": { + "input": { + "required": { + "driving_track_data": [ + "SAM3_TRACK_DATA", + { + "tooltip": "SAM3 track of the driving pose video. Will be rendered into the pose_video_mask output." + } + ], + "object_indices": [ + "STRING", + { + "tooltip": "Comma-separated list of person indices to include (e.g. '0,2,3'). Applied to both reference and pose video masks. Empty = all.", + "default": "", + "multiline": false + } + ], + "sort_by": [ + "COMBO", + { + "tooltip": "Order in which palette colors are assigned to the tracked objects (applied to both reference and pose video so each identity keeps the same color). Objects that appear in earlier frames always come first; within a frame, left_to_right = leftmost object (by centroid at first appearance) gets the first color, area = biggest object (by mask area at first appearance) gets the first color; none = keep SAM3's order.", + "default": "left_to_right", + "multiselect": false, + "options": [ + "none", + "left_to_right", + "area" + ] + } + ], + "replacement_mode": [ + "BOOLEAN", + { + "tooltip": "False = Animation Mode (pose_video_mask has black background, reference_image_mask has white background). True = Replacement Mode (pose_video_mask has white background, reference_image_mask has black background).", + "default": false + } + ] + }, + "optional": { + "ref_track_data": [ + "SAM3_TRACK_DATA,MASK", + { + "display_name": "reference_masks", + "tooltip": "SAM3 track of the reference image(s) (one identity per object, colored in batch order), or a plain MASK of the reference subject (rendered as a single identity)." + } + ] + } + } + }, + "WanSCAILToVideo": { + "input": { + "required": { + "positive": [ + "CONDITIONING", + {} + ], + "negative": [ + "CONDITIONING", + {} + ], + "vae": [ + "VAE", + {} + ], + "width": [ + "INT", + { + "default": 512, + "min": 32, + "max": 16384, + "step": 32 + } + ], + "height": [ + "INT", + { + "default": 896, + "min": 32, + "max": 16384, + "step": 32 + } + ], + "length": [ + "INT", + { + "default": 81, + "min": 1, + "max": 16384, + "step": 4 + } + ], + "batch_size": [ + "INT", + { + "default": 1, + "min": 1, + "max": 4096 + } + ], + "pose_strength": [ + "FLOAT", + { + "tooltip": "Strength of the pose latent.", + "default": 1.0, + "min": 0.0, + "max": 10.0, + "step": 0.01 + } + ], + "pose_start": [ + "FLOAT", + { + "tooltip": "Start step of the pose conditioning.", + "default": 0.0, + "min": 0.0, + "max": 1.0, + "step": 0.01 + } + ], + "pose_end": [ + "FLOAT", + { + "tooltip": "End step of the pose conditioning.", + "default": 1.0, + "min": 0.0, + "max": 1.0, + "step": 0.01 + } + ], + "video_frame_offset": [ + "INT", + { + "tooltip": "Cumulative output frame this chunk begins at. Wire from the previous chunk's video_frame_offset output.", + "default": 0, + "min": 0, + "max": 16384, + "step": 1 + } + ], + "previous_frame_count": [ + "INT", + { + "tooltip": "Tail frames of previous_frames to anchor. SCAIL-2 trained at 5 (81-frame chunks, 76-frame step).", + "default": 5, + "min": 1, + "max": 16384, + "step": 4 + } + ] + }, + "optional": { + "pose_video": [ + "IMAGE", + { + "tooltip": "Video used for pose conditioning. Will be downscaled to half the resolution of the main video." + } + ], + "pose_video_mask": [ + "IMAGE", + { + "tooltip": "SCAIL-2 only. Colored per-identity SAM3 mask video at the same resolution as pose_video." + } + ], + "replacement_mode": [ + "BOOLEAN", + { + "tooltip": "SCAIL-2 only. False = Animation Mode (pose_video_mask should have black background). True = Replacement Mode (pose_video_mask should have white background).", + "default": false + } + ], + "reference_image": [ + "IMAGE", + { + "tooltip": "Reference image. The first image is the primary reference (composite all identities onto it). SCAIL-2: extra batch images are used as additional views (back view, close-up, occluded background), each needing a matching reference_image_mask in that identity's color." + } + ], + "reference_image_mask": [ + "IMAGE", + { + "tooltip": "SCAIL-2 only. Colored reference mask, batch matching reference_image (first = primary reference mask, rest = identity masks for the additional reference_image)." + } + ], + "clip_vision_output": [ + "CLIP_VISION_OUTPUT", + { + "tooltip": "CLIP vision features for conditioning. Model is trained with stretch resize to aspect ratio." + } + ], + "previous_frames": [ + "IMAGE", + { + "tooltip": "SCAIL-2 only. Full decoded output of the previous chunk. Only the last previous_frame_count are used as the extension anchor." + } + ] + } + } + }, + "KSampler": { + "input": { + "required": { + "model": [ + "MODEL", + { + "tooltip": "The model used for denoising the input latent." + } + ], + "seed": [ + "INT", + { + "default": 0, + "min": 0, + "max": 18446744073709551615, + "control_after_generate": true, + "tooltip": "The random seed used for creating the noise." + } + ], + "steps": [ + "INT", + { + "default": 20, + "min": 1, + "max": 10000, + "tooltip": "The number of steps used in the denoising process." + } + ], + "cfg": [ + "FLOAT", + { + "default": 8.0, + "min": 0.0, + "max": 100.0, + "step": 0.1, + "round": 0.01, + "tooltip": "The Classifier-Free Guidance scale balances creativity and adherence to the prompt. Higher values result in images more closely matching the prompt however too high values will negatively impact quality." + } + ], + "sampler_name": [ + [ + "euler", + "euler_cfg_pp", + "euler_ancestral", + "euler_ancestral_cfg_pp", + "heun", + "heunpp2", + "exp_heun_2_x0", + "exp_heun_2_x0_sde", + "dpm_2", + "dpm_2_ancestral", + "lms", + "dpm_fast", + "dpm_adaptive", + "dpmpp_2s_ancestral", + "dpmpp_2s_ancestral_cfg_pp", + "dpmpp_sde", + "dpmpp_sde_gpu", + "dpmpp_2m", + "dpmpp_2m_alt", + "dpmpp_2m_cfg_pp", + "dpmpp_2m_sde", + "dpmpp_2m_sde_gpu", + "dpmpp_2m_sde_heun", + "dpmpp_2m_sde_heun_gpu", + "dpmpp_3m_sde", + "dpmpp_3m_sde_gpu", + "ddpm", + "lcm", + "ipndm", + "ipndm_v", + "deis", + "cfgpp_ud10_ab", + "res_multistep", + "res_multistep_cfg_pp", + "res_multistep_ancestral", + "res_multistep_ancestral_cfg_pp", + "gradient_estimation", + "gradient_estimation_cfg_pp", + "er_sde", + "seeds_2", + "seeds_3", + "sa_solver", + "sa_solver_ode_stable", + "sa_solver_pece", + "ddim", + "uni_pc", + "uni_pc_bh2", + "legacy_rk", + "rk", + "rk_beta", + "deis_3m_ode", + "deis_2m_ode", + "deis_3m", + "deis_2m", + "res_6s_ode", + "res_5s_ode", + "res_3s_ode", + "res_2s_ode", + "res_3m_ode", + "res_2m_ode", + "res_6s", + "res_5s", + "res_3s", + "res_2s", + "res_3m", + "res_2m", + "supreme", + "dpmpp_3m_sde_dynamic_eta", + "euler_ancestral_dancing", + "lcm_custom_noise", + "ttm", + "clyb_4m_sde_momentumized", + "dpmpp_dualsde_momentumized", + "res_momentumized", + "stork2", + "stork4", + "bleh_preset_0", + "hfe_s1", + "hfe_s2", + "hfe_s3", + "hfe_s4", + "hfe_s5", + "hfe_s6", + "hfe_s7", + "hfe_s8", + "hfe3_s1", + "hfe3_s2", + "hfe3_s3", + "hfe3_s4", + "hfe3_s5", + "hfe3_s6", + "hfe3_s7", + "hfe3_s8", + "hfe4_s1", + "hfe4_s2", + "hfe4_s3", + "hfe4_s4", + "hfe4_s5", + "hfe4_s6", + "hfe4_s7", + "hfe4_s8", + "hfe5_s1", + "hfe5_s2", + "hfe5_s3", + "hfe5_s4", + "hfe5_s5", + "hfe5_s6", + "hfe5_s7", + "hfe5_s8", + "hfe_auto", + "hfe3_auto", + "hfe4_auto", + "hfe5_auto", + "hfx_sharp", + "hfx_boost", + "hfx_detail", + "hfx_stochastic", + "hfx_momentum", + "hfx_spectral", + "hfx_orthogonal", + "hfx_refine", + "hfx_focus", + "hfx_coherence", + "hfx_sharp_s1", + "hfx_sharp_s2", + "hfx_sharp_s3", + "hfx_sharp_s4", + "hfx_boost_s1", + "hfx_boost_s2", + "hfx_boost_s3", + "hfx_boost_s4", + "hfx_detail_s1", + "hfx_detail_s2", + "hfx_detail_s3", + "hfx_detail_s4", + "hfx_stochastic_s1", + "hfx_stochastic_s2", + "hfx_stochastic_s3", + "hfx_stochastic_s4", + "hfx_momentum_s1", + "hfx_momentum_s2", + "hfx_momentum_s3", + "hfx_momentum_s4", + "hfx_spectral_s1", + "hfx_spectral_s2", + "hfx_spectral_s3", + "hfx_spectral_s4", + "hfx_orthogonal_s1", + "hfx_orthogonal_s2", + "hfx_orthogonal_s3", + "hfx_orthogonal_s4", + "hfx_refine_s1", + "hfx_refine_s2", + "hfx_refine_s3", + "hfx_refine_s4", + "hfx_focus_s1", + "hfx_focus_s2", + "hfx_focus_s3", + "hfx_focus_s4", + "hfx_coherence_s1", + "hfx_coherence_s2", + "hfx_coherence_s3", + "hfx_coherence_s4" + ], + { + "tooltip": "The algorithm used when sampling, this can affect the quality, speed, and style of the generated output." + } + ], + "scheduler": [ + [ + "simple", + "sgm_uniform", + "karras", + "exponential", + "ddim_uniform", + "beta", + "normal", + "linear_quadratic", + "kl_optimal", + "capitanZiT", + "FlowMatchEulerDiscreteScheduler", + "bong_tangent", + "beta57", + "ays", + "ays+", + "ays_30", + "ays_30+", + "gits", + "beta_1_1", + "power_shift", + "atan_gentle", + "atan_focused", + "atan_steep", + "karras_tan", + "logistic" + ], + { + "tooltip": "The scheduler controls how noise is gradually removed to form the image." + } + ], + "positive": [ + "CONDITIONING", + { + "tooltip": "The conditioning describing the attributes you want to include in the image." + } + ], + "negative": [ + "CONDITIONING", + { + "tooltip": "The conditioning describing the attributes you want to exclude from the image." + } + ], + "latent_image": [ + "LATENT", + { + "tooltip": "The latent image to denoise." + } + ], + "denoise": [ + "FLOAT", + { + "default": 1.0, + "min": 0.0, + "max": 1.0, + "step": 0.01, + "tooltip": "The amount of denoising applied, lower values will maintain the structure of the initial image allowing for image to image sampling." + } + ] + } + } + }, + "VAEDecode": { + "input": { + "required": { + "samples": [ + "LATENT", + { + "tooltip": "The latent to be decoded." + } + ], + "vae": [ + "VAE", + { + "tooltip": "The VAE model used for decoding the latent." + } + ] + } + } + }, + "VHS_VideoCombine": { + "input": { + "required": { + "images": [ + "IMAGE" + ], + "frame_rate": [ + "FLOAT", + { + "default": 8, + "min": 1, + "step": 1 + } + ], + "loop_count": [ + "INT", + { + "default": 0, + "min": 0, + "max": 100, + "step": 1 + } + ], + "filename_prefix": [ + "STRING", + { + "default": "AnimateDiff" + } + ], + "format": [ + [ + "video/h264-mp4", + "image/gif", + "image/webp", + "video/16bit-png", + "video/8bit-png", + "video/ProRes", + "video/av1-webm", + "video/ffmpeg-gif", + "video/ffv1-mkv", + "video/h264-mp4", + "video/h265-mp4", + "video/mov", + "video/nvenc_av1-mp4", + "video/webm" + ], + { + "formats": { + "video/ProRes": [ + [ + "profile", + [ + "1", + "2", + "3", + "4" + ], + { + "default": "3" + } + ] + ], + "video/av1-webm": [ + [ + "pix_fmt", + [ + "yuv420p10le", + "yuv420p" + ] + ], + [ + "crf", + "INT", + { + "default": 23, + "min": 0, + "max": 100, + "step": 1 + } + ], + [ + "input_color_depth", + [ + "8bit", + "16bit" + ] + ], + [ + "save_metadata", + "BOOLEAN", + { + "default": true + } + ] + ], + "video/ffmpeg-gif": [ + [ + "dither", + [ + "bayer", + "heckbert", + "floyd_steinberg", + "sierra2", + "sierra2_4a", + "sierra3", + "burkes", + "atkinson", + "none" + ], + { + "default": "sierra2_4a" + }, + "[0:v] split [a][b]; [a] palettegen=reserve_transparent=on:transparency_color=ffffff [p]; [b][p] paletteuse=dither=$val" + ] + ], + "video/ffv1-mkv": [ + [ + "level", + [ + "0", + "1", + "3" + ], + { + "default": "3" + } + ], + [ + "coder", + [ + "0", + "1", + "2" + ], + { + "default": "1" + } + ], + [ + "context", + [ + "0", + "1" + ], + { + "default": "1" + } + ], + [ + "gop_size", + "INT", + { + "default": 1, + "min": 1, + "max": 300, + "step": 1 + } + ], + [ + "slices", + [ + "4", + "6", + "9", + "12", + "16", + "20", + "24", + "30" + ], + { + "default": "16" + } + ], + [ + "slicecrc", + [ + "0", + "1" + ], + { + "default": "1" + } + ], + [ + "pix_fmt", + [ + "rgba64le", + "bgra", + "yuv420p", + "yuv422p", + "yuv444p", + "yuva420p", + "yuva422p", + "yuva444p", + "yuv420p10le", + "yuv422p10le", + "yuv444p10le", + "yuv420p12le", + "yuv422p12le", + "yuv444p12le", + "yuv420p14le", + "yuv422p14le", + "yuv444p14le", + "yuv420p16le", + "yuv422p16le", + "yuv444p16le", + "gray", + "gray10le", + "gray12le", + "gray16le" + ], + { + "default": "rgba64le" + } + ], + [ + "save_metadata", + "BOOLEAN", + { + "default": true + } + ], + [ + "trim_to_audio", + "BOOLEAN", + { + "default": false + } + ] + ], + "video/h264-mp4": [ + [ + "pix_fmt", + [ + "yuv420p", + "yuv420p10le" + ] + ], + [ + "crf", + "INT", + { + "default": 19, + "min": 0, + "max": 100, + "step": 1 + } + ], + [ + "save_metadata", + "BOOLEAN", + { + "default": true + } + ], + [ + "trim_to_audio", + "BOOLEAN", + { + "default": false + } + ] + ], + "video/h265-mp4": [ + [ + "pix_fmt", + [ + "yuv420p10le", + "yuv420p" + ] + ], + [ + "crf", + "INT", + { + "default": 22, + "min": 0, + "max": 100, + "step": 1 + } + ], + [ + "save_metadata", + "BOOLEAN", + { + "default": true + } + ] + ], + "video/mov": [ + [ + "crf", + "INT", + { + "default": 23, + "min": 0, + "max": 100, + "step": 1 + } + ], + [ + "save_metadata", + "BOOLEAN", + { + "default": true + } + ] + ], + "video/nvenc_av1-mp4": [ + [ + "pix_fmt", + [ + "yuv420p", + "p010le" + ] + ], + [ + "bitrate", + "INT", + { + "default": 10, + "min": 1, + "max": 999, + "step": 1 + } + ], + [ + "megabit", + "BOOLEAN", + { + "default": true + } + ], + [ + "save_metadata", + "BOOLEAN", + { + "default": true + } + ] + ], + "video/webm": [ + [ + "pix_fmt", + [ + "yuv420p", + "yuva420p" + ] + ], + [ + "crf", + "INT", + { + "default": 20, + "min": 0, + "max": 100, + "step": 1 + } + ], + [ + "save_metadata", + "BOOLEAN", + { + "default": true + } + ], + [ + "trim_to_audio", + "BOOLEAN", + { + "default": false + } + ] + ], + "image/webp": [ + [ + "lossless", + "BOOLEAN", + { + "default": true + } + ] + ] + } + } + ], + "pingpong": [ + "BOOLEAN", + { + "default": false + } + ], + "save_output": [ + "BOOLEAN", + { + "default": true + } + ] + }, + "optional": { + "audio": [ + "AUDIO" + ], + "meta_batch": [ + "VHS_BatchManager" + ], + "vae": [ + "VAE" + ], + "no_preview": [ + "BOOLEAN", + { + "default": false + } + ] + }, + "hidden": { + "prompt": "PROMPT", + "extra_pnginfo": "EXTRA_PNGINFO", + "unique_id": "UNIQUE_ID" + } + } + }, + "GetImageRangeFromBatch": { + "input": { + "required": { + "start_index": [ + "INT", + { + "default": 0, + "min": -1, + "max": 4096, + "step": 1 + } + ], + "num_frames": [ + "INT", + { + "default": 1, + "min": 1, + "max": 4096, + "step": 1 + } + ] + }, + "optional": { + "images": [ + "IMAGE" + ], + "masks": [ + "MASK" + ] + } + } + }, + "RepeatImageBatch": { + "input": { + "required": { + "image": [ + "IMAGE", + {} + ], + "amount": [ + "INT", + { + "default": 1, + "min": 1, + "max": 4096 + } + ] + } + } + }, + "BatchImagesNode": { + "input": { + "required": { + "images": [ + "COMFY_AUTOGROW_V3", + { + "template": { + "input": { + "required": { + "image": [ + "IMAGE", + {} + ] + } + }, + "prefix": "image", + "min": 1, + "max": 50 + } + } + ] + } + } + } +} diff --git a/scripts/fixtures/r30/runninghub-object-info.json b/scripts/fixtures/r30/runninghub-object-info.json new file mode 100644 index 0000000..acfcb14 --- /dev/null +++ b/scripts/fixtures/r30/runninghub-object-info.json @@ -0,0 +1,216 @@ +{ + "VHS_LoadVideo": { + "input": { + "required": { + "video": [ + "STRING", + { + "default": "None", + "vhs_path_extensions": [ + "webm", + "mp4", + "mkv", + "gif", + "mov" + ] + } + ], + "force_rate": [ + "INT", + { + "default": 0, + "min": 0, + "max": 60, + "step": 1 + } + ], + "force_size": [ + [ + "Disabled", + "Custom Height", + "Custom Width", + "Custom", + "256x?", + "?x256", + "256x256", + "512x?", + "?x512", + "512x512" + ] + ], + "custom_width": [ + "INT", + { + "default": 0, + "min": 0, + "max": 8192, + "step": 8 + } + ], + "custom_height": [ + "INT", + { + "default": 0, + "min": 0, + "max": 8192, + "step": 8 + } + ], + "frame_load_cap": [ + "INT", + { + "default": 0, + "min": 0, + "max": 9007199254740991, + "step": 1 + } + ], + "skip_first_frames": [ + "INT", + { + "default": 0, + "min": 0, + "max": 9007199254740991, + "step": 1 + } + ], + "select_every_nth": [ + "INT", + { + "default": 1, + "min": 1, + "max": 9007199254740991, + "step": 1 + } + ] + }, + "optional": { + "meta_batch": [ + "VHS_BatchManager" + ], + "vae": [ + "VAE" + ], + "format": [ + [ + "None", + "AnimateDiff", + "Mochi", + "LTXV", + "Hunyuan", + "Cosmos", + "Wan" + ], + { + "default": "AnimateDiff", + "formats": { + "None": {}, + "AnimateDiff": { + "target_rate": 8, + "dim": [ + 8, + 0, + 512, + 512 + ] + }, + "Mochi": { + "target_rate": 24, + "dim": [ + 16, + 0, + 848, + 480 + ], + "frames": [ + 6, + 1 + ] + }, + "LTXV": { + "target_rate": 24, + "dim": [ + 32, + 0, + 768, + 512 + ], + "frames": [ + 8, + 1 + ] + }, + "Hunyuan": { + "target_rate": 24, + "dim": [ + 16, + 0, + 848, + 480 + ], + "frames": [ + 4, + 1 + ] + }, + "Cosmos": { + "target_rate": 24, + "dim": [ + 16, + 0, + 1280, + 704 + ], + "frames": [ + 8, + 1 + ] + }, + "Wan": { + "target_rate": 16, + "dim": [ + 8, + 0, + 832, + 480 + ], + "frames": [ + 4, + 1 + ] + } + } + } + ] + }, + "hidden": { + "force_size": "STRING", + "unique_id": "UNIQUE_ID" + } + } + }, + "BatchImagesNode": { + "input": { + "required": { + "images": [ + "COMFY_AUTOGROW_V3", + { + "template": { + "input": { + "required": { + "image": [ + "IMAGE", + {} + ] + } + }, + "prefix": "image", + "min": 1, + "max": 50 + } + } + ] + } + } + } +} diff --git a/scripts/fixtures/r31/autoip-voice-25-to-50.json b/scripts/fixtures/r31/autoip-voice-25-to-50.json new file mode 100644 index 0000000..9e25882 --- /dev/null +++ b/scripts/fixtures/r31/autoip-voice-25-to-50.json @@ -0,0 +1,22 @@ +{ + "source": "synthetic", + "observed_at": 1794400000.0, + "pricing": { + "data": { + "voice_clone": { + "credits": 50, + "off_peak_credits": { + "credits": 25 + }, + "unit": null, + "billing": null + } + }, + "off_peak": { + "active_now": true + } + }, + "historical_quote": 25, + "actual_charge": 50, + "operation": "voice_clone" +} diff --git a/scripts/fixtures/r34/runninghub-resize-node.json b/scripts/fixtures/r34/runninghub-resize-node.json new file mode 100644 index 0000000..3272e88 --- /dev/null +++ b/scripts/fixtures/r34/runninghub-resize-node.json @@ -0,0 +1,248 @@ +{ + "input": { + "required": { + "input": [ + "COMFY_MATCHTYPE_V3", + { + "template": { + "template_id": "input_type", + "allowed_types": "IMAGE,MASK" + } + } + ], + "resize_type": [ + "COMFY_DYNAMICCOMBO_V3", + { + "tooltip": "Select how to resize: by exact dimensions, scale factor, matching another image, etc.", + "options": [ + { + "key": "scale dimensions", + "inputs": { + "required": { + "width": [ + "INT", + { + "tooltip": "Target width in pixels. Set to 0 to auto-calculate from height while preserving aspect ratio.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ], + "height": [ + "INT", + { + "tooltip": "Target height in pixels. Set to 0 to auto-calculate from width while preserving aspect ratio.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ], + "crop": [ + "COMBO", + { + "tooltip": "How to handle aspect ratio mismatch: 'disabled' stretches to fit, 'center' crops to maintain aspect ratio.", + "default": "center", + "multiselect": false, + "options": [ + "disabled", + "center" + ] + } + ] + } + } + }, + { + "key": "scale by multiplier", + "inputs": { + "required": { + "multiplier": [ + "FLOAT", + { + "tooltip": "Scale factor (e.g., 2.0 doubles size, 0.5 halves size).", + "default": 1.0, + "min": 0.01, + "max": 8.0, + "step": 0.01 + } + ] + } + } + }, + { + "key": "scale longer dimension", + "inputs": { + "required": { + "longer_size": [ + "INT", + { + "tooltip": "The longer edge will be resized to this value. Aspect ratio is preserved.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ] + } + } + }, + { + "key": "scale shorter dimension", + "inputs": { + "required": { + "shorter_size": [ + "INT", + { + "tooltip": "The shorter edge will be resized to this value. Aspect ratio is preserved.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ] + } + } + }, + { + "key": "scale width", + "inputs": { + "required": { + "width": [ + "INT", + { + "tooltip": "Target width in pixels. Height auto-adjusts to preserve aspect ratio.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ] + } + } + }, + { + "key": "scale height", + "inputs": { + "required": { + "height": [ + "INT", + { + "tooltip": "Target height in pixels. Width auto-adjusts to preserve aspect ratio.", + "default": 512, + "min": 0, + "max": 16384, + "step": 1 + } + ] + } + } + }, + { + "key": "scale total pixels", + "inputs": { + "required": { + "megapixels": [ + "FLOAT", + { + "tooltip": "Target total megapixels (e.g., 1.0 \u2248 1024\u00d71024). Aspect ratio is preserved.", + "default": 1.0, + "min": 0.01, + "max": 16.0, + "step": 0.01 + } + ] + } + } + }, + { + "key": "match size", + "inputs": { + "required": { + "match": [ + "IMAGE,MASK", + { + "tooltip": "Resize input to match the dimensions of this reference image or mask." + } + ], + "crop": [ + "COMBO", + { + "tooltip": "How to handle aspect ratio mismatch: 'disabled' stretches to fit, 'center' crops to maintain aspect ratio.", + "default": "center", + "multiselect": false, + "options": [ + "disabled", + "center" + ] + } + ] + } + } + }, + { + "key": "scale to multiple", + "inputs": { + "required": { + "multiple": [ + "INT", + { + "tooltip": "Resize so width and height are divisible by this number. Useful for latent alignment (e.g., 8 or 64).", + "default": 8, + "min": 1, + "max": 16384, + "step": 1 + } + ] + } + } + } + ] + } + ], + "scale_method": [ + "COMBO", + { + "tooltip": "Interpolation algorithm. 'area' is best for downscaling, 'lanczos' for upscaling, 'nearest-exact' for pixel art.", + "default": "area", + "multiselect": false, + "options": [ + "nearest-exact", + "bilinear", + "area", + "bicubic", + "lanczos" + ] + } + ] + } + }, + "input_order": { + "required": [ + "input", + "resize_type", + "scale_method" + ] + }, + "output": [ + "COMFY_MATCHTYPE_V3" + ], + "output_is_list": [ + false + ], + "output_name": [ + "resized" + ], + "name": "ResizeImageMaskNode", + "display_name": "Resize Image/Mask", + "description": "Resize an image or mask using various scaling methods.", + "python_module": "comfy_extras.nodes_post_processing", + "category": "image/transform", + "output_node": false, + "has_intermediate_output": false, + "output_tooltips": [ + null + ], + "api_node": false +} diff --git a/scripts/test_app_graph_catalog.py b/scripts/test_app_graph_catalog.py index b35e9f7..82054f9 100644 --- a/scripts/test_app_graph_catalog.py +++ b/scripts/test_app_graph_catalog.py @@ -1,5 +1,6 @@ """Topology, representative variants and privacy of static app diagrams.""" import ast +from collections import Counter import json from pathlib import Path import shutil @@ -11,7 +12,7 @@ ROOT=Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT)) -from scripts.app_graph_catalog import SOURCE_FILES, Source, graphs +from scripts.app_graph_catalog import SOURCE_FILES, Source, angles_delegation, graphs from scripts.app_guide_catalog import catalog @@ -205,3 +206,51 @@ def test_arbitrary_expression_calls_are_not_evaluated(tmp_path): source=Source(p) from scripts.app_graph_catalog import UNKNOWN assert source.value(ast.parse('X',mode='eval').body) is UNKNOWN + + +def test_angles_diagram_matches_qwen_edit_and_has_bilingual_notes(registry): + output=graphs(ROOT,registry) + angles=output['character-angles'] + edit=output['qwen21-edit'] + assert angles['source']=='webui/server.py#qwen21_angles_prompt' + assert Counter(n['type'] for n in angles['nodes'])==Counter(n['type'] for n in edit['nodes']) + assert angles['notes']==[ + '代表一張候選:每張候選各自以原始照片執行一次 Qwen 2.1 改圖,並加上自己的固定視角指令;不會串接前一張生成圖。', + '這是應用程式 builder 的連線,並非官方參考 JSON 的逐字複本。', + ] + assert angles['notes_en']==[ + 'Shows one candidate: each candidate runs one Qwen 2.1 edit on the original photo with its own fixed view instruction. A generated image is never chained into the next.', + 'These are application builder connections, not a verbatim copy of the official reference JSON.', + ] + + +def test_qwen_diagram_source_and_notes_remain_unchanged(registry): + output=graphs(ROOT,registry) + common='這是應用程式 builder 的連線,並非官方參考 JSON 的逐字複本。' + common_en='These are application builder connections, not a verbatim copy of the official reference JSON.' + expected={ + 'qwen21-edit':('代表分支:一張輸入圖片;實際改圖支援依序加入最多四張。', + 'Representative branch: one input image. Editing supports up to four images in sequence.'), + 'qwen21-text2img':('文生圖分支:ResolutionSelector 決定空白 latent 尺寸。', + 'Text-to-image branch: ResolutionSelector determines the empty latent dimensions.'), + } + for name,(note,note_en) in expected.items(): + graph=output[name] + assert graph['source']=='webui/qwen_image21.py#compile_prompt' + assert graph['notes']==[note,common] + assert graph['notes_en']==[note_en,common_en] + + +def test_angles_delegation_accepts_real_server_without_execution(): + angles_delegation(Source(ROOT/'webui/server.py')) + + +@pytest.mark.parametrize('calls',[ + "compile_qwen21_prompt(settings, {'image': face}, edit=False)", + "compile_qwen21_prompt(settings, {'image': face}, edit=True)\n compile_qwen21_prompt(settings, {'image': face}, edit=True)", +]) +def test_angles_delegation_rejects_changed_calls(tmp_path,calls): + path=tmp_path/'source.py' + path.write_text('def qwen21_angles_prompt(settings, face):\n '+calls+'\n') + with pytest.raises(ValueError,match='character-angles Qwen edit delegation changed'): + angles_delegation(Source(path)) diff --git a/scripts/test_character_original.py b/scripts/test_character_original.py new file mode 100644 index 0000000..657aa4a --- /dev/null +++ b/scripts/test_character_original.py @@ -0,0 +1,157 @@ +"""A8: canonical source survives binding and reaches an executed conditioning node.""" +import copy +import importlib.util +import sys +from pathlib import Path +from unittest.mock import patch +import pytest +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'webui')) +spec=importlib.util.spec_from_file_location('a8_server',ROOT/'webui/server.py') +server=importlib.util.module_from_spec(spec);spec.loader.exec_module(server) + +@pytest.fixture +def character(tmp_path): + image=tmp_path/'canonical.png';image.write_bytes(b'canonical test image') + return {'id':'fixture','name':'Fixture','kind':'example-character','visualClass':'anime','actions':[], '_test_path':image} + +@pytest.mark.parametrize('feature', sorted(server.CHARACTER_REFERENCE_SLOTS)) +def test_default_and_override(character,feature): + with patch.object(server,'character_asset_path',return_value=character['_test_path']): + files,receipt=server.bind_character_original(character,feature,{}) + slot=server.CHARACTER_REFERENCE_SLOTS[feature] + assert files[slot]['_characterAssetPath']==str(character['_test_path']) + assert receipt['sha256']==server.sha256_file(character['_test_path']) + override={slot:{'serverFile':'replacement.png'}} + bound,receipt=server.bind_character_original(character,feature,override) + assert bound==override and receipt['kind']=='character-reference-override' + assert override=={slot:{'serverFile':'replacement.png'}} + +@pytest.mark.parametrize('feature',sorted(set(server.CHARACTER_REFERENCE_SLOTS) & set(server.FEATURE_BY_ID))) +def test_original_is_executed_conditioning(feature): + character={'id':'fixture','visualClass':'anime'} + f=server.character_feature_definition(server.FEATURE_BY_ID[feature],character) + settings={x['id']:x['default'] for x in f.get('fields',[]) if 'default' in x} + settings.update(seed=20261111,instruction='同一角色的自然半身肖像。',positive='portrait, natural expression, soft studio lighting', + _characterId='fixture',_characterVisualClass='anime',description='角色自然站立,輕微呼吸與眨眼。') + if feature.startswith('h3-'): + settings={'seed':'20261111','_characterId':'fixture','_characterVisualClass':'anime','description':'角色自然站立,輕微呼吸與眨眼。','aspect':'portrait','quality':'quality','motionProfile':'gentle'} + uploads={server.CHARACTER_REFERENCE_SLOTS[feature]:'canonical.png'} + if feature=='image-blend':uploads['image2']='other.png' + if feature in ('dance','video-replace'): + uploads['video']='motion.mp4';settings['length']=81 + if feature=='lipsync':uploads.update(video='video.mp4',voice='voice.wav') + graph=server.BUILDERS[f['builder']](settings,uploads) + loads=[key for key,node in graph.items() if node.get('class_type')=='LoadImage' and node['inputs'].get('image')=='canonical.png'] + assert loads,feature + # Walk backwards from executed output nodes. A decorative disconnected LoadImage fails. + executed=set() + def visit(key): + if key in executed:return + executed.add(key) + for value in graph[key].get('inputs',{}).values(): + if isinstance(value,list) and len(value)==2 and isinstance(value[0],str) and value[0] in graph:visit(value[0]) + for key,node in graph.items(): + if node['class_type'] in {'SaveImage','VHS_VideoCombine','SaveVideo','SaveAudio','SaveAudioMP3'}:visit(key) + assert set(loads)&executed,(feature,[n['class_type'] for n in graph.values()]) + +@pytest.mark.parametrize('feature', sorted(server.FEATURE_BY_ID)) +def test_public_feature_unchanged(feature): + f=server.FEATURE_BY_ID[feature];before=copy.deepcopy(f) + assert server.character_feature_definition(f,None) is f + assert f==before + + + +def test_missing_original_fails_closed(character): + with patch.object(server,'character_asset_path',return_value=None): + with pytest.raises(ValueError,match='原圖'): + server.bind_character_original(character,'text2img',{}) + + +def test_sdxl_original_preserves_lora_and_trigger(): + graph={'base':{'class_type':'CheckpointLoaderSimple','inputs':{'ckpt_name':'sd_xl_base_1.0.safetensors'}}, + 'lora':{'class_type':'LoraLoaderModelOnly','inputs':{'model':['base',0],'lora_name':'existing.safetensors','strength_model':1}}, + 'text':{'class_type':'CLIPTextEncode','inputs':{'text':'existing_trigger, portrait','clip':['base',1]}}, + 'sample':{'class_type':'KSampler','inputs':{'model':['lora',0],'positive':['text',0]}}} + bound=server.attach_sdxl_original(graph,'canonical.png') + assert bound['lora']==graph['lora'] and bound['text']==graph['text'] + condition=bound[bound['sample']['inputs']['model'][0]] + assert condition['inputs']['model']==['lora',0] + assert bound[condition['inputs']['image'][0]]['inputs']['image']=='canonical.png' + assert graph['sample']['inputs']['model']==['lora',0] + + + +def test_public_lipsync_keeps_original_builder(): + public=server.character_feature_definition(server.FEATURE_BY_ID['lipsync'],None) + graph=server.BUILDERS[public['builder']]({}, {'video':'video.mp4','voice':'voice.wav'}) + assert graph['3']['inputs']['images']==['1',0] + assert all(n['class_type']!='ReActorFaceSwap' for n in graph.values()) + + +@pytest.mark.parametrize('feature,builder', [('text2img','zimage'),('qwen21-text2img','qwen21_t2i'),('h3-text-video','minimax_h3_t2v'),('character-angles','qwen21_angles')]) +def test_public_engine_contract(feature,builder): + assert server.character_feature_definition(server.FEATURE_BY_ID[feature],None)['builder']==builder + + +def test_angles_character_only_engine(): + public=server.FEATURE_BY_ID['character-angles'] + role=server.character_feature_definition(public,{'id':'fixture','visualClass':'anime'}) + assert role['builder']=='character_angles' + assert '2511' in role['subtitle'] + assert public['builder']=='qwen21_angles' + assert next(f['default'] for f in public['fields'] if f['id']=='batchSize')==2 + assert next(f['default'] for f in role['fields'] if f['id']=='batchSize')==3 + + + + + + + +def test_clipmode_override_is_sealed_and_worker_rebuilds_same_graph(tmp_path): + from PIL import Image + upload=tmp_path/'override.png';Image.new('RGB',(32,32),'green').save(upload) + settings={'seed':1,'prompt':'portrait','prefix':'test/original','_characterGender':'female'} + verified={'identity_route':server.CLIPMODE_REALISTIC_IDENTITY_ROUTE,'profile_input_name':'canonical.png'} + with patch.object(server,'COMFY_INPUT',tmp_path), patch.object(server,'verify_clipmode_character_photoshoot_files',return_value=verified): + staged=server.bind_clipmode_reference_override(settings,upload.name) + initial=server.clipmode_character_photoshoot_prompt(settings,{'image':staged}) + rebuilt=server.clipmode_character_photoshoot_prompt(settings,{}) + assert initial==rebuilt + assert initial['2']['inputs']['image']==staged + assert settings['_characterReferenceOverride']['sha256']==server.sha256_file(tmp_path/staged) + (tmp_path/staged).write_bytes(b'tampered') + with pytest.raises(ValueError,match='驗證'): + server.clipmode_character_photoshoot_prompt(settings,{}) + + + +def test_provider_default_binds_full_original_and_override_wins(tmp_path): + original=tmp_path/'full-original.png';original.write_bytes(b'full-resolution-original') + c={'id':'clipmode.character:fixture','kind':'provider_character','visualClass':'realistic'} + reference={'input_name':original.name,'sha256':server.sha256_file(original)} + with patch.object(server,'COMFY_INPUT',tmp_path): + files,receipt=server.bind_character_original(c,'text2img',{},reference) + assert files['image']['_characterAssetPath']==str(original) + assert receipt['sha256']==reference['sha256'] + replacement={'image':{'serverFile':'selected.png'}} + assert server.bind_character_original(c,'text2img',replacement,None)[0]==replacement + + +def test_public_angles_requirements_match_qwen_edit(): + edit = next(feature for feature in server.qwen21_feature_definitions() if feature['id'] == 'qwen21-edit') + angles = server.FEATURE_BY_ID['character-angles'] + assert angles['requiredModels'] == edit['requiredModels'] + assert angles['requiredNodes'] == edit['requiredNodes'] + + +def test_provider_character_studio_entry_uses_store_name(): + with patch.dict(sys.modules, {'character_identity': None, 'provider_library': None}): + row = {'character_id': 'clipmode.character:fixture', 'display_name': 'Fixture Name', 'visual_class': 'anime'} + assert server.provider_character_studio_entry(row) == { + 'id': 'clipmode.character:fixture', 'name': 'Fixture Name', 'kind': 'provider_character', + 'visualClass': server.normalized_visual_class('anime'), 'actions': []} + unnamed = {'character_id': 'clipmode.character:fixture', 'display_name': ''} + assert server.provider_character_studio_entry(unnamed)['name'] == 'clipmode.character:fixture' diff --git a/scripts/test_collector_r35_integration.py b/scripts/test_collector_r35_integration.py new file mode 100644 index 0000000..ff0c376 --- /dev/null +++ b/scripts/test_collector_r35_integration.py @@ -0,0 +1,128 @@ +"""Offline r35/collector integration; providers and session lifecycle forbidden.""" +import ast +from concurrent.futures import ThreadPoolExecutor +import json +from pathlib import Path +import threading +from types import SimpleNamespace as NS +from unittest.mock import Mock +import pytest +from test_review_r35 import rig, job, CANDIDATE +from compute_collector import ReceiptCollector +from compute_routing import ComputeAdapter, ComputeRouter, STATES +from compute_parity.colab import ColabNative +from compute_parity.journal import Journal +from compute_parity.runtime import Runtime + + +@pytest.mark.parametrize('session_phase,job_phase,expected',[ + ('requesting','queued','running'),('allocating','queued','submission_uncertain'), + ('uncertain','queued','submission_uncertain'),('uploading','queued','running'), + ('bootstrap','queued','running'),('ready','running','running'), + ('closing','cleanup_pending','cancelling'),('stopping','cleanup_pending','cancelling'), + ('released_unsettled','cleanup_pending','cancelling')]) +def test_collector_projects_session_state_without_driving_lease(rig,monkeypatch,session_phase,job_phase,expected): + s,b,clock,account,session=rig + s.sessions.save(session['id'],phase=session_phase,usage_unknown=session_phase=='released_unsettled') + j=job(rig,session['id'],job_phase) + journal=Journal(s.root.parent/'compute-parity/journal.sqlite3') + journal.reserve('owner',j['id'],'colab',account,'dance.anime.chatgpt','identity',{'unit':'CU','amount':15}) + native=ColabNative(s,journal) + forbidden=Mock(side_effect=AssertionError('Collector must not drive Colab lifecycle')) + for method in ('open','close','release','allocate','tick_all','sweep_leases'): + monkeypatch.setattr(s.sessions,method,forbidden) + monkeypatch.setattr(s,'bridge',forbidden);monkeypatch.setattr(s,'start',forbidden) + def status(owner,rid):return Runtime.receipt(native.poll(owner,rid)) + path=s.root.parent/'compute-routing.sqlite3' + router=ComputeRouter(path,{'colab':ComputeAdapter(forbidden,forbidden,status,forbidden)},clock=s.clock) + with router._db() as db: + db.execute('INSERT INTO compute_requests VALUES (?,?,?,?,?,?,?,?,?,?,?)', + ('owner',j['id'],'hash','colab','colab',expected,'{}','{}', + json.dumps({'state':expected,'downstream_id':j['id']}),clock[0]-86400,clock[0]-86400)) + server=NS(user_for_email=lambda owner:{'email':owner,'role':'member'}) + collector=ReceiptCollector(server,path,clock=s.clock,wall_clock=s.clock) + collector.router=lambda owner:router + assert collector.tick()['refreshed']==1 # Old nonterminal rows remain eligible. + receipt=router.status('owner',j['id']) + assert receipt['state']==expected and receipt['session_id']==session['id'] + assert receipt.get('actual_cost') is None + assert s.sessions.get(session['id'])['phase']==session_phase + if expected=='submission_uncertain':assert receipt['diagnostics']['stage']=='provisioning' + forbidden.assert_not_called() + + +def test_completed_retained_session_job_is_not_collector_work(rig,monkeypatch): + s,b,clock,account,session=rig + s.sessions.save(session['id'],phase='ready') + j=job(rig,session['id'],'completed',released=True,session_runtime_retained=True,units_observed=2) + path=s.root.parent/'compute-routing.sqlite3';router=ComputeRouter(path,{},clock=s.clock) + with router._db() as db: + db.execute('INSERT INTO compute_requests VALUES (?,?,?,?,?,?,?,?,?,?,?)', + ('owner',j['id'],'hash','colab','colab','completed','{}','{}',json.dumps({ + 'state':'completed','session_id':session['id'],'session_runtime_retained':True, + 'actual_cost':{'unit':'CU','amount':2}}),clock[0],clock[0])) + collector=ReceiptCollector(NS(),path,clock=s.clock,wall_clock=s.clock) + collector.router=Mock(side_effect=AssertionError('Already settled')) + assert collector.tick()['scanned']==0 + collector.router.assert_not_called() + assert s.sessions.get(session['id'])['phase']=='ready' + + +def method_scope(collector): + source=CANDIDATE/'webui/server.py';tree=ast.parse(source.read_text()) + handler=next(n for n in tree.body if isinstance(n,ast.ClassDef) and n.name=='Handler') + method=next(n for n in handler.body if isinstance(n,ast.FunctionDef) and n.name=='api_compute') + scope={'_RECEIPT_COLLECTOR':collector} + exec(compile(ast.Module(body=[method],type_ignores=[]),str(source),'exec'),scope) + return scope['api_compute'] + + +@pytest.mark.parametrize('enabled,alive,exists',[(True,True,True),(True,False,True),(True,False,False),(False,False,False)]) +def test_admin_health_is_read_only_and_reports_real_thread(monkeypatch,enabled,alive,exists): + monkeypatch.setenv('CASTLE_COMPUTE_RECEIPT_COLLECTOR','1' if enabled else '0') + collector=NS(_thread=NS(is_alive=lambda:alive)) if exists else None + method=method_scope(collector);sent=[] + handler=NS(current_user=lambda:{'role':'admin'},send_json=lambda value,**kw:sent.append(value)) + forbidden=Mock(side_effect=AssertionError('Health must not assemble adapters')) + monkeypatch.setattr('compute_web.ComputeWeb',forbidden) + method(handler,'/api/compute/collector-health',False) + assert sent==[{'ok':True,'enabled':enabled,'thread_alive':alive}] + forbidden.assert_not_called() + + +@pytest.mark.parametrize('user',[None,{'role':'member'},{'role':'operator'}]) +def test_health_denies_non_admin(user): + sent=[];handler=NS(current_user=lambda:user,send_json=lambda value,code:sent.append((value,code))) + method_scope(None)(handler,'/api/compute/collector-health',False) + assert sent==[({'ok':False},403)] + + + + + + +def test_new_r35_uncertain_refresh_uses_same_lock_as_collector(rig,monkeypatch): + s,b,clock,account,session=rig + j=job(rig,session['id']);s.sessions.save(session['id'],phase='uncertain') + journal=Journal(s.root.parent/'compute-parity/journal.sqlite3') + journal.reserve('owner',j['id'],'colab',account,'dance.anime.chatgpt','identity',{'unit':'CU','amount':15}) + native=ColabNative(s,journal);entered=threading.Event();release=threading.Event();calls=[] + def poll(owner,rid): + calls.append(True);entered.set();assert release.wait(5) + return Runtime.receipt(native.poll(owner,rid)) + path=s.root.parent/'compute-routing.sqlite3' + router=ComputeRouter(path,{'colab':ComputeAdapter(Mock(),Mock(),poll,Mock())},clock=s.clock) + with router._db() as db: + db.execute('INSERT INTO compute_requests VALUES (?,?,?,?,?,?,?,?,?,?,?)', + ('owner',j['id'],'hash','colab','colab','queued','{}','{}',json.dumps({'state':'queued','downstream_id':j['id']}),clock[0],clock[0])) + collector=ReceiptCollector(NS(user_for_email=lambda owner:{'email':owner,'role':'member'}),path,clock=s.clock,wall_clock=s.clock) + collector.router=lambda owner:router + with ThreadPoolExecutor(max_workers=1) as pool: + task=pool.submit(collector.tick) + try: + assert entered.wait(5) + assert router.status('owner',j['id'],refresh=True)['state']=='queued' + assert len(calls)==1 + finally:release.set() + assert task.result(timeout=5)['refreshed']==1 + assert router.status('owner',j['id'])['state']=='submission_uncertain' diff --git a/scripts/test_compute_collector.py b/scripts/test_compute_collector.py new file mode 100644 index 0000000..a770bed --- /dev/null +++ b/scripts/test_compute_collector.py @@ -0,0 +1,492 @@ +"""Offline receipt collection: disk fixtures and mocked adapters only.""" +import ast +from concurrent.futures import ThreadPoolExecutor +import json +import logging +from pathlib import Path +import sys +import threading +from types import SimpleNamespace as NS +from unittest.mock import Mock +import uuid + +import pytest + +from compute_collector import ENV, ReceiptCollector, HOSTED, SETTLEMENT_WINDOW, SETTLEMENT_INTERVAL, SETTLEMENT_LIMIT +from compute_execution import ExecutionContext +from compute_refresh import request_lock +from compute_routing import ComputeAdapter, ComputeRouter, TERMINAL + +OWNER = 'owner@example.test' + + +@pytest.fixture +def rig(tmp_path, monkeypatch): + monkeypatch.delenv(ENV, raising=False) + now = [1000.0] + wall = [100000.0] + user = {'email': OWNER, 'role': 'member'} + server = NS(user_for_email=lambda email: dict(user) if email == OWNER else None) + path = tmp_path / 'compute-routing.sqlite3' + forbidden = Mock(side_effect=AssertionError('forbidden operation')) + status = Mock(return_value={'state': 'queued', 'downstream_id': 'task'}) + adapters = {lane: ComputeAdapter(forbidden, forbidden, status, forbidden, recover=Mock(return_value=None)) + for lane in ('local', 'colab', 'autoip', 'comfy_cloud', 'runninghub')} + router = ComputeRouter(path, adapters, clock=lambda: wall[0]) + collector = ReceiptCollector(server, path, clock=lambda: now[0], wall_clock=lambda: wall[0]) + collector.router = lambda owner: ComputeRouter(path, adapters, clock=lambda: wall[0]) + monkeypatch.setattr(ComputeRouter, 'submit', forbidden) + monkeypatch.setattr(ComputeRouter, 'cancel', forbidden) + monkeypatch.setattr('compute_web.ComputeWeb.close_local_unknown', forbidden) + + def seed(lane='local', state='queued', owner=OWNER, cost=None, downstream=True, updated=None): + rid = str(uuid.uuid4()) + receipt = {'state': state} + if downstream: + receipt['downstream_id'] = 'task' + if cost is not None: + receipt['actual_cost'] = {'unit': 'POINT', 'amount': cost} + with router._db() as db: + db.execute('INSERT INTO compute_requests VALUES (?,?,?,?,?,?,?,?,?,?,?)', + (owner, rid, 'hash', lane, lane, state, '{}', '{}', json.dumps(receipt), wall[0] - 86400, wall[0] if updated is None else updated)) + return rid + yield NS(now=now, wall=wall, server=server, user=user, path=path, forbidden=forbidden, + status=status, adapters=adapters, router=router, collector=collector, seed=seed) + forbidden.assert_not_called() + + +def test_local_history_collected_without_get(rig, monkeypatch): + from compute_web import ComputeWeb + rid = rig.seed() + history = {'task': {'status': {'completed': True}, 'outputs': {'1': {'images': [ + {'filename': 'output.png', 'type': 'output'}]}}}} + rig.server.get_colab_service = lambda: NS(root=rig.path.parent / 'colab') + rig.server.get_hosted_compute_service = lambda: NS() + rig.server.compute_parity_runtime = NS(owns=lambda *args: False) + rig.server.Handler = NS(_provider_console=lambda context: NS()) + rig.server.local_job_snapshot = lambda: [] + rig.server.load_job_index = lambda: {'task': {'email': OWNER}} + rig.server.request_json = Mock(return_value=history) + rig.server.user_can_access_job = lambda user, *args: user == rig.user + rig.server.user_can_access_view_item = lambda user, *args: user == rig.user + monkeypatch.setattr(ComputeWeb, '_durable_local_result', lambda *args: None) + persist = Mock(return_value=True) + monkeypatch.setattr(ComputeWeb, '_persist_local_history', persist) + del rig.collector.router # Exercise real ExecutionContext -> ComputeWeb -> adapter chain. + assert rig.collector.tick()['refreshed'] == 1 + result = rig.router.status(OWNER, rid) # Durable read only, no GET/refresh. + assert result['state'] == 'completed' and result['artifacts'] + rig.server.request_json.assert_called_once_with('/history/task') + persist.assert_called_once_with('task', history['task'], {'email': OWNER}) + + +@pytest.mark.parametrize('lane', ['colab', 'autoip', 'comfy_cloud', 'runninghub']) +def test_hosted_completed_unsettled_until_cost_observed(rig, lane): + rid = rig.seed(lane, 'completed') + rig.status.side_effect = [ + {'state': 'completed', 'downstream_id': 'task'}, + {'state': 'completed', 'downstream_id': 'task', 'actual_cost': {'unit': 'POINT', 'amount': 0}, 'settlement_status': 'settled'}] + assert rig.collector.tick()['refreshed'] == 1 + for second in (15, 30, 45, 60, 120, 299): + rig.now[0] = 1000 + second + assert rig.collector.tick()['deferred'] == 1 + rig.now[0] = 1300 + assert rig.collector.tick()['refreshed'] == 1 + assert rig.router.status(OWNER, rid)['actual_cost']['amount'] == 0 + rig.now[0] = 1600 + assert rig.collector.tick()['scanned'] == 0 + assert rig.status.call_count == 2 + + +@pytest.mark.parametrize('lane,base', [('local', 15), ('colab', 60), ('autoip', 60), ('comfy_cloud', 60), ('runninghub', 60)]) +def test_cadence_exponential_backoff_cap_and_reset(rig, lane, base): + rig.seed(lane) + rig.status.side_effect = RuntimeError('private exception') + for failure in range(1, 10): + assert rig.collector.tick()['errors'] == 1 + delay = min(600, base * 2 ** failure) + rig.now[0] += delay - 1 + assert rig.collector.tick()['deferred'] == 1 + rig.now[0] += 1 + rig.status.side_effect = None + assert rig.collector.tick()['errors'] == 0 + rig.now[0] += base - 1 + assert rig.collector.tick()['deferred'] == 1 + rig.now[0] += 1 + assert rig.collector.tick()['refreshed'] == 1 + + +def test_get_and_collector_never_overlap(rig, monkeypatch): + # Execute the real GET branch without importing/starting the live server. + import compute_web + import compute_parity.http + source = Path(__file__).resolve().parents[1] / 'webui/server.py' + tree = ast.parse(source.read_text()) + handler = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Handler') + method = next(n for n in handler.body if isinstance(n, ast.FunctionDef) and n.name == 'api_compute') + namespace = {'sys': sys, '__name__': __name__, 'FEATURE_BY_ID': {}} + exec(compile(ast.Module(body=[method], type_ignores=[]), str(source), 'exec'), namespace) + rid = rig.seed('runninghub') + monkeypatch.setattr(compute_web, 'ComputeWeb', lambda *args: NS(router=rig.router, owner=OWNER, user=rig.user)) + monkeypatch.setattr(compute_parity.http, 'handle', lambda *args: False) + received = [] + h = NS(send_json=lambda value, *args: received.append(value)) + entered, release = threading.Event(), threading.Event() + def slow(*args): + entered.set() + assert release.wait(5) + return {'state': 'completed', 'downstream_id': 'task', 'actual_cost': {'unit': 'POINT', 'amount': 1}} + rig.status.side_effect = slow + with ThreadPoolExecutor(max_workers=1) as pool: + task = pool.submit(rig.collector.tick) + try: + assert entered.wait(5) + namespace['api_compute'](h, '/api/compute/jobs/' + rid, False) + assert received[-1]['state'] == 'queued' # bounded wait, durable fallback + assert rig.status.call_count == 1 + finally: + release.set() + assert task.result(timeout=5)['refreshed'] == 1 + assert rig.router.status(OWNER, rid)['state'] == 'completed' + + +def test_collector_skips_busy_get(rig): + rid = rig.seed() + entered, release = threading.Event(), threading.Event() + def slow(*args): + entered.set() + assert release.wait(5) + return {'state': 'queued', 'downstream_id': 'task'} + rig.status.side_effect = slow + with ThreadPoolExecutor(max_workers=1) as pool: + get = pool.submit(rig.router.status, OWNER, rid, refresh=True) + try: + assert entered.wait(5) + assert rig.collector.tick()['busy'] == 1 + assert rig.status.call_count == 1 + finally: + release.set() + get.result(timeout=5) + assert rig.collector.tick()['refreshed'] == 1 + + +@pytest.mark.parametrize('damage', ['missing', 'disabled', 'mustSetPassword', 'mismatch']) +def test_unresolvable_owner_skips_before_adapters(rig, damage): + rig.seed() + if damage == 'missing': + rig.server.user_for_email = lambda email: None + elif damage == 'mismatch': + rig.user['email'] = 'another@example.test' + else: + rig.user[damage] = True + rig.collector.router = Mock(side_effect=AssertionError('must skip')) + assert rig.collector.tick()['unknown_owner'] == 1 + rig.collector.router.assert_not_called() + rig.status.assert_not_called() + + +@pytest.mark.parametrize('role', ['admin', 'operator', 'member']) +def test_existing_owner_context_preserves_current_roles(rig, monkeypatch, role): + import compute_web + rig.user['role'] = role + rig.server.Handler = NS(_provider_console=lambda ctx: ctx.current_user()['role']) + seen = [] + def web(context, server): + seen.append((context.current_user(), context._provider_console(), server)) + return NS(router=rig.router) + monkeypatch.setattr(compute_web, 'ComputeWeb', web) + del rig.collector.router + assert rig.collector.router(OWNER) is rig.router + assert seen == [(rig.user, role, rig.server)] + rig.user['role'] = 'member' + assert ExecutionContext(rig.server, OWNER).current_user()['role'] == 'member' + + +def test_legacy_identity_uses_existing_credential_resolution(rig): + rig.server.user_for_email = lambda email: None + rig.server.LOCAL_SESSION_USER = dict(rig.user) + rig.server.local_credential_version = lambda: 'synthetic-version' + assert ExecutionContext(rig.server, OWNER).current_user() == rig.user + rig.server.local_credential_version = lambda: None + with pytest.raises(PermissionError): + ExecutionContext(rig.server, OWNER) + + +@pytest.mark.parametrize('lane', ['local', 'colab', 'autoip', 'comfy_cloud', 'runninghub']) +def test_terminal_settled_and_closed_untouched(rig, lane): + for state in TERMINAL: + rig.seed(lane, state, cost=0) + if lane == 'local': + rig.seed(lane, 'completed') + with rig.router._db() as db: + before = [tuple(row) for row in db.execute('SELECT * FROM compute_requests')] + assert rig.collector.tick()['scanned'] == 0 + with rig.router._db() as db: + assert before == [tuple(row) for row in db.execute('SELECT * FROM compute_requests')] + rig.status.assert_not_called() + + +def test_uncertain_only_recovers_original_identity(rig): + rid = rig.seed(state='submission_uncertain', downstream=False) + adapter = rig.adapters['local'] + adapter.recover.return_value = None + assert rig.collector.tick()['refreshed'] == 1 + adapter.recover.assert_called_once_with(OWNER, rid) + assert rig.router.status(OWNER, rid)['state'] == 'submission_uncertain' + rig.status.assert_not_called() + adapter.recover.side_effect = RuntimeError('private') + rig.now[0] += 15 + assert rig.collector.tick()['errors'] == 1 + rig.now[0] += 15 + assert rig.collector.tick()['deferred'] == 1 + + +def test_bounded_rotation_no_starvation(rig): + for _ in range(45): + rig.seed('runninghub') + assert rig.collector.tick()['refreshed'] == 20 + assert rig.collector.tick()['refreshed'] == 20 + assert rig.collector.tick()['refreshed'] == 5 + assert rig.collector.tick()['deferred'] == 20 + assert rig.status.call_count == 45 + + +def test_exception_in_one_owner_context_does_not_stop_batch(rig): + for _ in range(3): + rig.seed() + original = rig.collector.router + rig.collector.router = Mock(side_effect=[RuntimeError('private'), original(OWNER), original(OWNER)]) + counts = rig.collector.tick() + assert counts['errors'] == 1 and counts['refreshed'] == 2 + + +def test_loop_survives_scan_error_and_logs_only_counts(rig, caplog): + caplog.set_level(logging.INFO) + original = rig.collector.tick + rig.seed() + rig.collector.tick = Mock(side_effect=[RuntimeError('private@example.test https://secret.test/?key=secret'), original()]) + waits = [] + def wait(seconds): + waits.append(seconds) + if len(waits) == 2: + rig.collector._stop.set() + rig.collector._stop.wait = wait + rig.collector._loop() + assert waits == [15, 15] + assert rig.collector.tick.call_count == 2 + assert 'tick_errors=1' in caplog.text and 'refreshed=1' in caplog.text + assert not any(value in caplog.text for value in ('private', 'https:', 'secret', OWNER)) + + +@pytest.mark.parametrize('value', ['0', 'false', 'OFF', 'no']) +def test_kill_switch_blocks_start_and_ticks(rig, monkeypatch, value): + rig.seed() + monkeypatch.setenv(ENV, value) + rig.collector.start() + assert rig.collector._thread is None + assert rig.collector.tick()['scanned'] == 0 + rig.status.assert_not_called() + + +def test_start_is_default_on_daemon_and_idempotent(rig, monkeypatch): + threads = [] + class FakeThread: + def __init__(self, **kwargs): + self.kwargs, self.started = kwargs, False + threads.append(self) + def start(self): self.started = True + def is_alive(self): return self.started + monkeypatch.setattr('compute_collector.threading.Thread', FakeThread) + rig.collector.start() + rig.collector.start() + assert len(threads) == 1 + assert threads[0].kwargs['daemon'] and threads[0].kwargs['name'] == 'compute-receipts' + assert threads[0].kwargs['target'] == rig.collector._loop + + +def test_no_database_until_first_request(rig, tmp_path): + path = tmp_path / 'not-created' / 'routing.sqlite3' + collector = ReceiptCollector(rig.server, path) + assert collector.tick()['scanned'] == 0 and not path.exists() + + +def test_request_locks_are_owner_and_database_scoped(rig, tmp_path): + a = request_lock(rig.path, OWNER, 'id') + assert a is request_lock(rig.path, OWNER, 'id') + assert a is not request_lock(rig.path, 'different', 'id') + assert a is not request_lock(tmp_path / 'other.db', OWNER, 'id') + + +def test_server_startup_starts_collector_even_without_routing_database(rig, monkeypatch): + import argparse + import os + import compute_collector + import comfy_checkpoint_context + source = Path(__file__).resolve().parents[1] / 'webui/server.py' + main = next(n for n in ast.parse(source.read_text()).body if isinstance(n, ast.FunctionDef) and n.name == 'main') + monkeypatch.setattr(sys, 'argv', ['server.py']) + monkeypatch.setenv('CASTLE_COLAB_ROOT', str(rig.path.parent / 'fresh' / 'colab')) + monkeypatch.setattr(comfy_checkpoint_context, 'write_checkpoint_context', Mock()) + factory = Mock(return_value=NS(start=Mock())) + monkeypatch.setattr(compute_collector, 'ReceiptCollector', factory) + http = NS(serve_forever=Mock()) + namespace = dict(argparse=argparse, os=os, sys=sys, Path=Path, __name__=__name__, + _CASTLE_DATA_HOME=rig.path.parent, DEFAULT_COMFY='unused', + CastleThreadingHTTPServer=Mock(return_value=http), Handler=object, + library_service=NS(start_indexer=Mock()), library_server_context=lambda: NS(), + castle_orchestrator=NS(initialize=Mock(), start_worker_once=Mock())) + exec(compile(ast.Module(body=[main], type_ignores=[]), str(source), 'exec'), namespace) + namespace['main']() + factory.assert_called_once_with(sys.modules[__name__], rig.path.parent / 'fresh' / 'compute-routing.sqlite3') + factory.return_value.start.assert_called_once_with() + assert namespace['_RECEIPT_COLLECTOR'] is factory.return_value + assert not (rig.path.parent / 'fresh').exists() + + +def test_terminal_transition_after_scan_is_not_refreshed(rig): + rid = rig.seed('runninghub') + rows = rig.collector._rows() + rig.router._save(OWNER, rid, {'state': 'completed', 'downstream_id': 'task', + 'actual_cost': {'unit': 'POINT', 'amount': 0}}) + rig.collector._rows = lambda: rows + rig.collector.tick() + rig.status.assert_not_called() + + +@pytest.mark.parametrize('role,operator,expected', [('admin', False, 'admin'), ('user', True, 'operator'), ('user', False, 'member')]) +def test_context_delegates_to_authenticated_actor_resolution(rig, role, operator, expected): + source = Path(__file__).resolve().parents[1] / 'webui/server.py' + handler = next(n for n in ast.parse(source.read_text()).body if isinstance(n, ast.ClassDef) and n.name == 'Handler') + method = next(n for n in handler.body if isinstance(n, ast.FunctionDef) and n.name == '_provider_runtime_actor') + namespace = dict(normalize_email=lambda email: email.lower(), is_operator_user=lambda user: operator, + _PROVIDER_CANONICAL_CONTEXT=threading.local()) + exec(compile(ast.Module(body=[method], type_ignores=[]), str(source), 'exec'), namespace) + rig.user['role'] = role + runtime = NS(actor_context=Mock(return_value=NS())) + rig.server.Handler = NS(_provider_runtime_actor=namespace['_provider_runtime_actor'], + _provider_runtime=lambda context: runtime) + ExecutionContext(rig.server, OWNER)._provider_runtime_actor() + runtime.actor_context.assert_called_once_with(OWNER, expected) + + +@pytest.mark.parametrize('lane', sorted(HOSTED)) +@pytest.mark.parametrize('age,expected', [(0, 1), (21599.999, 1), (21600, 0), (21600.001, 0), (86400 * 7, 0)]) +def test_settlement_sql_uses_updated_strict_six_hour_window(rig, lane, age, expected): + rig.seed(lane, 'completed', updated=rig.wall[0] - age) + rig.status.return_value = {'state': 'completed', 'downstream_id': 'task'} + counts = rig.collector.tick() + assert counts['scanned'] == counts['refreshed'] == expected + assert rig.status.call_count == expected + + +@pytest.mark.parametrize('lane', ['local', *sorted(HOSTED)]) +def test_old_nonterminal_rows_remain_eligible(rig, lane): + rig.seed(lane, 'queued', updated=rig.wall[0] - 86400 * 7) + assert rig.collector.tick()['refreshed'] == 1 + + +@pytest.mark.parametrize('lane', sorted(HOSTED)) +@pytest.mark.parametrize('error', [False, True]) +def test_twelve_settlement_attempts_per_process_including_failures(rig, lane, error): + rid = rig.seed(lane, 'completed') + if error: + rig.status.side_effect = RuntimeError('private provider error') + else: + rig.status.return_value = {'state': 'completed', 'downstream_id': 'task'} + delay = 600 if error else 300 + for _ in range(12): + assert rig.collector.tick()['refreshed'] == 1 + rig.now[0] += delay - 1 + assert rig.collector.tick()['refreshed'] == 0 + rig.now[0] += 1 + assert rig.status.call_count == 12 + assert rig.collector._settlement_attempts[(OWNER, rid)] == 12 + # Old scheduling entries expire; the lifetime budget must not expire. + rig.now[0] += 10000 + assert rig.collector.tick()['refreshed'] == 0 + assert rig.status.call_count == 12 + # Owner demand still uses the unchanged router GET path, without a cap. + rig.status.side_effect = None + rig.status.return_value = {'state': 'completed', 'downstream_id': 'task'} + rig.wall[0] += 3600 + assert rig.router.status(OWNER, rid, refresh=True)['updated_at'] == rig.wall[0] + assert rig.status.call_count == 13 + assert rig.collector.tick()['refreshed'] == 0 # updated was refreshed by GET + assert rig.status.call_count == 13 + # Another request has its own independent budget. + rig.seed(lane, 'completed') + assert rig.collector.tick()['refreshed'] == 1 + assert rig.status.call_count == 14 + + +@pytest.mark.parametrize('lane', sorted(HOSTED)) +def test_get_refreshes_expired_settlement_on_demand(rig, lane): + rid = rig.seed(lane, 'completed', updated=rig.wall[0] - 86400) + rig.status.return_value = {'state': 'completed', 'downstream_id': 'task', + 'actual_cost': {'unit': 'POINT', 'amount': 2}} + assert rig.collector.tick()['scanned'] == 0 + assert rig.router.status(OWNER, rid, refresh=True)['actual_cost']['amount'] == 2 + assert rig.status.call_count == 1 + + +def test_expiry_between_scan_and_refresh_rechecked_under_lock(rig): + rig.seed('autoip', 'completed', updated=rig.wall[0] - SETTLEMENT_WINDOW + 1) + rows = rig.collector._rows() + rig.collector._rows = lambda: rows + rig.wall[0] += 1 + assert rig.collector.tick()['refreshed'] == 0 + assert not rig.collector._settlement_attempts + rig.status.assert_not_called() + + +def test_nonterminal_completion_enters_five_minute_cadence(rig): + rid = rig.seed('autoip') + rig.status.return_value = {'state': 'completed', 'downstream_id': 'task'} + assert rig.collector.tick()['refreshed'] == 1 + assert not rig.collector._settlement_attempts + rig.now[0] += 299 + assert rig.collector.tick()['refreshed'] == 0 + rig.now[0] += 1 + assert rig.collector.tick()['refreshed'] == 1 + assert rig.collector._settlement_attempts[(OWNER, rid)] == 1 + + +def test_completion_by_get_after_scan_cannot_bypass_settlement_cap(rig): + rid = rig.seed('autoip') + rows = rig.collector._rows() + rig.collector._rows = lambda: rows + rig.collector._settlement_attempts[(OWNER, rid)] = SETTLEMENT_LIMIT + rig.router._save(OWNER, rid, {'state': 'completed', 'downstream_id': 'task'}) + assert rig.collector.tick()['refreshed'] == 0 + rig.status.assert_not_called() + + +def test_unresolved_or_busy_settlement_does_not_consume_attempt(rig): + rid = rig.seed('autoip', 'completed') + rig.server.user_for_email = lambda owner: None + assert rig.collector.tick()['unknown_owner'] == 1 + assert not rig.collector._settlement_attempts + rig.server.user_for_email = lambda owner: dict(rig.user) + rig.now[0] += 600 + entered, release = threading.Event(), threading.Event() + def hold(): + with request_lock(rig.path, OWNER, rid): + entered.set() + assert release.wait(5) + with ThreadPoolExecutor(max_workers=1) as pool: + task = pool.submit(hold) + try: + assert entered.wait(5) + assert rig.collector.tick()['busy'] == 1 + assert not rig.collector._settlement_attempts + finally: + release.set() + task.result(timeout=5) + + +def test_settlement_budget_does_not_throttle_nonterminal_request(rig): + rid = rig.seed('runninghub', 'running') + rig.collector._settlement_attempts[(OWNER, rid)] = SETTLEMENT_LIMIT + assert rig.collector.tick()['refreshed'] == 1 + rig.now[0] += 60 + assert rig.collector.tick()['refreshed'] == 1 diff --git a/scripts/test_compute_parity_hosted_h1.py b/scripts/test_compute_parity_hosted_h1.py new file mode 100644 index 0000000..a68d243 --- /dev/null +++ b/scripts/test_compute_parity_hosted_h1.py @@ -0,0 +1,59 @@ +"""Regression: RunningHub's real catalog exceeds the old 16 MiB ceiling.""" +import io +import json +from pathlib import Path +import socket +import sys +import pytest + +ROOT=Path(__file__).resolve().parents[1] +sys.path[:0]=[str(ROOT),str(ROOT/'webui')] +from compute_parity.transport import Transport +from compute_parity.contracts import ParityError + +@pytest.fixture(autouse=True) +def offline(monkeypatch): + def deny(*args,**kwargs):raise AssertionError('network forbidden') + monkeypatch.setattr(socket.socket,'connect',deny) + +class FakeOpener: + def __init__(self,raw):self.raw=raw;self.calls=0 + def open(self,request,timeout): + self.calls+=1 + return io.BytesIO(self.raw) + +def transport(lane,raw): + t=Transport(lane,'fake-owner-key',enabled=True) + t._opener=FakeOpener(raw) + return t + +def test_large_native_catalog_parses_without_retry(): + raw=json.dumps({'Loader':{'input':{'required':{'model':[['x.safetensors']]}}},'padding':'x'*(17*1024*1024)}).encode() + t=transport('runninghub',raw) + assert t.request('GET','/object_info')['Loader']['input']['required']['model']==[['x.safetensors']] + assert t._opener.calls==1 + +@pytest.mark.parametrize('lane,method,path,billing',[ + ('runninghub','GET','/history',False), + ('runninghub','POST','/object_info',False), + ('runninghub','GET','/object_info',True), + ('comfy_cloud','GET','/api/object_info',False), +]) +def test_other_json_endpoints_keep_original_ceiling(lane,method,path,billing): + t=transport(lane,b' '*(16*1024*1024)+b'{}') + with pytest.raises(ParityError) as error:t.request(method,path,billing=billing) + assert error.value.code=='provider_io' + assert 'fake-owner-key' not in str(error.value) + assert t._opener.calls==1 + +def test_native_catalog_still_bounded(): + t=transport('runninghub',b' '*(64*1024*1024)+b'{}') + with pytest.raises(ParityError) as error:t.request('GET','/object_info') + assert error.value.code=='provider_io' + assert t._opener.calls==1 + +def test_malformed_catalog_keeps_safe_failure(): + t=transport('runninghub',b'fake-owner-key') + with pytest.raises(ParityError) as error:t.request('GET','/object_info') + assert error.value.code=='provider_io' + assert 'fake-owner-key' not in str(error.value) diff --git a/scripts/test_compute_parity_p1.py b/scripts/test_compute_parity_p1.py new file mode 100644 index 0000000..1c752d8 --- /dev/null +++ b/scripts/test_compute_parity_p1.py @@ -0,0 +1,549 @@ +"""P1 offline contracts and real adapter lifecycle tests; no provider credentials.""" +import copy +import hashlib +import json +import logging +from pathlib import Path +import socket +import sys +import uuid +from types import SimpleNamespace +import pytest +ROOT=Path(__file__).resolve().parents[1] +sys.path[:0]=[str(ROOT),str(ROOT/'webui')] +from compute_parity.contracts import * +from compute_parity.adapters import RunningHubNative,AutoIPPublic,CloudManifestProbe,call +from compute_parity.colab import ColabNative,submit_native +from compute_parity.journal import Journal +from compute_parity.transport import Transport +from scripts.colab_remote.native_schema import validate_native_manifest +from scripts.colab_remote.native_runner import install_model + +@pytest.fixture(autouse=True) +def no_network(monkeypatch): + def deny(*a,**kw):raise AssertionError('Offline test attempted network') + monkeypatch.setattr(socket.socket,'connect',deny) + monkeypatch.setattr(socket,'create_connection',deny) + +@pytest.fixture +def bundle(): + graph={'1':{'class_type':'LoadImage','inputs':{'image':'old.png'}}, + '2':{'class_type':'VHS_LoadVideoPath','inputs':{'video':'/old/private.mp4','force_rate':16,'frame_load_cap':205}}, + '3':{'class_type':'UNETLoader','inputs':{'unet_name':'scail.safetensors','weight_dtype':'default'}}, + '4':{'class_type':'Output','inputs':{'images':['1',0],'video':['2',0],'model':['3',0],'filename_prefix':'old'}}} + b={'schema_version':1,'case_id':'dance.anime','feature':'dance','graph':graph,'graph_sha256':digest(graph), + 'private_persona':False,'material_settings':{'positive':'Full body dance'},'models':[ + {'name':'scail.safetensors','target':'models/diffusion_models/scail.safetensors','sha256':'b'*64,'bytes':12,'private':False}], + 'inputs':[],'core':{'commit':'a'*40},'node_packs':{},'output_contract':{'kind':'video'}} + for node,slot,kind,ext in [('1','reference','image','.png'),('2','video','video','.mp4')]: + data=slot.encode();b['inputs'].append({'node_id':node,'slot':slot,'kind':kind,'field':'image' if slot=='reference' else 'video','name':'input/'+node+ext,'bytes':len(data),'sha256':hashlib.sha256(data).hexdigest()}) + return seal(b) + +def seal(b): + b['graph_sha256']=digest(b['graph']);b.pop('bundle_sha256',None);b['bundle_sha256']=digest(b);return b + +def synthetic_material_bundle(tmp_path): + # Lifecycle tests exercise byte signatures and media probing using generated inputs. + import io + import subprocess + import tempfile + from PIL import Image + if not hasattr(synthetic_material_bundle, '_media'): + image = io.BytesIO() + Image.new('RGB', (32, 32), 'black').save(image, format='PNG') + with tempfile.TemporaryDirectory(prefix='synthetic-video-') as directory: + video = Path(directory) / 'input.mp4' + subprocess.run(['ffmpeg', '-loglevel', 'error', '-f', 'lavfi', '-i', + 'color=c=black:s=32x32:r=2', '-t', '1', '-c:v', 'mpeg4', + '-y', str(video)], check=True) + synthetic_material_bundle._media = {'reference': image.getvalue(), 'video': video.read_bytes()} + b = bundle.__wrapped__() + b['case_id'] = 'dance.anime.chatgpt' + for item in b['inputs']: + raw = synthetic_material_bundle._media[item['slot']] + path = tmp_path / ('fixture-' + Path(item['name']).name) + path.write_bytes(raw) + item.update(local_path=str(path), bytes=len(raw), sha256=hashlib.sha256(raw).hexdigest()) + seal(b) + catalog = tmp_path / 'compute-parity' / 'bundles-r29' + catalog.mkdir(parents=True, exist_ok=True) + (catalog / (b['case_id'] + '.json')).write_text(json.dumps(b)) + return b + +def voice(b,private=False): + b=copy.deepcopy(b);b.update(feature='voice-speak',case_id='voice-speak.shared' if private else 'voice-speak.library',private_persona=private) + if private: + b['graph']={'1':{'class_type':'CastleBreezyVoiceTTS','inputs':{'persona':'custom','text':'hello'}}} + b['inputs']=[{'node_id':None,'slot':'audio','kind':'audio','field':None,'name':'input/1.wav','bytes':5,'sha256':hashlib.sha256(b'audio').hexdigest()}] + b['voice_export']={'persona':'custom','reference_name':'input/1.wav','reference_text':'reference','text':'hello','weight_target':None} + + else: + data=b'audio';b['graph']={'1':{'class_type':'LoadAudio','inputs':{'audio':'original.wav'}},'2':{'class_type':'CastleBreezyVoiceClone','inputs':{'ref_audio':['1',0],'ref_text':'reference','text':'hello'}}} + b['inputs']=[{'node_id':'1','slot':'audio','kind':'audio','field':'audio','name':'input/1.wav','bytes':5,'sha256':hashlib.sha256(data).hexdigest()}] + return seal(b) + +def files(b):return {i['slot']:i['slot'].encode() for i in b['inputs']} +def oid():return str(uuid.uuid4()) +def schema(graph): + result={} + for n in graph.values(): + required={k:([v] if k in MODEL_FIELDS else 'STRING',{}) for k,v in n['inputs'].items()} + result[n['class_type']]={'input':{'required':required}} + return result + +class FakeTransport: + account_type="NORMAL" + fingerprint='account-A' + def __init__(self,b): + self.calls=[];self.graph=compile_request(b,'runninghub',request_id=oid(),voice_consent=True)['json']['prompt'];self.info=schema(self.graph) + self.timeout=False;self.rid='remote-1';self.history={};self.queue={'queue_running':[],'queue_pending':[]};self.point=12 + self.pricing={'data':{'character_dance':100,'voice_clone':20}};self.balance={'data':{'balance':1000}};self.status={'status':'queued'} + def request(self,method,path,**kw): + self.calls.append((method,path,kw)) + if path=='/object_info' or path=='/api/object_info':return self.info + if path=='/upload/image':return {'name':kw['files']['image'][0],'subfolder':'owned','type':'input'} + if path=='/prompt': + if self.timeout:raise TimeoutError('SECRET https://www.runninghub.ai/proxy-plus/SECRET/prompt') + self.prompt=kw['body'];return {'prompt_id':self.rid} + if path=='/history':return self.history + if path=='/queue' and method=='GET':return self.queue + if path.startswith('/history/'):return self.history + if path in {'/interrupt','/queue'}:return {} + if path.startswith('/view?'):return b'video-result' + if path=='/openapi/v2/query':return {'usage':{'chargedPoint':self.point,'consumeCoins':9999}} + if path=='/api/v1/pricing':return self.pricing + if path=='/api/v1/credits/balance':return self.balance + if path in {'/api/v1/videos/character-dance','/api/v1/voice/clone'}: + if self.timeout:raise TimeoutError('SECRET') + return {'task_uuid':self.rid} + if path.endswith('/outputs/0'):return b'audio-or-video' + if path.startswith('/api/v1/tasks/'):return self.status + raise AssertionError((method,path)) + def download_runninghub_output(self,artifact):return b'video-result' + def finish(self):self.history={self.rid:{'status':{'completed':True},'outputs':{'25':{'gifs':[{'filename':'movie.mp4','type':'output','subfolder':'parity'}]}}}} + +@pytest.mark.parametrize('lane',['local','colab','runninghub','autoip','comfy_cloud']) +def test_compilers(bundle,lane): + p=compile_request(bundle,lane,request_id=oid()) + assert p['lane']==lane + if lane=='runninghub': + assert p['json']['prompt']['2']['class_type']=='VHS_LoadVideo' + assert p['json']['prompt']['2']['inputs']['frame_load_cap']==205 + assert p['capacity_gb']==48 + if lane=='colab':assert p['gpu']=='A100' and p['cache'].endswith(bundle['bundle_sha256']) + if lane=='autoip':assert p['fields']['mode']=='animation' and 'seed' in p['differences'] + assert bundle['graph']['2']['class_type']=='VHS_LoadVideoPath' + +@pytest.mark.parametrize('lane',['colab','runninghub','autoip','comfy_cloud']) +@pytest.mark.parametrize('consent',[False,True,'true',1]) +def test_private_voice_needs_consent(bundle,lane,consent): + b=voice(bundle,True) + if consent is not True: + with pytest.raises(ParityError,match='明確同意'):compile_request(b,lane,request_id=oid(),voice_consent=consent) + else: + assert compile_request(b,lane,request_id=oid(),voice_consent=True)['lane']==lane + +@pytest.mark.parametrize('lane',['colab','runninghub','autoip']) +@pytest.mark.parametrize('consent',[False,'true',1,None]) +def test_voice_requires_literal_per_run_true(bundle,lane,consent): + with pytest.raises(ParityError,match='明確同意'):compile_request(voice(bundle),lane,request_id=oid(),voice_consent=consent) + +@pytest.mark.parametrize('lane',['colab','runninghub','autoip']) +def test_portable_voice_compiles(bundle,lane): + p=compile_request(voice(bundle),lane,request_id=oid(),voice_consent=True) + if lane=='autoip':assert p['fields']['dialect_rewrite']=='0' and 'reference_voice_id' not in p['fields'] + +def test_unknown_node_and_model(bundle): + p=compile_request(bundle,'runninghub',request_id=oid());info=schema(p['json']['prompt']) + info.pop('LoadImage');info['UNETLoader']['input']['required']['unet_name']=(['different'],{}) + r=dependency_probe(p['json']['prompt'],info) + assert not r['ready'] and r['missing_nodes']==['LoadImage'] and r['missing_models']==['scail.safetensors'] + assert '收藏' in r['reason'] and not r['hashes_verified'] + +def test_rh_lifecycle_and_correct_unit(bundle,tmp_path): + t=FakeTransport(bundle);a=RunningHubNative(t,Journal(tmp_path/'jobs.db'));rid=oid() + assert a.submit('a',rid,bundle,files(bundle),quote={'unit':'POINT','amount':100})['state']=='queued' + assert a.poll('a',rid)['state']=='queued' + t.finish();result=a.poll('a',rid) + assert result['state']=='completed' and result['actual_cost']=={'unit':'POINT','amount':12} + assert a.download('a',rid)==b'video-result' + assert a.submit('a',rid,bundle,files(bundle),quote={'unit':'POINT','amount':100})['state']=='completed' + assert sum(p=='/prompt' for _,p,_ in t.calls)==1 + assert all('workflowId' not in str(kw) for _,_,kw in t.calls) + +def test_rh_unknown_recovery_no_resubmit(bundle,tmp_path): + t=FakeTransport(bundle);t.timeout=True;j=Journal(tmp_path/'jobs.db');a=RunningHubNative(t,j);rid=oid() + assert a.submit('a',rid,bundle,files(bundle),quote={'unit':'POINT','amount':100})['state']=='submission_uncertain' + a=RunningHubNative(t,Journal(tmp_path/'jobs.db')) + assert a.recover('a',rid)['state']=='submission_uncertain' + a.submit('a',rid,bundle,files(bundle),quote={'unit':'POINT','amount':100}) + t.queue['queue_pending']=[[0,t.rid,{}, {'castle_request_id':rid}]] + assert a.recover('a',rid)['remote_id']==t.rid + assert sum(p=='/prompt' for _,p,_ in t.calls)==1 + assert 'SECRET' not in (tmp_path/'jobs.db').read_bytes().decode('utf8','ignore') + +@pytest.mark.parametrize('where',['queue_running','queue_pending']) +def test_rh_cancel_scoped(bundle,tmp_path,where): + t=FakeTransport(bundle);a=RunningHubNative(t,Journal(tmp_path/'j.db'));rid=oid() + a.submit('a',rid,bundle,files(bundle),quote={'unit':'POINT','amount':100}) + t.queue[where]=[[0,t.rid,{},{}]] + assert a.cancel('a',rid)['state']=='cancelling' + assert t.calls[-1][1]==('/interrupt' if where=='queue_running' else '/queue') + +def test_rh_cancel_does_not_interrupt_other_work(bundle,tmp_path): + t=FakeTransport(bundle);a=RunningHubNative(t,Journal(tmp_path/'j.db'));rid=oid() + a.submit('a',rid,bundle,files(bundle),quote={'unit':'POINT','amount':100}) + t.queue['queue_running']=[[0,t.rid],[1,'other']] + with pytest.raises(ParityError):a.cancel('a',rid) + assert not any(p=='/interrupt' for _,p,_ in t.calls) + +@pytest.mark.parametrize('q,cap',[({'unit':'coins','amount':1},2000),({'unit':'POINT','amount':float('nan')},2000)]) +def test_rh_budget_refused_before_io(bundle,tmp_path,q,cap): + t=FakeTransport(bundle);a=RunningHubNative(t,Journal(tmp_path/'j.db')) + with pytest.raises(ParityError):a.submit('a',oid(),bundle,files(bundle),quote=q,cap=cap) + assert not t.calls + +def test_missing_dependencies_before_upload(bundle,tmp_path): + t=FakeTransport(bundle);t.info={};a=RunningHubNative(t,Journal(tmp_path/'j.db')) + result=a.submit('a',oid(),bundle,files(bundle),quote={'unit':'POINT','amount':100}) + assert result['state']=='rejected' and '收藏' in result['message'] + assert [p for _,p,_ in t.calls]==['/object_info'] + +def test_journal_no_fixed_cap_three_attempts_and_owner_scope(tmp_path): + j=Journal(tmp_path/'j.db');q={'unit':'POINT','amount':50000} + for n in range(3): + rid=oid();j.reserve('a',rid,'runninghub','acct','case',rid,q) + with pytest.raises(ParityError,match='帳號已有'):j.reserve('a',oid(),'runninghub','acct','other','id',q) + j.update('a',rid,state='completed',actual_cost={'unit':'POINT','amount':n+1}) + with pytest.raises(ParityError,match='最多三次'):j.reserve('a',oid(),'runninghub','new-account','case','new',q) + j.reserve('b',oid(),'runninghub','other-account','case','new',q) + assert j.ledger('a')['runninghub']=={'unit':'POINT','actual':6,'unsettled_reserved':0,'attempts':3} + +def test_stop_lane_two_consecutive_root_causes(tmp_path): + j=Journal(tmp_path/'j.db');q={'unit':'credits','amount':3} + for case in ('a','b'): + rid=oid();j.reserve('a',rid,'autoip','acct',case,rid,q);j.update('a',rid,state='failed',root_cause='missing_model') + with pytest.raises(ParityError,match='相同原因'):j.reserve('a',oid(),'autoip','acct','c','new',q) + j.reserve('other-owner',oid(),'autoip','other','c','new',q) + j.reserve('a',oid(),'runninghub','rh','c','new',{'unit':'POINT','amount':3}) + +def test_account_key_rotation_rejects_old_job(bundle,tmp_path): + t=FakeTransport(bundle);a=RunningHubNative(t,Journal(tmp_path/'j.db'));rid=oid() + a.submit('a',rid,bundle,files(bundle),quote={'unit':'POINT','amount':100}) + t.fingerprint='account-B' + with pytest.raises(ParityError):a.poll('a',rid) + with pytest.raises(ParityError):a.submit('a',rid,bundle,files(bundle),quote={'unit':'POINT','amount':100}) + with pytest.raises(ParityError):a.poll('another-owner',rid) + +@pytest.mark.parametrize('feature',['dance','video-replace','voice-speak']) +def test_autoip_lifecycle_quote_and_files(bundle,tmp_path,feature,monkeypatch): + from compute_parity import autoip_duration + bundle['output_contract']['frames']=391;seal(bundle) + monkeypatch.setattr(autoip_duration,'prepare',lambda raw,n:(raw,{'frames':n})) + monkeypatch.setattr(autoip_duration,'trim',lambda raw,c:raw) + b=voice(bundle) if feature=='voice-speak' else copy.deepcopy(bundle);b['feature']=feature;seal(b) + t=FakeTransport(b);a=AutoIPPublic(t,Journal(tmp_path/'j.db'));rid=oid() + result=a.submit('a',rid,b,files(b),voice_consent=True) + assert result['state']=='queued' and result['cost']['unit']=='credits' + assert [p for _,p,_ in t.calls[:2]]==['/api/v1/pricing','/api/v1/credits/balance'] + if feature=='video-replace':assert t.calls[-1][2]['fields']['mode']=='replacement' + assert a.poll('a',rid)['state']=='queued' + assert '未公開取消' in a.cancel('a',rid)['message'] + t.status={'status':'completed','outputs':[{'url':'ignored-untrusted-url'}]} + assert a.poll('a',rid)['state']=='completed' + assert a.download('a',rid)==b'audio-or-video' + +def test_autoip_unknown_never_resubmits(bundle,tmp_path,monkeypatch): + from compute_parity import autoip_duration + bundle['output_contract']['frames']=391;seal(bundle) + monkeypatch.setattr(autoip_duration,'prepare',lambda raw,n:(raw,{'frames':n})) + t=FakeTransport(bundle);t.timeout=True;a=AutoIPPublic(t,Journal(tmp_path/'j.db'));rid=oid() + a.submit('a',rid,bundle,files(bundle));a.submit('a',rid,bundle,files(bundle));a.recover('a',rid) + assert sum(p=='/api/v1/videos/character-dance' for _,p,_ in t.calls)==1 + +@pytest.mark.parametrize('price,cap',[({'unit':'coins','credits':1},1000),(None,1000),(-2,1000),(True,1000)]) +def test_autoip_quote_refusal(bundle,tmp_path,price,cap): + t=FakeTransport(bundle);t.pricing={'data':{'character_dance':price}};a=AutoIPPublic(t,Journal(tmp_path/'j.db')) + with pytest.raises(ParityError):a.submit('a',oid(),bundle,files(bundle),cap=cap) + assert all(m=='GET' for m,_,_ in t.calls) + +def test_all_adapter_voice_gates_before_io(bundle,tmp_path): + b=voice(bundle);t=FakeTransport(b) + for cls in [RunningHubNative,AutoIPPublic]: + a=cls(t,Journal(tmp_path/(cls.__name__+'.db'))) + with pytest.raises(ParityError):a.submit('a',oid(),b,files(b),quote={'unit':'POINT','amount':1}) + assert not t.calls + +def test_cloud_probe_only_never_sends_voice(bundle): + b=voice(bundle);t=FakeTransport(b);result=CloudManifestProbe(t).probe(b) + assert not result['submit_allowed'] + assert t.calls==[('GET','/api/object_info',{})] + +def test_transport_disabled_and_no_key_in_errors_or_logs(caplog): + secret='MY_SECRET_KEY_123';t=Transport('runninghub',secret) + assert secret not in repr(t) + assert secret not in t.scrub('https://www.runninghub.ai/proxy-plus/'+secret+'/prompt') + with pytest.raises(ParityError):t.request('GET','/object_info') + class Bad: + def request(self,*a,**kw):raise RuntimeError('https://www.runninghub.ai/proxy-plus/'+secret+'/prompt') + with pytest.raises(ParityError) as e:call(Bad(),'GET','/object_info') + assert secret not in str(e.value) and e.value.__context__ is None and secret not in caplog.text + t.enabled=True + with pytest.raises(ParityError) as e:t.request('GET','/object_info') + assert e.value.__context__ is None and secret not in str(e.value) + +def test_native_schema_hashes_and_manifest(bundle,tmp_path): + manifest={'schema_version':1,'job_id':oid(),'deadline_epoch':1,'jobs':[{'engine':'castle_native_p1','type':'video','bundle':bundle}], + 'input_files':[{'path':i['name'],'size':i['bytes'],'sha256':i['sha256']} for i in bundle['inputs']]} + for i in bundle['inputs']: + p=tmp_path/i['name'];p.parent.mkdir(exist_ok=True);p.write_bytes(i['slot'].encode()) + assert validate_native_manifest(manifest,tmp_path)==manifest + (tmp_path/bundle['inputs'][0]['name']).write_bytes(b'bad') + with pytest.raises(ValueError):validate_native_manifest(manifest,tmp_path) + +def test_model_cache_hash_validation_and_repair(tmp_path): + item={'target':'models/a','sha256':hashlib.sha256(b'abc').hexdigest(),'bytes':3,'url':'https://huggingface.co/a/resolve/rev/file'} + calls=[] + def fetch(url,p):calls.append(url);p.write_bytes(b'abc') + p=install_model(item,tmp_path,fetch);assert p.read_bytes()==b'abc' + install_model(item,tmp_path,fetch);assert len(calls)==1 + p.write_bytes(b'bad');install_model(item,tmp_path,fetch);assert len(calls)==2 + p.write_bytes(b'bad') + with pytest.raises(ValueError):install_model(item,tmp_path,lambda u,p:p.write_bytes(b'xxx')) + assert not list(tmp_path.rglob('*.part')) + +def test_bundle_tamper_and_graph_cycle(bundle): + bundle['graph']['3']['inputs']['unet_name']='different' + with pytest.raises(ParityError):validate_bundle(bundle) + graph={'1':{'class_type':'X','inputs':{'input':['1',0]}}} + with pytest.raises(ParityError):validate_graph(graph) + +def test_colab_server_hook_uses_original_lifecycle(bundle,tmp_path,monkeypatch): + import colab_service + class Bridge: + installed=True + def __call__(self,op,directory,**kw): + if op=='account_identity':return {'bound':True,'subject_key':'a'*64} + if op=='account_status':return {'authenticated':True,'balance_compute_units':100} + raise AssertionError(op) + service=colab_service.ColabService(tmp_path/'colab',bridge=Bridge()) + account=service.create_account('a','fake') + monkeypatch.setattr(service,'start',lambda:None) + monkeypatch.setattr(colab_service,'validate_media',lambda p,**kw:{'kind':'video'}) + import colab_inputs + monkeypatch.setattr(colab_inputs,'input_name',lambda name,raw,kind:name) + import base64 + body={'request_id':oid(),'account_id':account['id'],'gpu':'A100','max_units':20,'max_minutes':60, + 'files':[{'name':Path(i['name']).name,'data':base64.b64encode(i['slot'].encode()).decode()} for i in bundle['inputs']]} + result=submit_native(service,'a',body,bundle) + assert result['phase']=='queued' + state=service.job('a',body['request_id']) + assert state['watchdog_sha256'] and state['uploads'] and state['allocation_id'] + assert any(u['path'].endswith('native_runner.py') for u in state['uploads']) + assert submit_native(service,'a',body,bundle)['id']==result['id'] + service.cancel('a',result['id']);service.tick(service.job('a',result['id'])) + assert service.job('a',result['id'])['phase']=='cancelled' + assert service.job('a',result['id'])['released'] is True + +def test_colab_consent_before_auth(bundle): + class NoService: + def __getattr__(self,n):raise AssertionError('Must not use auth before gate') + with pytest.raises(ParityError):submit_native(NoService(),'a',{},voice(bundle,True),voice_consent=False) + + +def test_owner_consent_is_not_role_or_client_truthiness(tmp_path): + from compute_parity.consent import VoiceConsent + consent=VoiceConsent(tmp_path/'consent.db');consent.record('owner',True,'explicit owner decision') + assert consent.permits('owner') + assert not consent.permits('other') and not consent.permits('other','true') + assert consent.permits('other',True) + consent.record('owner',False,'revoked');assert not consent.permits('owner') + +def test_private_model_frozen_and_changed_rejected(tmp_path): + from compute_parity.private_assets import freeze_private_models + p=tmp_path/'model.pt';p.write_bytes(b'private-weight') + b={'models':[{'private':True,'path':str(p),'target':'private/persona.pt','bytes':14,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()}]} + uploads=freeze_private_models(b,tmp_path/'job') + assert uploads[0]['path']=='private-models/private/persona.pt.parts/0' + assert (tmp_path/'job'/uploads[0]['path']).stat().st_mode & 0o777 == 0o600 + from scripts.colab_remote.native_runner import assemble_private_model + recovered=assemble_private_model(tmp_path/'job',tmp_path/'cache',b['models'][0]) + assert recovered.read_bytes()==p.read_bytes() + p.write_bytes(b'changed') + with pytest.raises(ParityError):freeze_private_models(b,tmp_path/'changed') + +def test_cloud_lifecycle_and_unknown_no_retry(bundle,tmp_path): + from compute_parity.adapters import CloudNative + class Cloud(FakeTransport): + def download_output(self,link,**kw):return b'video' + def request(self,method,path,**kw): + self.calls.append((method,path,kw)) + if path=='/api/object_info':return schema(compile_request(bundle,'comfy_cloud',request_id=oid())['probe_graph']) + if path=='/api/v2/assets':return {'id':'asset-owned'} + if path=='/api/v2/jobs': + if self.timeout:raise TimeoutError('secret') + self.submitted=kw;return {'id':'00000000-0000-4000-8000-00000000c001','urls':{'self':'/api/v2/jobs/00000000-0000-4000-8000-00000000c001','cancel':'/api/v2/jobs/00000000-0000-4000-8000-00000000c001/cancel'}} + if path=='/api/v2/jobs/00000000-0000-4000-8000-00000000c001':return self.status + if path.endswith('/cancel'):return {} + if path=='/api/v2/assets/output/content':return b'video' + if path=='/api/jobs?limit=100':return {'jobs':[]} + raise AssertionError(path) + t=Cloud(bundle);a=CloudNative(t,Journal(tmp_path/'cloud.db'));rid=oid() + assert a.submit('a',rid,bundle,files(bundle),quote={'unit':'credits','amount':3000})['state']=='queued' + assert t.submitted['headers']['Idempotency-Key']==rid + assert t.submitted['body']['workflow']['1']['inputs']['image']['__type']=='core/ASSET' + assert a.poll('a',rid)['state']=='queued' + assert a.cancel('a',rid)['state']=='cancelling' + t.status={'status':'succeeded','outputs':[{'url':'/api/v2/assets/output/content','size_bytes':5}]} + assert a.poll('a',rid)['state']=='completed';assert a.download('a',rid)==b'video' + a.submit('a',rid,bundle,files(bundle),quote={'unit':'credits','amount':3000}) + assert sum(p=='/api/v2/jobs' for _,p,_ in t.calls)==1 + t.timeout=True;rid=oid();a.submit('a',rid,bundle,files(bundle),quote={'unit':'credits','amount':2}) + a.recover('a',rid);a.submit('a',rid,bundle,files(bundle),quote={'unit':'credits','amount':2}) + assert sum(p=='/api/v2/jobs' for _,p,_ in t.calls)==2 + with pytest.raises(ParityError):a.poll('other',rid) + +def test_cloud_voice_blocked_before_io(bundle,tmp_path): + from compute_parity.adapters import CloudNative + b=voice(bundle);t=FakeTransport(b);a=CloudNative(t,Journal(tmp_path/'cloud.db')) + with pytest.raises(ParityError,match='Build'):a.submit('a',oid(),b,files(b),quote={'unit':'credits','amount':2},voice_consent=True) + assert not t.calls + +def test_colab_adapter_full_lifecycle_and_uncertain_recovery(bundle,tmp_path): + from contextlib import nullcontext + class Service: + def __init__(self):self.calls=[];self.jobs={};self.timeout=False + def account(self,owner,account): + assert owner=='a' and account=='owned' + def account_guard(self,account,**kw):return nullcontext() + def native_submission_guard(self,owner,rid):return nullcontext() + def claim_request(self,owner,rid):pass # fake store; durable SQL covered by test_review_r37 + def find_job(self,owner,rid):return self.jobs.get(rid) + def _submit(self,owner,body,_native): + self.calls.append(body['request_id']);rid=body['request_id'] + self.jobs[rid]={'id':rid,'phase':'queued','artifacts':[]} + if self.timeout:raise TimeoutError('private-url') + return self.jobs[rid] + def job(self,owner,rid): + assert owner=='a';return self.jobs[rid] + def public_job(self,job):return job + def cancel(self,owner,rid):self.jobs[rid].update(phase='cancelled',released=True,units_observed=2) + def artifact(self,owner,rid,name):return b'output' + service=Service();a=ColabNative(service,Journal(tmp_path/'colab.db'));rid=oid() + q={'unit':'CU','amount':800} + assert a.submit('a',rid,bundle,files(bundle),account_id='owned',quote=q)['state']=='running' + assert a.poll('a',rid)['state']=='running' + service.jobs[rid].update(phase='completed',released=True,units_observed=3,artifacts=[{'name':'a.mp4'}]) + assert a.poll('a',rid)['actual_cost']=={'unit':'CU','amount':3} + assert a.download('a',rid,'a.mp4')==b'output' + service.timeout=True;rid2=oid() + assert a.submit('a',rid2,bundle,files(bundle),account_id='owned',quote=q)['state']=='running' + a.submit('a',rid2,bundle,files(bundle),account_id='owned',quote=q) + assert service.calls.count(rid2)==1 + assert a.cancel('a',rid2)['state']=='cancelled' + assert a.journal.ledger('a')['colab']['actual']==5 + +def test_registration_local_delegates_original_lock_and_remote_off(bundle): + from compute_routing import ComputeAdapter,ComputeRejected + from compute_parity.registration import register + calls=[] + def submit(*args):calls.append(args);return {'state':'queued','downstream_id':'original-lock'} + old=ComputeAdapter(lambda *a:{'eligible':True},submit,None,None,None) + web=SimpleNamespace(s=SimpleNamespace(),router=SimpleNamespace(adapters={'local':old,'runninghub':old})) + register(web);request={'featureId':'dance'} + assert web.router.adapters['local'].submit('a','id',request,{})['downstream_id']=='original-lock' + with pytest.raises(ComputeRejected):web.router.adapters['runninghub'].submit('a','id',request,{}) + assert len(calls)==1 + +def test_owner_credentials_only_use_console_reference(tmp_path): + from contextlib import nullcontext + from compute_parity.owner_credentials import reference_for + from provider_fabric.config import SecretReference,SecretKind + root=tmp_path/'vault';ref=SecretReference(kind=SecretKind.FILE,locator=str(root/'runninghub/acct/api-key.secret')) + console=SimpleNamespace(owner='a',actor=SimpleNamespace(user_id='actor-a'),prefs=SimpleNamespace(db=lambda:nullcontext(None)),runtime=SimpleNamespace(config=SimpleNamespace(credential_root=root))) + data={'actor_id':'actor-a','credential_present':True,'account_id':'acct','credential_ref':{'kind':'file','locator':ref.locator}} + console._raw=lambda lane,db:data + assert reference_for(console,'a','runninghub')==ref + with pytest.raises(ParityError):reference_for(console,'b','runninghub') + data['actor_id']='other' + with pytest.raises(ParityError):reference_for(console,'a','runninghub') + data['actor_id']='actor-a';data['credential_ref']['locator']=str(tmp_path/'secret') + with pytest.raises(ParityError):reference_for(console,'a','runninghub') + +def test_cloud_foreign_links_rejected(): + from compute_parity.adapters import CloudNative + for value in ['https://other.example/api/v2/jobs/a','//other.example/api/v2/jobs/a','/prompt']: + with pytest.raises(ParityError):CloudNative._link(value) + + +def test_v3_dynamic_fields_not_false_missing(): + info={'Resize':{'input':{'required':{'resize':['COMFY_DYNAMICCOMBO_V3',{'options':[{'key':'pixels','inputs':{'required':{'megapixels':['FLOAT',{}]}}}]}]}}}, + 'Batch':{'input':{'required':{'images':['COMFY_AUTOGROW_V3',{'template':{'prefix':'image','min':1,'max':2}}]}}}} + graph={'1':{'class_type':'Resize','inputs':{'resize':'pixels','resize.megapixels':1}}, + '2':{'class_type':'Batch','inputs':{'images.image0':['1',0],'images.image1':['1',0]}}} + assert dependency_probe(graph,info)['ready'] + graph['1']['inputs']['resize']='other';graph['2']['inputs']['images.image2']=['1',0] + assert dependency_probe(graph,info)['missing_inputs']==['Batch.images','Batch.images.image2','Resize.resize','Resize.resize.megapixels'] + + +def test_runninghub_voice_requires_model_execution_contract(bundle,tmp_path): + b=voice(bundle);t=FakeTransport(b);a=RunningHubNative(t,Journal(tmp_path/'rh.db')) + with pytest.raises(ParityError,match='綁定契約'):a.submit('a',oid(),b,files(b),quote={'unit':'POINT','amount':1},voice_consent=True) + assert not t.calls + + +def test_local_campaign_preserves_product_admission_and_three_attempts(bundle,tmp_path): + from compute_parity.local import LocalBaseline + calls=[];state={'state':'queued','downstream_id':'locked-local'} + def submit(*args):calls.append(args);return dict(state) + delegate=SimpleNamespace(submit=submit,status=lambda *a:dict(state),recover=lambda *a:dict(state),cancel=lambda *a:{'state':'cancelled'}) + a=LocalBaseline(delegate,Journal(tmp_path/'local.db'),lambda *a:b'local-output') + rid=oid();assert a.submit('a',rid,bundle,files(bundle),request={'featureId':'dance'})['state']=='queued' + a.submit('a',rid,bundle,files(bundle),request={'featureId':'dance'});assert len(calls)==1 + assert a.cancel('a',rid)['state']=='cancelled' + state['state']='completed';rid=oid();a.submit('a',rid,bundle,files(bundle),request={'featureId':'dance'}) + assert a.download('a',rid)==b'local-output' + assert a.journal.ledger('a')['local']['actual']==0 + with pytest.raises(ParityError):a.download('b',rid) + + +def test_persona_missing_export_refused_before_remote_preparation(bundle): + b=voice(bundle,True);b.pop('voice_export');seal(b) + for lane in ('colab','autoip','runninghub','comfy_cloud'): + with pytest.raises(ParityError,match='尚未封裝'):compile_request(b,lane,request_id=oid(),voice_consent=True) + + +def test_cloud_cdn_no_auth_and_signed_url_not_public(bundle,tmp_path): + from compute_parity.adapters import CloudNative,public + t=FakeTransport(bundle);a=CloudNative(t,Journal(tmp_path/'cdn.db'));rid=oid() + j,_=a.journal.reserve('a',rid,'comfy_cloud',t.fingerprint,'case','identity',{'unit':'credits','amount':1}) + url='https://storage.googleapis.com/owned/output.mp4?signature=synthetic-signature' + a.journal.update('a',rid,state='completed',artifacts=[{'index':0}],output_links=[url],output_metadata=[{'size_bytes':10}]) + t.download_output=lambda link,**kw:b'cdn-output' + assert a.download('a',rid)==b'cdn-output' + assert 'synthetic-signature' not in str(public(a.journal.get('a',rid))) + for bad in ['https://127.0.0.1/api/v2/data','https://evil.test/a','https://evil@storage.googleapis.com/a']: + with pytest.raises(ParityError):a._output_link(bad) + transport=Transport('comfy_cloud','synthetic-provider-key',enabled=True) + class Response: + headers={} + def __enter__(self):return self + def __exit__(self,*a):pass + def read(self,*a):return b'download' + class Opener: + def open(self,request,**kw): + assert not request.get_header('Authorization') and not request.get_header('X-api-key') + return Response() + transport._opener=Opener();assert transport.download_output(url)==b'download' + + +def test_native_runner_source_pin_is_enforced(bundle,tmp_path): + bundle['runner_sources']={'native_runner.py':{'bytes':4,'sha256':hashlib.sha256(b'good').hexdigest()}};seal(bundle) + m={'schema_version':1,'job_id':oid(),'deadline_epoch':1,'jobs':[{'engine':'castle_native_p1','type':'video','bundle':bundle}], + 'input_files':[{'path':i['name'],'size':i['bytes'],'sha256':i['sha256']} for i in bundle['inputs']]} + for i in bundle['inputs']: + p=tmp_path/i['name'];p.parent.mkdir(exist_ok=True);p.write_bytes(i['slot'].encode()) + (tmp_path/'runner').mkdir();(tmp_path/'runner/native_runner.py').write_bytes(b'good') + validate_native_manifest(m,tmp_path) + (tmp_path/'runner/native_runner.py').write_bytes(b'evil') + with pytest.raises(ValueError,match='Runner differs'):validate_native_manifest(m,tmp_path) diff --git a/scripts/test_compute_r29.py b/scripts/test_compute_r29.py new file mode 100644 index 0000000..3e27ccf --- /dev/null +++ b/scripts/test_compute_r29.py @@ -0,0 +1,291 @@ +"""R29 regressions with fake actors, providers, media and clocks; no network.""" +from pathlib import Path +from types import SimpleNamespace as NS +import contextlib,copy,json,sys,uuid +import pytest +ROOT=Path(__file__).resolve().parents[1];sys.path[:0]=[str(ROOT),str(ROOT/'webui')] +from test_compute_parity_p1 import bundle,files,FakeTransport,oid,no_network +from compute_parity.contracts import ParityError,digest,compile_request +from compute_parity.journal import Journal +from compute_parity.materials import Materials +from compute_parity.local import LocalBaseline +from compute_parity.adapters import AutoIPPublic +from compute_parity.readiness import usable,dependencies_usable +from compute_routing import ComputeRejected +import server + + +def test_clipmode_catalog_owner_split(tmp_path): + calls=[] + def owned(actor,cid): + calls.append((actor,cid)) + if actor!='owner-actor':raise KeyError(cid) + return {'id':cid} + w=NS(owner='owner',user={},_feature=lambda r:None, + s=NS(character_entry_for_generation=lambda *a:{'id':a[0]},provider_character_studio_entry=lambda x:x), + h=NS(_provider_runtime_actor=lambda:(NS(store=NS(get_owned_character=owned)),NS(user_id='owner-actor')))) + rows=[{'case_id':str(i),'owner':'owner','feature':'dance','character_id':('clipmode.character:' if i<6 else 'native:')+str(i), + 'label':str(i),'ready':i>=2,'reason':''} for i in range(13)] + (tmp_path/'catalog.json').write_text(json.dumps({'cases':rows})) + m=Materials(w,tmp_path);choices=m.choices('dance') + assert len(choices)==13 and sum(c['ready'] for c in choices)==11 + assert len(calls)==6 and all(c[0]=='owner-actor' for c in calls) + w.owner='other';assert m.choices('dance')==[] + with pytest.raises(ParityError):m.bundle('other',{'featureId':'dance','parity_case_id':'0'}) + + + + + + +@pytest.mark.parametrize('charge,expected',[(100,100),('75.5',75.5),(None,None),(0,None),(-1,None),('NaN',None)]) +def test_autoip_explicit_charge_or_pending(tmp_path,bundle,charge,expected): + j=Journal(tmp_path/'j.sqlite3');t=FakeTransport(bundle);rid=oid() + j.reserve('owner',rid,'autoip',t.fingerprint,bundle['case_id'],'identity',{'unit':'credits','amount':100}) + j.update('owner',rid,state='running',remote_id='remote1') + def request(method,path,**kw): + if path.endswith('/balance'):return {'data':{'available_credits':17000}} + return {'status':'completed','outputs':['artifact'],'credits_charged':charge,'quote':100,'cost':0} + t.request=request;a=AutoIPPublic(t,j);out=a.poll('owner',rid) + if expected is None: + assert 'actual_cost' not in out and out['message']=='已完成、費用待對帳' + assert out['balance_observation']['value']==17000 and out['balance_observation']['at']>0 + assert j.ledger('owner')['autoip']['unsettled_reserved']==100 + else: + assert out['actual_cost']=={'unit':'credits','amount':expected} + assert j.ledger('owner')['autoip']['unsettled_reserved']==0 + + +def test_local_pre_dispatch_rejected_releases_reservation(tmp_path,bundle): + j=Journal(tmp_path/'j.sqlite3');calls=[] + def submit(*a):calls.append(1);raise ComputeRejected('No dispatch',code='persona_hash_mismatch') + adapter=LocalBaseline(NS(submit=submit,recover=None),j,None);rid=oid() + out=adapter.submit('owner',rid,bundle,files(bundle),request={}) + assert out['state']=='rejected' and out['root_cause']=='persona_hash_mismatch' + assert adapter.poll('owner',rid)['state']=='rejected' and len(calls)==1 + assert j.get('owner',rid)['reservation_released'] is True + assert not j.ledger('owner')['local']['unsettled_reserved'] + + +def test_local_unknown_still_uncertain(tmp_path,bundle): + j=Journal(tmp_path/'j.sqlite3') + def submit(*a):raise OSError('connection lost') + adapter=LocalBaseline(NS(submit=submit,recover=None),j,None);rid=oid() + assert adapter.submit('owner',rid,bundle,files(bundle),request={})['state']=='submission_uncertain' + assert adapter.poll('owner',rid)['state']=='submission_uncertain' + + +def test_local_request_binds_server_tuple_and_verifies_persona(monkeypatch,tmp_path): + checks=[];character={'id':'trusted'} + def resolve(c,a,f,v): + assert c==character and (a,f,v)==('voice-speak','voice-speak','voice-speak.persona.v1') + return {'actionId':a,'variantId':v} + w=NS(user={},s=NS(character_entry_for_generation=lambda *a:character,resolve_character_capability=resolve, + apply_character_capability_settings=lambda c,v,s:{**s,'persona':'server-persona'})) + m=Materials(w,tmp_path);monkeypatch.setattr(m,'read',lambda item:checks.append('original')) + monkeypatch.setattr('compute_parity.persona.verify_persona',lambda b,p:checks.append(p)) + b={'feature':'voice-speak','request_context':{'material_character':'trusted'},'material_settings':{'persona':'forged'},'inputs':[],'character_original_image':{}} + req=m.local_request(b,{}) + assert req['characterId']=='trusted' and req['variantId']=='voice-speak.persona.v1' + assert req['settings']['persona']=='server-persona' and checks==['server-persona','original'] + + +def test_local_request_has_no_fixed_voxcpm_binding(monkeypatch,tmp_path): + reads=[];character={'id':'trusted'} + def resolve(*a):raise AssertionError('voxcpm-tts must not resolve a fixed variant') + w=NS(user={},s=NS(character_entry_for_generation=lambda *a:character,resolve_character_capability=resolve, + character_capabilities=lambda c:[])) + m=Materials(w,tmp_path);monkeypatch.setattr(m,'read',lambda item:reads.append(item)) + b={'feature':'voxcpm-tts','request_context':{'material_character':'trusted'},'material_settings':{},'inputs':[],'character_original_image':{}} + with pytest.raises(ParityError,match='角色功能未啟用'):m.local_request(b,{}) + assert reads==[] + + +def test_local_request_refuses_voice_selection(monkeypatch,tmp_path): + reads=[];character={'id':'trusted'} + def resolve(*a):raise AssertionError('a borrowed voice must be refused before capability lookup') + w=NS(user={},s=NS(character_entry_for_generation=lambda *a:character,resolve_character_capability=resolve)) + m=Materials(w,tmp_path);monkeypatch.setattr(m,'read',lambda item:reads.append(item)) + b={'feature':'voice-speak','voice_selection':{'character':'other'},'request_context':{'material_character':'trusted'},'material_settings':{},'inputs':[],'character_original_image':{}} + with pytest.raises(ParityError) as error:m.local_request(b,{}) + assert error.value.code=='voice_selection_unsupported' and reads==[] + + +def test_persona_changed_bytes_rejected(tmp_path): + from compute_parity.persona import verify_persona,fingerprint + (tmp_path/'ref.wav').write_bytes(b'audio');(tmp_path/'breezy_server.py').write_bytes(b'code') + (tmp_path/'refs.json').write_text(json.dumps({'refs':{'fake':{'wav':'ref.wav','text':'synthetic test'}}})) + import hashlib + selected={'variant':'stock','persona':'fake','reference':fingerprint(tmp_path/'ref.wav'), + 'reference_text_sha256':hashlib.sha256(b'synthetic test').hexdigest(),'models':[],'daemon_source':fingerprint(tmp_path/'breezy_server.py')} + b={'material_settings':{'persona':'fake'},'voice_export':{'persona':'fake'},'models':[],'voice_identity_sha256':digest(selected), + 'persona_verification':{'variant':'stock','service_sources':[]}} + verify_persona(b,'fake',root=tmp_path) + (tmp_path/'ref.wav').write_bytes(b'changed') + with pytest.raises(ParityError,match='聲音已變更'):verify_persona(b,'fake',root=tmp_path) + + +@pytest.mark.parametrize('reason,status,code',[('GPU_UNAVAILABLE',503,'allocation_unavailable'),('QUOTA_EXCEEDED',403,'allocation_rejected'),('secret',503,'allocation_uncertain'),(None,504,'allocation_uncertain')]) +def test_colab_diagnostics_allowlist(reason,status,code): + from scripts.colab_allocation_diagnostics import classify + e=Exception('secret-token');e.response=NS(status_code=status,json=lambda:{'error':{'reason':reason,'message':'secret-body','token':'secret'}}) + result,diag=classify(e);assert result==code + assert 'secret' not in json.dumps(diag) and set(diag)<={'http_status','reason_code'} + + +def test_colab_one_retry_after_300_same_gpu(tmp_path): + from colab_service import ColabService,BridgeError + now=[1000];service=ColabService(tmp_path,bridge=lambda *a:None,clock=lambda:now[0]);rid=oid() + state={'id':rid,'owner':'owner','account_id':oid(),'phase':'queued','gpu':'A100','deadline_epoch':5000, + 'uploads':['pinned'],'watchdog_sha256':'pinned','allocation_id':oid()} + with service.db() as db:db.execute('INSERT INTO jobs VALUES (?,?,?,?,?)',(rid,'owner',state['account_id'],'queued',json.dumps(state))) + calls=[] + def call(state,op,**kw): + calls.append((op,kw));raise BridgeError('allocation_unavailable',False,{'reason_code':'GPU_UNAVAILABLE','http_status':503,'token':'private'}) + service._call=call + service.tick(state);first=service.job('owner',rid);assert first['phase']=='allocation_retry_wait' + now[0]=1299;service.tick(first);assert len(calls)==1 + now[0]=1300;service.tick(first);last=service.job('owner',rid) + assert last['phase']=='failed' and last['released'] and len(calls)==2 + assert calls[0][1]['allocation_id']!=calls[1][1]['allocation_id'] and all(c[1]['gpu']=='A100' for c in calls) + service.tick(last);assert len(calls)==2 + assert 'token' not in json.dumps(last) + + +def test_hosted_policy_and_official_alias(bundle): + e={'dependencies_ready':True,'hashes_verified':True,'lifecycle_mode':'provisional_monitored','alias_map_version':'20261111-r29b','alias_evidence_verified':True} + assert dependencies_usable(e,'runninghub') and not usable(e,'runninghub') + e['quote']={'amount':10,'unit':'POINT','basis':'provider'};assert usable(e,'runninghub') + e['lifecycle_mode']='stopped_drain';assert not usable(e,'runninghub') + assert dependencies_usable({'dependencies_ready':True,'hash_mode':'name_size_provisional','lora_sha_verified':True,'alias_map_version':'20261111-r29b','alias_evidence_verified':True},'comfy_cloud') + b=copy.deepcopy(bundle);b['graph']['5']={'class_type':'CLIPLoader','inputs':{'clip_name':'text.safetensors'}};b['graph']['3']['class_type']='LoraLoaderModelOnly';b['graph']['3']['inputs']['lora_name']='Wan21_I2V_14B_lightx2v_cfg_step_distill_lora_rank64.safetensors' + from test_compute_parity_p1 import seal + from compute_parity.model_aliases import reviewed_map, SOURCE + alias=reviewed_map()['runninghub'][SOURCE] + b['models'].append({'name':SOURCE,'target':'models/loras/'+SOURCE,'sha256':alias['source_sha256'],'bytes':alias['bytes']}) + b['hosted_model_proof']={SOURCE:{'md5':alias['evidence']['md5'],'page_id':alias['evidence']['page_id']}} + b=seal(b);plan=compile_request(b,'runninghub',request_id=oid()) + assert plan['json']['prompt']['3']['inputs']['lora_name'].endswith('_official.safetensors') + assert plan['json']['prompt']['3']['class_type']=='LoraLoader' and plan['json']['prompt']['3']['inputs']['strength_clip']==0 + + +def test_monitor_console_test_schedule_and_drain(tmp_path): + from compute_parity.lifecycle import ensure_monitor,tick,pending_monitor + from compute_parity.readiness import save,entries + j=Journal(tmp_path/'j.sqlite3');rid=oid();j.reserve('owner',rid,'runninghub','account','case','id',{'unit':'POINT','amount':10});j.update('owner',rid,state='completed') + @contextlib.contextmanager + def db():yield None + balance=[100];calls=[] + def test(lane,body):calls.append((lane,body));return {'connections':[{'provider':'runninghub','connection_state':'connected','balances':[{'unit':'POINT','value':balance[0]}]}]} + c=NS(root=tmp_path,owner='owner',prefs=NS(db=db),_raw=lambda *a:{'credential_version':1,'revision':3},test=test) + save(tmp_path/'compute-parity',{'owner':'owner','lane':'runninghub','credential_version':1,'bundle_sha256':'b','lifecycle_mode':'provisional_monitored'}) + ensure_monitor(c,j,'owner',rid,now=1000);tick(c,j,now=1000);tick(c,j,now=1299);assert len(calls)==1 + tick(c,j,now=1300);tick(c,j,now=1900);tick(c,j,now=2800);tick(c,j,now=4600) + assert len(calls)==5 and not pending_monitor(j,'owner') + assert [o['offset_seconds'] for o in j.get('owner',rid)['lifecycle_monitor']['observations']]==[0,300,900,1800,3600] + m=j.get('owner',rid)['lifecycle_monitor'];m['state']='pending';m['observations']=m['observations'][:1];j.update('owner',rid,lifecycle_monitor=m) + balance[0]=99;tick(c,j,now=1300) + assert entries(tmp_path/'compute-parity')[0]['lifecycle_mode']=='stopped_drain' and pending_monitor(j,'owner') + + +def test_source_relative_framing_and_one_frame_duration(): + from compute_parity.quality import source_framing,source_duration + source=[[2,2,0] for _ in range(33)] + for i in (0,11,12,23,24):source[i]=[.5,.5,1] + assert source_framing(source,copy.deepcopy(source)) is True # source mid-thigh crop + cropped=copy.deepcopy(source);cropped[23]=[.5,1.1,1] + assert source_framing(source,cropped) is False + assert source_framing([],source) is None + assert source_duration(13.033333,13.033333+1/30,30) + assert not source_duration(13.033333,12.966667,30) + + +def test_local_durable_receipt_recovery(tmp_path): + from compute_web import ComputeWeb + w=object.__new__(ComputeWeb);w.colab=NS(root=tmp_path/'colab') + calls=[];w._run=lambda *a:(calls.append(a) or {'prompt_id':'product-queue-id'}) + rid=oid();receipt=w.submit_local('owner',rid,{'featureId':'voice-speak'}, {}) + assert w.recover_local('owner',rid)==receipt and len(calls)==1 + assert w.recover_local('another',rid) is None + assert receipt['downstream_id']=='product-queue-id' + + +def test_colab_network_loss_keeps_original_id(tmp_path): + from colab_service import ColabService,BridgeError + service=ColabService(tmp_path,bridge=lambda *a:None,clock=lambda:1000);rid=oid();allocation=oid() + state={'id':rid,'owner':'owner','account_id':oid(),'phase':'queued','gpu':'A100','deadline_epoch':5000, + 'uploads':['pinned'],'watchdog_sha256':'pinned','allocation_id':allocation} + with service.db() as db:db.execute('INSERT INTO jobs VALUES (?,?,?,?,?)',(rid,'owner',state['account_id'],'queued',json.dumps(state))) + calls=[] + def call(state,op,**kw): + calls.append((op,kw)) + if op=='runtime_allocate':raise BridgeError('allocation_uncertain',True,{'http_status':504}) + return {'found':False} + service._call=call;service.tick(state);state=service.job('owner',rid) + assert state['phase']=='allocation_uncertain' + service.tick(state);assert [c[0] for c in calls]==['runtime_allocate','runtime_lookup'] + assert all(c[1]['allocation_id']==allocation for c in calls) + + +def test_live_inventory_refresh_can_enable_after_favourite(tmp_path,monkeypatch,bundle): + from compute_parity.hosted_readiness import refresh,PUBLIC_MD5 + from test_compute_parity_p1 import schema,seal + from compute_parity.transport import Transport + @contextlib.contextmanager + def db():yield None + c=NS(root=tmp_path,owner='owner',prefs=NS(db=db),_raw=lambda *a:{'credential_version':1,'account_type':'NORMAL'}) + bundle['hosted_model_proof']={name:{'md5':md5,'page_id':page} for name,(page,md5) in PUBLIC_MD5.items()};seal(bundle) + info=schema(compile_request(bundle,'runninghub',request_id=oid())['json']['prompt']) + t=NS(fingerprint='fake',request=lambda *a,**kw:info) + monkeypatch.setattr(Transport,'for_owner',lambda *a,**kw:t) + ready=refresh(c,bundle,'runninghub',{'runninghub_points':10}) + assert ready['can_enable'] and ready['ready'] + bundle['hosted_model_proof'][next(iter(PUBLIC_MD5))]['md5']='0'*32;seal(bundle) + assert not refresh(c,bundle,'runninghub')['can_enable'] + + +@pytest.mark.parametrize('valid',[True,False]) +def test_colab_sdk_post_assignment_response_is_not_no_assignment(tmp_path,valid): + from scripts.colab_bridge import Bridge,BridgeError + class Assignment:pass + class PostAssignmentResponse: + endpoint='fake-endpoint';runtime_proxy_info=object() + sdk=NS(Assignment=Assignment,Variant=NS(GPU='GPU'),Accelerator=lambda gpu:gpu) + bridge=Bridge(tmp_path,sdk);bridge._client=NS(assign=lambda *a,**kw:PostAssignmentResponse() if valid else None) + saved=[];bridge.save_assignment=lambda *a:saved.append(a) + request={'allocation_id':oid(),'gpu':'A100'} + if valid: + assert bridge.runtime_allocate(request)['found'] and len(saved)==1 + else: + with pytest.raises(BridgeError) as error:bridge.runtime_allocate(request) + assert error.value.code=='allocation_uncertain' and error.value.ambiguous and not saved + + +def test_colab_xssi_error_whitelists_only_reason(): + from scripts.colab_allocation_diagnostics import classify + def bad():raise ValueError('not plain JSON') + error=Exception('private');error.response=NS(status_code=503,json=bad) + error.response_body=")]}'\n"+json.dumps({'error':{'reason':'GPU_UNAVAILABLE','token':'private'}}) + code,diag=classify(error) + assert code=='allocation_unavailable' and diag=={'http_status':503,'reason_code':'GPU_UNAVAILABLE'} + + +def test_cloud_import_changes_readiness_but_keeps_provisional_label(tmp_path,monkeypatch,bundle): + from compute_parity.hosted_readiness import refresh,LORA_SHA + from test_compute_parity_p1 import schema,seal + from compute_parity.transport import Transport + @contextlib.contextmanager + def db():yield None + c=NS(root=tmp_path,owner='owner',prefs=NS(db=db),_raw=lambda *a:{'credential_version':1,'account_type':'NORMAL'}) + b=copy.deepcopy(bundle);b['models'].append({'name':'Wan21_I2V_fixture.safetensors','target':'models/loras/test.safetensors','bytes':10,'sha256':LORA_SHA});seal(b) + info=schema(compile_request(b,'comfy_cloud',request_id=oid())['probe_graph']);imported=[False] + def request(method,path,**kw): + if 'object_info' in path:return info + from urllib.parse import parse_qs,urlsplit + name=parse_qs(urlsplit(path).query)['name_contains'][0] + m=next(m for m in b['models'] if m['name']==name) + return {'assets':[] if name.startswith('Wan21') and not imported[0] else [{'name':name,'size':m['bytes']}]} + monkeypatch.setattr(Transport,'for_owner',lambda *a,**kw:NS(fingerprint='fake',request=request)) + assert not refresh(c,b,'comfy_cloud')['can_enable'] + imported[0]=True;result=refresh(c,b,'comfy_cloud',{'comfy_cloud_credits':10}) + assert result['can_enable'] and result['ready'] and 'hash 未驗' in result['verification_note'] diff --git a/scripts/test_compute_r29b.py b/scripts/test_compute_r29b.py new file mode 100644 index 0000000..ce369c4 --- /dev/null +++ b/scripts/test_compute_r29b.py @@ -0,0 +1,203 @@ +"""Hosted alias/estimate regressions with fake provider schemas and owned bytes.""" +import contextlib +import copy +from types import SimpleNamespace as NS +from urllib.parse import parse_qs, urlsplit +import pytest +from test_compute_parity_p1 import bundle, no_network, seal, oid, schema, files, FakeTransport +from compute_parity.contracts import compile_request, dependency_probe, ParityError +from compute_parity.hosted_readiness import refresh, PUBLIC_MD5 +from compute_parity.readiness import dependencies_usable, entries +from compute_parity.hosted_estimates import estimate, MEASUREMENTS +from compute_parity.transport import Transport +from compute_parity.adapters import RunningHubNative, CloudNative +from compute_parity.runtime import Runtime +from compute_parity.journal import Journal +from compute_parity import model_aliases as aliases + +@pytest.fixture +def alias_bundle(bundle): + b=copy.deepcopy(bundle) + a=aliases.reviewed_map()['runninghub'][aliases.SOURCE] + b['models'].append({'name':aliases.SOURCE,'target':'models/loras/'+aliases.SOURCE, + 'bytes':a['bytes'],'sha256':a['source_sha256']}) + b['hosted_model_proof']={name:{'md5':md5,'page_id':page} for name,(page,md5) in PUBLIC_MD5.items()} + b['graph']['5']={'class_type':'CLIPLoader','inputs':{'clip_name':'text.safetensors'}} + b['graph']['6']={'class_type':'LoraLoaderModelOnly','inputs':{'lora_name':aliases.SOURCE,'model':['3',0],'strength_model':1.0}} + return seal(b) + +def console(root): + @contextlib.contextmanager + def db(): yield None + return NS(root=root,owner='owner',prefs=NS(db=db),_raw=lambda *a:{'credential_version':1,'account_type':'NORMAL'}) + +@pytest.mark.parametrize('lane',['runninghub','comfy_cloud']) +def test_compile_probe_and_inventory_use_exact_alias(alias_bundle,lane,tmp_path,monkeypatch): + original=copy.deepcopy(alias_bundle) + plan=compile_request(alias_bundle,lane,request_id=oid()) + graph=plan.get('probe_graph') or plan['json']['prompt'] + target=aliases.reviewed_map()[lane][aliases.SOURCE]['target_name'] + assert graph['6']['inputs']['lora_name']==target and alias_bundle==original + info=schema(graph) + assert dependency_probe(graph,info)['ready'] + info[graph['6']['class_type']]['input']['required']['lora_name']=([aliases.SOURCE],{}) + assert dependency_probe(graph,info)['missing_models']==[target] + info=schema(graph) + if lane=='comfy_cloud':info[graph['6']['class_type']]['input']['required']['lora_name']=(['public-only.safetensors'],{}) + calls=[];available=[True] + def request(method,path,**kw): + assert method=='GET';calls.append(path) + if 'object_info' in path:return info + q=parse_qs(urlsplit(path).query);name=q['name_contains'][0] + if name==target:assert q['include_public']==['false'] + model=next(m for m in alias_bundle['models'] if m['name']==name or (name==target and m['name']==aliases.SOURCE)) + a=aliases.reviewed_map()[lane][aliases.SOURCE] + return {'assets':[{'name':name,'size':model['bytes'],'tags':['models','loras'],'loader_path':name, + 'metadata':{'revision':a['evidence'].get('revision'),'resolve_url':a['evidence'].get('url')}}] if available[0] else []} + monkeypatch.setattr(Transport,'for_owner',lambda *a,**kw:NS(fingerprint='fake',request=request)) + r=refresh(console(tmp_path),alias_bundle,lane,{'runninghub_points':10,'comfy_cloud_credits':10},persist=False) + assert r['can_enable'] and r['ready'] and not entries(tmp_path/'compute-parity') + record=r['model_aliases'][0] + assert record['source_name']==aliases.SOURCE and record['target_name']==target and record['evidence'] + if lane=='comfy_cloud': + available[0]=False + assert not refresh(console(tmp_path),alias_bundle,lane,persist=False)['can_enable'] + +@pytest.mark.parametrize('lane',['runninghub','comfy_cloud']) +@pytest.mark.parametrize('damage',['missing_map','missing_evidence','wrong_hash','wrong_size']) +def test_missing_or_mismatched_alias_evidence_not_ready(alias_bundle,lane,tmp_path,monkeypatch,damage): + if damage in {'missing_map','missing_evidence'}: + data=aliases.reviewed_map() + if damage=='missing_map':data.pop(lane) + else:data[lane][aliases.SOURCE]['evidence']={} + monkeypatch.setattr(aliases,'reviewed_map',lambda:data) + else: + model=next(m for m in alias_bundle['models'] if m['name']==aliases.SOURCE) + if damage=='wrong_hash':model['sha256']='0'*64 + else:model['bytes']+=1 + seal(alias_bundle) + monkeypatch.setattr(Transport,'for_owner',lambda *a,**kw:pytest.fail('must reject before provider access')) + r=refresh(console(tmp_path),alias_bundle,lane) + assert not r['ready'] and not r['can_enable'] + assert not dependencies_usable(entries(tmp_path/'compute-parity')[0],lane) + +@pytest.mark.parametrize('lane',['local','colab','autoip']) +def test_other_lanes_do_not_read_alias_map(alias_bundle,lane,monkeypatch): + monkeypatch.setattr(aliases,'reviewed_map',lambda:pytest.fail('non-hosted lane read alias map')) + plan=compile_request(alias_bundle,lane,request_id=oid()) + assert plan.get('model_aliases',[])==[] + if lane!='autoip':assert plan['json']['prompt']['6']['inputs']['lora_name']==aliases.SOURCE + +@pytest.mark.parametrize('lane',['runninghub','comfy_cloud']) +def test_stale_readiness_without_alias_verification_rejected(lane): + e={'dependencies_ready':True,'hashes_verified':True,'lifecycle_verified':True} + assert not dependencies_usable(e,lane) + +@pytest.mark.parametrize('lane',['runninghub','comfy_cloud']) +def test_receipts_persist_both_names(alias_bundle,lane,tmp_path): + plan=compile_request(alias_bundle,lane,request_id=oid()) + graph=plan.get('probe_graph') or plan['json']['prompt'] + class Fake(FakeTransport): + def request(self,method,path,**kw): + if path=='/api/object_info':return schema(graph) + if path.startswith('/api/assets?'): + a=aliases.reviewed_map()['comfy_cloud'][aliases.SOURCE] + return {'assets':[{'name':a['target_name'],'size':a['bytes'],'tags':['models','loras'],'loader_path':a['target_name'], + 'metadata':{'revision':a['evidence']['revision'],'resolve_url':a['evidence']['url']}}]} + if path=='/api/v2/assets':return {'id':'asset-fake'} + if path=='/api/v2/jobs':return {'id':'00000000-0000-4000-8000-00000000c001','urls':{'self':'/api/v2/jobs/00000000-0000-4000-8000-00000000c001','cancel':'/api/v2/jobs/00000000-0000-4000-8000-00000000c001/cancel'}} + return super().request(method,path,**kw) + t=Fake(alias_bundle);j=Journal(tmp_path/'journal.sqlite3');rid=oid() + adapter=(RunningHubNative if lane=='runninghub' else CloudNative)(t,j) + job=adapter.submit('owner',rid,alias_bundle,files(alias_bundle),quote={'unit':'POINT' if lane=='runninghub' else 'credits','amount':10}) + assert job['state']=='queued' + receipt=Runtime.receipt(job) + assert receipt['model_aliases']==j.get('owner',rid)['model_aliases']==plan['model_aliases'] + assert receipt['model_aliases'][0]['source_name']==aliases.SOURCE + assert receipt['model_aliases'][0]['target_name']!=aliases.SOURCE + from compute_routing import _public_receipt + routed=_public_receipt(receipt) + assert routed['model_aliases']==receipt['model_aliases'] + assert routed['estimated_cost']['is_estimate'] and routed['actual_cost'] is None + +@pytest.mark.parametrize('lane,rate',[('runninghub',0.25),('comfy_cloud',0.266)]) +def test_reviewed_case_estimate_and_unknown_case(lane,rate,monkeypatch): + monkeypatch.setitem(MEASUREMENTS, 'synthetic-bundle', {'case_id':'dance.realistic.example-a','wall_seconds':500}) + key,m=next(iter(MEASUREMENTS.items())) + b={'bundle_sha256':key,'case_id':m['case_id']} + q=estimate(b,lane) + assert q['amount']==round(m['wall_seconds']*1.5*rate,6) + assert q['actual_cost'] is None and q['is_estimate'] and q['rate_source'] + if lane=='runninghub':assert '估計,非官方報價' in q['label'] + assert estimate({**b,'bundle_sha256':'changed'},lane)=={} + assert estimate({**b,'case_id':'different'},lane)=={} + +def test_cloud_runtime_cap(monkeypatch): + monkeypatch.setitem(MEASUREMENTS, 'synthetic-bundle', {'case_id':'dance.realistic.example-a','wall_seconds':500}) + key,m=next(iter(MEASUREMENTS.items()));b={'bundle_sha256':key,'case_id':m['case_id']} + q=estimate(b,'comfy_cloud',cloud_limit_seconds=600) + assert q['expected_seconds']==600 and q['amount']==159.6 + assert estimate(b,'comfy_cloud',cloud_limit_seconds=0)=={} + +@pytest.mark.parametrize('damage',['size','tags','loader_path','revision','resolve_url','name']) +def test_cloud_private_inventory_rejects_wrong_category_or_provenance(alias_bundle,damage): + from compute_parity.cloud_inventory import private_aliases + plan=compile_request(alias_bundle,'comfy_cloud',request_id=oid()) + a=aliases.reviewed_map()['comfy_cloud'][aliases.SOURCE] + row={'name':a['target_name'],'size':a['bytes'],'tags':['models','loras'],'loader_path':a['target_name'], + 'metadata':{'revision':a['evidence']['revision'],'resolve_url':a['evidence']['url']}} + if damage in {'revision','resolve_url'}:row['metadata'][damage]='wrong' + else:row[damage]=[] if damage=='tags' else 1 if damage=='size' else 'wrong' + allowed,records=private_aliases(alias_bundle,plan['probe_graph'],NS(request=lambda *a,**kw:{'assets':[row]})) + assert not allowed and not records[0]['present'] + +def test_cloud_usage_units_and_no_false_settlement(): + from compute_parity.cloud_usage import observe + t=NS(request=lambda *a:{'summary':{'balance':{'currency':'USD','amount_micros':25000},'spend_micros':1000000}}) + o=observe(t) + assert o['balance_usd_cents']==25000 and o['workspace_spend_usd_micros']==1000000 + assert 'actual_cost' not in o and o['scope']=='workspace' and o['reporting_may_lag'] + +@pytest.mark.parametrize('lane',['runninghub','comfy_cloud']) +def test_changed_release_map_invalidates_readiness(alias_bundle,lane,tmp_path,monkeypatch): + monkeypatch.setattr(aliases,'MAP_SHA256','0'*64) + r=refresh(console(tmp_path),alias_bundle,lane,persist=False) + assert not r['can_enable'] and r['reason']=='model_alias_evidence_missing' + assert not dependencies_usable({'dependencies_ready':True,'hashes_verified':True,'lifecycle_verified':True, + 'alias_map_version':aliases.VERSION,'alias_evidence_verified':True},lane) + +def test_cloud_completion_observes_usage_without_claiming_estimate_as_actual(tmp_path,bundle): + j=Journal(tmp_path/'journal.sqlite3');rid=oid() + j.reserve('owner',rid,'comfy_cloud','fake','case','identity',{'unit':'credits','amount':200.5}) + j.update('owner',rid,state='queued',remote_id='00000000-0000-4000-8000-00000000c001',links={'self':'/api/v2/jobs/00000000-0000-4000-8000-00000000c001'}) + calls=[] + def request(method,path,**kw): + assert method=='GET';calls.append(path) + if path=='/api/v2/jobs/00000000-0000-4000-8000-00000000c001':return {'status':'succeeded','outputs':[{'url':'/api/v2/assets/result/content','size_bytes':5}]} + if path=='/api/billing/usage/timeseries':return {'summary':{'balance':{'currency':'USD','amount_cents':100},'spend_micros':2000000}} + pytest.fail('unexpected provider call') + a=CloudNative(NS(fingerprint='fake',request=request),j) + result=a.poll('owner',rid) + assert result['state']=='completed' and result['settlement_status']=='pending' + assert result.get('actual_cost') is None and result['cost']['amount']==200.5 + assert result['balance_observation']['balance_usd_cents']==100 + a.poll('owner',rid) + assert calls==['/api/v2/jobs/00000000-0000-4000-8000-00000000c001','/api/billing/usage/timeseries'] + +@pytest.mark.parametrize('lane',['local','colab','autoip']) +def test_nonhosted_receipt_unchanged(lane): + job={'lane':lane,'request_id':'fake','state':'queued','cost':{'unit':'fake','amount':1}} + r=Runtime.receipt(job) + assert all(r[k]==v for k,v in {'state':'queued','downstream_id':'fake','cancel_supported':lane!='autoip','result_ids':[],'cost':job['cost']}.items()) + if lane in {'autoip','colab'}:assert r['estimated_cost']==job['cost'] and r['actual_cost'] is None + +def test_router_never_echoes_unreviewed_alias_fields(): + from compute_routing import _public_receipt, ComputeUncertain + a=copy.deepcopy(aliases.reviewed_map()['comfy_cloud'][aliases.SOURCE]) + a.update(map_version=aliases.VERSION,private_provider_field='not-public') + value={'state':'queued','downstream_id':'fake','model_aliases':[a], + 'estimated_cost':{'unit':'credits','amount':10,'private_provider_field':'not-public'}} + r=_public_receipt(value) + assert 'private_provider_field' not in str(r) + value['model_aliases'][0]['target_name']='not-reviewed' + with pytest.raises(ComputeUncertain):_public_receipt(value) diff --git a/scripts/test_compute_r29c.py b/scripts/test_compute_r29c.py new file mode 100644 index 0000000..543420d --- /dev/null +++ b/scripts/test_compute_r29c.py @@ -0,0 +1,29 @@ +"""Borrowed persona calibration contracts; fake media, no dispatch/network.""" +from pathlib import Path +from types import SimpleNamespace as NS +import copy, json, sys +import pytest +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT / 'webui')] +import server +from compute_parity.materials import Materials +from compute_parity.contracts import digest, ParityError, compile_request +from test_compute_parity_p1 import no_network + + + + + + + + + + + + +def test_unpaired_character_still_has_no_persona_capability(): + own = {'id': 'example-a', 'name': 'Example A', 'visualClass': 'realistic', 'kind': 'provider_character'} + with pytest.raises(ValueError): + server.resolve_character_capability(own, 'voice-speak', 'voice-speak', 'voice-speak.persona.v1') + + diff --git a/scripts/test_compute_r30.py b/scripts/test_compute_r30.py new file mode 100644 index 0000000..e91e5c4 --- /dev/null +++ b/scripts/test_compute_r30.py @@ -0,0 +1,325 @@ +"""r30 regression: trimmed authenticated provider GET fixtures plus adversarial cases.""" +import copy,io,json,time,uuid,urllib.error +from pathlib import Path +from types import SimpleNamespace as NS +import pytest +from test_compute_parity_p1 import bundle,files,oid,FakeTransport,no_network,seal +from compute_parity.adapters import RunningHubNative,CloudNative,AutoIPPublic,call +from compute_parity.journal import Journal +from compute_parity.contracts import compile_request,dependency_probe,ParityError +from compute_parity.transport import Transport +F=Path(__file__).parent/'fixtures/r30' +def fixture(name):return json.loads((F/name).read_text()) +CLOUD=fixture('cloud-job.json')['id'] +REQUEST='00000000-0000-4000-8000-00000000d001' + +def reserved(tmp_path,lane='runninghub',rid=None): + j=Journal(tmp_path/'journal.db');rid=rid or oid() + j.reserve('owner',rid,lane,'account','dance.anime.chatgpt','identity',{'unit':'POINT' if lane=='runninghub' else 'credits','amount':100}) + j.update('owner',rid,state='submission_uncertain',created_at=0,submitted_at=0) + return j,rid + +@pytest.mark.parametrize('inventory',[None,{('unused','unused','unused')}]) +def test_real_required_schema_and_v3_groups(inventory): + info=fixture('runninghub-object-info.json') + values={'video':'owned.mp4','force_rate':16,'custom_width':432,'custom_height':768,'frame_load_cap':213,'skip_first_frames':0,'select_every_nth':1} + g={'15':{'class_type':'VHS_LoadVideo','inputs':values},'28':{'class_type':'BatchImagesNode','inputs':{'images.image0':['15',0],'images.image1':['15',0]}}} + assert dependency_probe(g,info,model_inventory=inventory)['missing_inputs']==['VHS_LoadVideo.force_size'] + values['force_size']='Custom' + assert dependency_probe(g,info,model_inventory=inventory)['ready'] + g['28']['inputs']={} + assert dependency_probe(g,info)['missing_inputs']==['BatchImagesNode.images'] + g['28']['inputs']={'images.image51':['15',0]} + assert not dependency_probe(g,info)['ready'] + +def test_compiled_loader_custom_preserves_approved_dimensions(bundle): + bundle['graph']['2']['inputs'].update(custom_width=432,custom_height=768);seal(bundle) + v=compile_request(bundle,'runninghub',request_id=oid())['json']['prompt']['2']['inputs'] + assert (v['force_size'],v['custom_width'],v['custom_height'])==('Custom',432,768) + +class CloudCaptured(FakeTransport): + def __init__(self,b):super().__init__(b);self.fingerprint='account' + def request(self,method,path,**kw): + self.calls.append((method,path,kw)) + if path=='/api/v2/assets':return {'id':oid()} + if path=='/api/v2/jobs':return fixture('cloud-job.json') + if path=='/api/jobs?limit=100':return fixture('cloud-jobs.json') + if path.endswith('/workflow'):return fixture('cloud-workflow.json') + if path=='/api/v2/jobs/'+CLOUD:return fixture('cloud-job.json') + if path=='/api/billing/usage/timeseries':return {} + pytest.fail('Unexpected provider operation') + +def test_cloud_persists_id_despite_http_links(bundle,tmp_path,monkeypatch): + t=CloudCaptured(bundle);a=CloudNative(t,Journal(tmp_path/'j.db'));monkeypatch.setattr(a,'probe',lambda b:{'ready':True}) + result=a.submit('owner',REQUEST,bundle,files(bundle),quote={'unit':'credits','amount':10}) + assert result['remote_id']==CLOUD and result['state']=='queued' + j=a.journal.get('owner',REQUEST);assert j['links']['self']=='/api/v2/jobs/'+CLOUD + a.poll('owner',REQUEST) + assert a.journal.get('owner',REQUEST)['output_links'][0].startswith('/api/v2/assets/') + assert all(not p.startswith('http:') for _,p,_ in t.calls) + +def test_cloud_id_survives_link_processing_exception(bundle,tmp_path,monkeypatch): + t=CloudCaptured(bundle);a=CloudNative(t,Journal(tmp_path/'j.db'));monkeypatch.setattr(a,'probe',lambda b:{'ready':True}) + monkeypatch.setattr(a,'_job_links',lambda rid:(_ for _ in ()).throw(ParityError('cloud_link_invalid','safe'))) + result=a.submit('owner',REQUEST,bundle,files(bundle),quote={'unit':'credits','amount':10}) + assert result['remote_id']==CLOUD + +def test_cloud_exact_executed_graph_recovery_never_posts(bundle,tmp_path): + j,rid=reserved(tmp_path,'comfy_cloud',REQUEST);t=CloudCaptured(bundle);a=CloudNative(t,j) + result=a.recover('owner',rid) + assert result['state']=='completed' and result['remote_id']==CLOUD + assert all(m=='GET' for m,_,_ in t.calls) + assert j.get('owner',rid)['recovery_evidence']['new_submissions']==0 + +@pytest.mark.parametrize('prefix',['parity/different','parity/'+REQUEST+'extra']) +def test_cloud_nonmatching_prefix_not_recovered(bundle,tmp_path,prefix): + j,rid=reserved(tmp_path,'comfy_cloud',REQUEST);t=CloudCaptured(bundle);original=t.request + def req(m,p,**kw): + if p.endswith('/workflow'):return {'workflow':{'1':{'inputs':{'filename_prefix':prefix}}}} + return original(m,p,**kw) + t.request=req + assert CloudNative(t,j).recover('owner',rid)['state']=='submission_uncertain' + assert not j.get('owner',rid).get('remote_id') + +class Response: + def __init__(self,raw=b'video'):self.raw=raw;self.headers={'Content-Length':str(len(raw))} + def __enter__(self):return self + def __exit__(self,*a):pass + def read(self,*a):return self.raw + +def redirect(url):return urllib.error.HTTPError('https://cloud.comfy.org',302,'Found',{'Location':url},io.BytesIO()) + +def test_cloud_real_302_shape_drops_key_and_checks_size(): + t=Transport('comfy_cloud','synthetic-test-key',enabled=True);calls=[] + loc=fixture('cloud-redirect.json')['location'] + def open(req,**kw): + calls.append(req) + if len(calls)==1:raise redirect(loc) + assert not req.get_header('Authorization') and not req.get_header('X-api-key') + return Response() + t._opener=NS(open=open) + assert t.download_output('/api/v2/assets/00000000-0000-4000-8000-00000000c002/content',expected_size=5)==b'video' + assert calls[0].get_header('Authorization') + with pytest.raises(ParityError):t.download_output(loc,expected_size=6) + +@pytest.mark.parametrize('url',['http://storage.googleapis.com/a','https://evil.test/a','https://user@storage.googleapis.com/a','https://storage.googleapis.com:444/a','https://127.0.0.1/a']) +def test_cloud_malicious_redirect_rejected_before_next_request(url): + t=Transport('comfy_cloud','synthetic-test-key',enabled=True);calls=[] + def open(req,**kw):calls.append(req);raise redirect(url) + t._opener=NS(open=open) + with pytest.raises(ParityError):t.download_output('/api/v2/assets/00000000-0000-4000-8000-00000000c002/content') + assert len(calls)==1 + +def test_cloud_redirect_bound_and_no_key_when_redirecting_back(): + t=Transport('comfy_cloud','synthetic-test-key',enabled=True);calls=[] + origin='https://cloud.comfy.org/api/v2/assets/00000000-0000-4000-8000-00000000c002/content' + def open(req,**kw): + calls.append(req) + if len(calls)>1:assert not req.get_header('Authorization') + raise redirect('https://storage.googleapis.com/a' if len(calls)%2 else origin) + t._opener=NS(open=open) + with pytest.raises(ParityError):t.download_output(origin) + assert len(calls)==4 + +def validation_body(prompt=None): + # Synthetic error case: original failed POST was NOT captured. Real required schema above establishes B8. + return {'prompt_id':prompt,'error':{'type':'prompt_outputs_failed_validation','message':'https://private.invalid/token'}, + 'node_errors':{'15':{'class_type':'VHS_LoadVideo','errors':[{'type':'required_input_missing','message':'PRIVATE'}]}}} + +@pytest.mark.parametrize('accepted',[False,True]) +def test_runninghub_diagnostics_and_prompt_id_precede_node_errors(bundle,tmp_path,accepted): + t=FakeTransport(bundle);old=t.request + t.request=lambda m,p,**kw:validation_body('native-id' if accepted else None) if p=='/prompt' else old(m,p,**kw) + a=RunningHubNative(t,Journal(tmp_path/'j.db'));rid=oid() + r=a.submit('owner',rid,bundle,files(bundle),quote={'unit':'POINT','amount':10}) + assert r['state']==('queued' if accepted else 'rejected') + assert bool(r.get('remote_id'))==accepted + assert r['diagnostics']['nodes']==[{'node_id':'15','node_class':'VHS_LoadVideo','error_type':'required_input_missing'}] + assert 'PRIVATE' not in str(r) and 'https:' not in str(r) + +def test_transport_keeps_safe_http_reason_without_raw_error(): + t=Transport('runninghub','synthetic-test-key',enabled=True) + body=json.dumps(validation_body()).encode() + t._opener=NS(open=lambda *a,**kw:(_ for _ in ()).throw(urllib.error.HTTPError('https://private',400,'PRIVATE',{},io.BytesIO(body)))) + with pytest.raises(ParityError) as error:call(t,'POST','/prompt',body={}) + assert error.value.diagnostics['http_status']==400 + assert error.value.diagnostics['reason_code']=='prompt_outputs_failed_validation' + assert 'PRIVATE' not in str(error.value) + +@pytest.mark.parametrize('before,age,span,drop,closed',[(True,3599,0,0,False),(True,3600,0,0,True),(True,7200,0,1,False),(False,3600,1799,0,False),(False,3600,1800,0,True),(False,7200,1800,1,False)]) +def test_uncertain_closure_all_conditions(tmp_path,monkeypatch,before,age,span,drop,closed): + j,rid=reserved(tmp_path);now=[age-span];monkeypatch.setattr(time,'time',lambda:now[0]);value=[100] + captured=fixture('runninghub-absence.json');calls=[] + def request(m,p,**kw):calls.append((m,p));assert m=='GET';return copy.deepcopy(captured[p[1:]]) + a=RunningHubNative(NS(fingerprint='account',request=request),j);a.observe_point=lambda:value[0] + if before:j.update('owner',rid,pre_submission_point={'at':-1,'account':'account','unit':'POINT','value':100}) + else:a.recover('owner',rid) + now[0]=age;value[0]-=drop;r=a.recover('owner',rid) + assert (r['state']=='closed_no_execution_evidence')==closed + assert j.get('owner',rid)['closure_evidence']['history_absent'] + if closed: + original=j.get('owner',rid);a.recover('owner',rid);assert j.get('owner',rid)==original + # New request, counted separately; original never re-POSTed. + for n in (1,2): + new=oid();j.reserve('owner',new,'runninghub','account','dance.anime.chatgpt',new,{'unit':'POINT','amount':1});j.update('owner',new,state='rejected') + with pytest.raises(ParityError) as error:j.reserve('owner',oid(),'runninghub','account','dance.anime.chatgpt','next',{'unit':'POINT','amount':1}) + assert error.value.code=='attempt_cap' + +@pytest.mark.parametrize('damage',['queue','history','malformed','balance','account']) +def test_uncertain_no_false_closure(tmp_path,monkeypatch,damage): + j,rid=reserved(tmp_path);monkeypatch.setattr(time,'time',lambda:7200) + captured=fixture('runninghub-absence.json') + if damage=='queue':captured['queue']['queue_running']=[[0,'remote',{}, {'castle_request_id':rid}]] + if damage=='history':captured['history']={'remote':{'prompt':[0,'remote',{}, {'castle_request_id':rid}]}} + if damage=='malformed':captured['queue']={} + a=RunningHubNative(NS(fingerprint='account',request=lambda m,p,**kw:captured[p[1:]]),j) + a.observe_point=lambda:None if damage=='balance' else 100 + j.update('owner',rid,pre_submission_point={'at':-1,'unit':'POINT','account':'other' if damage=='account' else 'account','value':100}) + try:a.recover('owner',rid) + except ParityError:pass + assert j.get('owner',rid)['state']!='closed_no_execution_evidence' + +def test_uncertain_never_starts_completed_monitor(tmp_path): + from compute_parity.lifecycle import ensure_monitor + j,rid=reserved(tmp_path);ensure_monitor(NS(),j,'owner',rid) + assert 'lifecycle_monitor' not in j.get('owner',rid) + +def test_autoip_terminal_settlement_monotonic_and_outer_id(tmp_path): + from compute_routing import ComputeRouter,ComputeAdapter + from compute_parity.runtime import Runtime + j,rid=reserved(tmp_path,'autoip');response=fixture('autoip-settlement.json') + j.update('owner',rid,state='completed',remote_id=response['task_uuid'],artifacts=[{'index':0}]) + calls=[] + def get(m,p,**kw):calls.append((m,p));assert m=='GET';return response + a=AutoIPPublic(NS(fingerprint='account',request=get),j) + router=ComputeRouter(tmp_path/'router.db',{'autoip':ComputeAdapter(inspect=lambda *a:{'eligible':True},submit=lambda *a:Runtime.receipt(j.get('owner',rid)),status=lambda o,r:Runtime.receipt(a.poll(o,r)))}) + # Use ordinary public router submission, with only the adapter dispatch mocked. + result=router.submit('owner',rid,{'featureId':'dance','settings':{}},placement='autoip') + first=router.status('owner',rid,refresh=True) + assert first['state']=='completed' + assert first['actual_cost']=={'unit':'credits','amount':100} + snapshot=router.status('owner',rid,refresh=True);assert snapshot==first + assert calls==[('GET','/api/v1/tasks/'+response['task_uuid'])] + j.update('owner',rid,state='failed',artifacts=[],actual_cost=None,settlement_status='pending') + assert j.get('owner',rid)['state']=='completed' and j.get('owner',rid)['artifacts']==[{'index':0}] + assert j.get('owner',rid)['actual_cost']['amount']==100 + +def test_colab_whitelisted_stage_diagnostics_and_cu(tmp_path): + from scripts.colab_remote.remote_job import sanitize_diagnostics + from compute_parity.colab import ColabNative + from compute_parity.runtime import Runtime + from compute_routing import _public_receipt + j=Journal(tmp_path/'j.db');rid=oid();j.reserve('owner',rid,'colab','account','case','id',{'unit':'CU','amount':15}) + diagnostic={'stage':'prompt_validation','error_type':'ValueError','error_code':'node_validation_failed','node_class':'VHS_LoadVideo','node_id':'15','http_status':400,'stdout':'SECRET','url':'https://private','token':'SECRET'} + r=ColabNative(NS(),j)._record('owner',rid,{'id':rid,'phase':'failed','released':True,'units_observed':.1,'diagnostics':diagnostic}) + assert 'SECRET' not in str(r) and 'A100 unavailable' not in str(r) + assert r['diagnostics']==sanitize_diagnostics(diagnostic) + assert _public_receipt(Runtime.receipt(r))['actual_cost']=={'unit':'CU','amount':.1} + +@pytest.mark.parametrize('stage',['bootstrap','model_download','node_start','prompt_validation','execute','ffprobe']) +def test_colab_stage_whitelist(stage): + from scripts.colab_remote.remote_job import failure_diagnostics + assert failure_diagnostics(ValueError('URL token stdout'),stage)=={'stage':stage,'error_type':'ValueError'} + +def test_every_measured_local_has_versioned_hosted_estimate(): + from compute_parity.hosted_estimates import MEASUREMENTS,estimate + for sha,m in MEASUREMENTS.items(): + for lane,rate in [('runninghub',.25),('comfy_cloud',.266)]: + q=estimate({'bundle_sha256':sha,'case_id':m['case_id']},lane) + assert q['amount']==round((min(m['wall_seconds']*1.5,1800) if lane=='comfy_cloud' else m['wall_seconds']*1.5)*rate,6) + assert q['estimate_version']=='20261111-r30' and q['measured_at'] and '估計,非官方報價' in q['label'] + + +def test_runninghub_http_error_with_prompt_id_is_not_rejected(bundle,tmp_path): + t=FakeTransport(bundle);old=t.request + def request(m,p,**kw): + if p=='/prompt': + error=ParityError('provider_http','safe');error.prompt_id='accepted-native' + error.diagnostics={'http_status':400,'reason_code':'prompt_outputs_failed_validation'};raise error + return old(m,p,**kw) + t.request=request;a=RunningHubNative(t,Journal(tmp_path/'j.db'));rid=oid() + r=a.submit('owner',rid,bundle,files(bundle),quote={'unit':'POINT','amount':1}) + assert r['state']=='queued' and r['remote_id']=='accepted-native' + +def test_unrelated_identified_history_does_not_deadlock_uncertain(tmp_path,monkeypatch): + j,rid=reserved(tmp_path);monkeypatch.setattr(time,'time',lambda:3600) + response={'/history':{'different':{'prompt':[0,'different',{}, {'castle_request_id':oid()}]}},'/queue':{'queue_running':[],'queue_pending':[]}} + a=RunningHubNative(NS(fingerprint='account',request=lambda m,p,**kw:response[p]),j);a.observe_point=lambda:100 + j.update('owner',rid,pre_submission_point={'at':-1,'unit':'POINT','value':100,'account':'account'}) + assert a.recover('owner',rid)['state']=='closed_no_execution_evidence' + assert j.get('owner',rid)['closure_evidence']['history_count']==1 + +def test_new_local_measurement_is_owner_and_bundle_bound(tmp_path,monkeypatch,bundle): + from compute_parity.local import LocalBaseline + from compute_parity.hosted_estimates import measurement_from_journal,estimate + j=Journal(tmp_path/'j.db');clock=[100];monkeypatch.setattr(time,'time',lambda:clock[0]) + a=LocalBaseline(NS(submit=lambda *args:{'state':'queued','downstream_id':'local-id'},status=lambda *args:{'state':'completed','downstream_id':'local-id'}),j,None) + rid=oid();a.submit('owner',rid,bundle,files(bundle),request={});clock[0]=200;a.poll('owner',rid) + m=measurement_from_journal(j.path,'owner',bundle);assert m['wall_seconds']==100 + assert estimate(bundle,'runninghub',measurement=m)['amount']==37.5 + assert measurement_from_journal(j.path,'other',bundle) is None + assert measurement_from_journal(j.path,'owner',{**bundle,'bundle_sha256':'wrong'}) is None + +def test_colab_fetches_sanitized_status_before_cleanup(tmp_path): + from colab_service import ColabService + service=object.__new__(ColabService);events=[];service.clock=lambda:100 + state={'id':oid(),'runtime_id':'lease','native_parity':True,'manifest_sha256':'a'*64,'phase':'cleanup_pending'} + diagnostic={'stage':'execute','error_type':'RuntimeError','stdout':'SECRET','url':'https://private'} + def execute(s,code): + events.append('diagnostic_get');assert 'runner.log' not in code + return {'status':{'job_id':state['id'],'manifest_sha256':state['manifest_sha256'],'diagnostics':diagnostic}} + def update(rid,**changes):state.update(changes);return dict(state) + def call(s,operation,**kw): + events.append(operation);assert s['remote_diagnostics']=={'stage':'execute','error_type':'RuntimeError'} + # Stop at the release call; no real provider, no lease exists in this test. + raise RuntimeError('test ends at cleanup boundary') + service._exec=execute;service.update=update;service._call=call + with pytest.raises(RuntimeError):service._cleanup(state) + assert events==['diagnostic_get','runtime_stop'] and 'SECRET' not in str(state) + +def test_colab_real_old_failure_does_not_claim_a100_shortage(): + from compute_parity.colab import ColabNative + data=fixture('colab-failure.json') + assert data['released'] and data['remote_phase']=='failed' and data['remote_diagnostics']=={} + assert 'allocation_unavailable' not in str(data) + + + +def test_uncertain_keeps_first_observation_and_never_forgets_drain(tmp_path,monkeypatch): + j,rid=reserved(tmp_path);now=[3600];monkeypatch.setattr(time,'time',lambda:now[0]);value=[100] + response=fixture('runninghub-absence.json') + a=RunningHubNative(NS(fingerprint='account',request=lambda m,p,**kw:response[p[1:]]),j);a.observe_point=lambda:value[0] + a.recover('owner',rid);value[0]=99;now[0]+=60;a.recover('owner',rid);value[0]=100 + # An unexplained drop cannot be erased by long polling or recovery to the same balance. + for i in range(140):now[0]+=60;a.recover('owner',rid) + evidence=j.get('owner',rid)['closure_evidence'] + assert evidence['observations'][0]['at']==3600 and evidence['unexplained_drop'] + assert len(evidence['observations'])==128 and j.get('owner',rid)['state']=='submission_uncertain' + +def test_cost_allowlist_is_independent_of_model_aliases(): + from compute_routing import _public_receipt + r=_public_receipt({'state':'completed','downstream_id':'original','actual_cost':{'unit':'credits','amount':100},'settlement_status':'settled','balance_observation':{'at':1,'unit':'credits','value':1000,'status':'observed','token':'SECRET'}}) + assert r['actual_cost']=={'unit':'credits','amount':100} and r['balance_observation']['unit']=='credits' + assert 'model_aliases' not in r and 'SECRET' not in str(r) + +def test_diagnostic_hostile_types_never_leak(): + from compute_parity.diagnostics import sanitize,response_diagnostics + from scripts.colab_remote.remote_job import sanitize_diagnostics + assert sanitize({'nodes':[{'node_id':{},'node_class':{},'error_type':[]}],'reason_code':{'token':'secret'}})=={} + assert response_diagnostics({'node_errors':{'15':{'errors':None}}})=={} + assert sanitize_diagnostics({'node_class':{},'error_code':[]})=={} + +def test_pipeline_closure_blocks_dependents_and_retry_has_new_identity(tmp_path): + from compute_pipeline import ComputePipeline + from compute_routing import ComputeRouter,ComputeAdapter + submitted=[] + def submit(owner,rid,*args):submitted.append(rid);return {'state':'submission_uncertain','downstream_id':rid} + router=ComputeRouter(tmp_path/'routing.db',{'runninghub':ComputeAdapter(inspect=lambda *a:{'eligible':True},submit=submit,status=lambda owner,rid:{'state':'closed_no_execution_evidence','downstream_id':rid})}) + pipeline=ComputePipeline(tmp_path/'pipeline.db',router_factory=lambda owner:router,artifact_resolver=lambda *a:None) + pid=oid();pipeline.create('owner',pid,{'version':1,'steps':[{'id':'run','request':{'featureId':'dance'},'placement':'runninghub'},{'id':'next','request':{'featureId':'video-replace'},'placement':'runninghub','depends_on':['run']}]}) + pipeline.tick('owner',pid);pipeline.tick('owner',pid) + result=pipeline.status('owner',pid);assert result['state']=='blocked' + assert result['steps'][0]['retry_allowed'] and result['steps'][1]['state']=='blocked' + original=result['steps'][0]['request_id'];new=pipeline.retry('owner',pid,'run') + assert new['steps'][0]['request_id']!=original and submitted==[original] + assert new['steps'][0]['attempt']==2 diff --git a/scripts/test_compute_r31.py b/scripts/test_compute_r31.py new file mode 100644 index 0000000..25c632a --- /dev/null +++ b/scripts/test_compute_r31.py @@ -0,0 +1,302 @@ +"""Offline r31 regressions: recorded boundary shapes, admission and owner closure.""" +import copy,io,json,ssl,time,uuid,urllib.error +from pathlib import Path +from types import SimpleNamespace as NS +import pytest +from test_compute_parity_p1 import bundle,files,oid,FakeTransport,no_network,seal +from compute_parity.adapters import RunningHubNative,AutoIPPublic +from compute_parity.journal import Journal +from compute_parity.contracts import ParityError,lane_description +from compute_parity.transport import Transport +from compute_parity.diagnostics import sanitize,attempt_diagnostics + +@pytest.mark.parametrize('error,kind',[(TimeoutError('PRIVATE'),'timeout'),(ConnectionError('PRIVATE'),'connection'),(ssl.SSLError('PRIVATE'),'tls'),(urllib.error.URLError(TimeoutError('PRIVATE')),'timeout')]) +def test_transport_types_are_safe(error,kind): + t=Transport('runninghub','synthetic-test-key',enabled=True) + t._opener=NS(open=lambda *a,**k:(_ for _ in ()).throw(error)) + with pytest.raises(ParityError) as caught:t.request('POST','/prompt',body={}) + d=caught.value.diagnostics + assert d['stage']=='prompt_transport' and d['transport_error_type']==kind + assert 'PRIVATE' not in str(d) and d['prompt_id_present'] is False + +@pytest.mark.parametrize('raw,kind',[(b'not json','json_decode'),(b'x'*(16*1024*1024+1),'response_size')]) +def test_decode_size_and_prompt_timeout(raw,kind): + from test_compute_r30 import Response + calls=[];response=Response(raw);response.status=200 + def open(*a,**kw):calls.append(kw['timeout']);return response + t=Transport('runninghub','synthetic-test-key',enabled=True);t._opener=NS(open=open) + with pytest.raises(ParityError) as caught:t.request('POST','/prompt',body={}) + assert calls==[300] and caught.value.diagnostics['http_status']==200 + assert caught.value.diagnostics['transport_error_type']==kind + +@pytest.mark.parametrize('body,rid',[({'data':{'taskId':'nested-task','PRIVATE':'secret'},'msg':'secret'},'nested-task'),({'prompt_id':'native','data':{'taskId':'nested'},'error':[]},'native'),({'prompt_id':'invalid id','data':{'prompt_id':'valid'}},'valid'),(['private'],None),({'data':None},None)]) +def test_rh_envelopes_preserve_id_first(bundle,tmp_path,body,rid): + t=FakeTransport(bundle);original=t.request + t.request=lambda m,p,**kw:body if p=='/prompt' else original(m,p,**kw) + a=RunningHubNative(t,Journal(tmp_path/'j.db'));result=a.submit('owner',oid(),bundle,files(bundle),quote={'unit':'POINT','amount':10}) + assert result.get('remote_id')==rid + assert result['diagnostics']['stage']==('prompt_response' if rid else 'id_parse') + assert result['diagnostics']['prompt_id_present']==bool(rid) + assert 'secret' not in str(result['diagnostics']) and 'secret' not in json.dumps(result['diagnostics'].get('unknown_keys',{})) # r32 allows safe key names, never values + assert result['state']==('queued' if rid else 'submission_uncertain') + +@pytest.mark.parametrize('path,stage,state',[('/upload/image','upload','rejected'),('/prompt','prompt_transport','submission_uncertain')]) +def test_upload_distinct_from_ambiguous_prompt(bundle,tmp_path,path,stage,state): + t=FakeTransport(bundle);original=t.request + def request(m,p,**kw): + if p==path:raise TimeoutError('private') + return original(m,p,**kw) + t.request=request;a=RunningHubNative(t,Journal(tmp_path/'j.db')) + result=a.submit('owner',oid(),bundle,files(bundle),quote={'unit':'POINT','amount':10}) + assert result['state']==state and result['diagnostics']['stage']==stage + assert result['diagnostics']['transport_error_type']=='timeout' + +def failed(j,case='voice-speak.anime.chatgpt',kind='execution',root='native_runtime_failed',lane='colab'): + rid=oid();j.reserve('owner',rid,lane,'account',case,rid,{'unit':'CU' if lane=='colab' else 'credits','amount':10}) + return j.update('owner',rid,state='failed',root_cause=root,failure_kind=kind) + +def test_epoch_preserves_attempt_cap_and_history(tmp_path): + j=Journal(tmp_path/'j.db');failed(j);failed(j) + with pytest.raises(ParityError,match='重新驗證'):j.check_admission('owner','colab','voice-speak.anime.claude') + with pytest.raises(ParityError):j.revalidate('owner','colab','20261111-r31') + first=j.revalidate('owner','colab','20261111-r31',authorized=True) + assert j.revalidate('owner','colab','20261111-r31',authorized=True)==first + j.check_admission('owner','colab','voice-speak.anime.chatgpt');failed(j) + with pytest.raises(ParityError) as e:j.check_admission('owner','colab','voice-speak.anime.chatgpt') + assert e.value.code=='attempt_cap' and j.ledger('owner')['colab']['attempts']==3 + assert j.ledger('someone-else')=={} + +def test_contract_scope_and_quality_never_stop(tmp_path): + j=Journal(tmp_path/'j.db') + failed(j,'dance.anime.chatgpt','contract','duration_short','autoip');failed(j,'video-replace.anime.claude','contract','duration_short','autoip') + j.check_admission('owner','autoip','voice-speak.anime.chatgpt') + with pytest.raises(ParityError) as e:j.check_admission('owner','autoip','dance.realistic.example-a') + assert e.value.code=='lane_stopped' + failed(j,'voice-speak.anime.chatgpt','quality','speaker_gate','autoip');failed(j,'voice-speak.anime.claude','quality','speaker_gate','autoip') + j.check_admission('owner','autoip','voice-speak.realistic.example-a') + +def test_autoip_upper_bound_real_25_to_50(tmp_path): + # P1g four voice tasks each quoted 25, actually charged 50. Exact safe pricing fields. + observed=json.loads((Path(__file__).parent/'fixtures/r31/autoip-voice-25-to-50.json').read_text()) + evidence={'pricing':observed['pricing'],'balance':{'data':{'credits':1000}}} + q=AutoIPPublic.normalize_quote(evidence,'voice_clone') + assert q['amount']==q['base_amount']==50 and q['off_peak_amount']==25 and q['upper_bound'] + j=Journal(tmp_path/'j.db');rid=oid() + j.reserve('owner',rid,'autoip','account','voice-speak.anime.chatgpt','id',{'unit':'credits','amount':25}) + result=j.update('owner',rid,state='completed',actual_cost={'unit':'credits','amount':50}) + assert result['actual_minus_quote']==25 and result['cost']['amount']==25 + +def test_autoip_voxcpm_rejected_before_quote(bundle,tmp_path): + t=FakeTransport(bundle);bundle['feature']='voxcpm-tts';a=AutoIPPublic(t,Journal(tmp_path/'j.db')) + assert lane_description('voxcpm-tts','autoip')['recipe_mode']=='impossible' + with pytest.raises(ParityError) as e:a.quote(bundle,voice_consent=True) + assert e.value.code=='voice_node_contract_required' and not t.calls + +def test_quality_survives_router_and_local(tmp_path): + from quality_rejection import QualityRejected,from_error + from compute_parity.local import LocalBaseline + from compute_routing import _public_receipt + diagnostic={'stage':'speaker_gate','best_similarity':0.819,'threshold':0.820,'attempts':2} + assert from_error(str(QualityRejected({**diagnostic,'private':'never'})))==diagnostic + j=Journal(tmp_path/'j.db');rid=oid();j.reserve('owner',rid,'local','account','voxcpm-tts.shared.custom-english','identity',{'unit':'local','amount':0}) + receipt={'state':'quality_rejected','downstream_id':'run_test','diagnostics':diagnostic} + result=LocalBaseline(None,j,None)._record('owner',rid,_public_receipt(receipt)) + assert result['state']=='quality_rejected' and result['diagnostics']==diagnostic + assert j.get('owner',rid)['failure_kind']=='quality' + +def test_mapping_rejects_changed_graph_and_inputs(bundle): + from compute_parity.measurement_mapping import link + target=copy.deepcopy(bundle);target['runner_sources']={};seal(target) + assert link(bundle,target)['source_bundle']==bundle['bundle_sha256'] + target['graph']['1']['inputs']['changed']='value';seal(target) + with pytest.raises(ValueError):link(bundle,target) + +def product(tmp_path,bundle): + from compute_parity.product import ProductRuntime + p=object.__new__(ProductRuntime);p.journal=Journal(tmp_path/'j.db') + class Materials: + def bundle(self,*args):return bundle + def __call__(self,*args):return bundle,files(bundle) + p.materials=Materials();p.voice_consent=lambda *a:True + p.evidence=lambda *a:{'quote':{'unit':'CU','amount':15},'account_id':'account'} + p.web=NS(owner='owner');return p + +def test_product_preview_and_submit_known_lock_no_io(tmp_path,bundle): + from compute_routing import ComputeRejected + p=product(tmp_path,bundle);failed(p.journal);failed(p.journal) + p.evidence=lambda *a:pytest.fail('Locked lane must not obtain provider evidence') + p.adapter=lambda *a:pytest.fail('Locked lane must not acquire adapter') + assert p.inspect('owner','colab',{}, {})['reasons']==['lane_stopped'] + with pytest.raises(ComputeRejected) as e:p.submit('owner','colab',oid(),{}, {}) + assert e.value.code=='lane_stopped' + assert p.journal.ledger('owner')['colab']['attempts']==2 + +@pytest.mark.parametrize('reserved',[False,True]) +def test_product_reserve_race_rejected_only_before_dispatch(tmp_path,bundle,reserved): + from compute_routing import ComputeRejected + p=product(tmp_path,bundle);rid=oid() + def submit(*a,**kw): + if reserved:p.journal.reserve('owner',rid,'colab','account',bundle['case_id'],'i',{'unit':'CU','amount':15}) + raise ParityError('lane_stopped','safe') + p.adapter=lambda *a:NS(submit=submit) + with pytest.raises(ParityError if reserved else ComputeRejected):p.submit('owner','colab',rid,{}, {}) + +@pytest.fixture +def legacy(tmp_path,monkeypatch): + from compute_routing import ComputeRouter,ComputeAdapter + from compute_parity import local_closure + clock=[10000.];monkeypatch.setattr(local_closure.time,'time',lambda:clock[0]) + rid=oid();did=oid();owner='owner' + router=ComputeRouter(tmp_path/'routing.db',{'local':ComputeAdapter(lambda *a:{'eligible':True},lambda *a:{'state':'submission_uncertain','downstream_id':did})},clock=lambda:0) + router.submit(owner,rid,{'featureId':'text2img'},'local') + states={'queue':{'queue_running':[],'queue_pending':[]},'history':{},'durable':None,'direct':None,'indexed_owner':owner} + server=NS(DEFAULT_COMFY='http://127.0.0.1:8188',load_job_index=lambda:{did:{'email':states['indexed_owner']}},user_can_access_job=lambda *a:True, + local_job_snapshot=lambda:[],request_json=lambda path:states['queue'] if path=='/queue' else states['history']) + web=NS(router=router,owner=owner,user={},s=server,_durable_local_result=lambda *a:states['durable'],_direct_local_result=lambda *a:states['direct']) + return web,rid,did,clock,states + +def test_local_unknown_closure_two_observations_idempotent_and_late(legacy): + from compute_parity.local_closure import close,reconcile,STATE + from compute_routing import ComputeRoutingError + web,rid,did,clock,s=legacy;body={'authorize':True,'downstream_id':did} + first=close(web,rid,body);assert first['state']=='submission_uncertain' + clock[0]+=59;assert close(web,rid,body)['state']=='submission_uncertain' + clock[0]+=1;closed=close(web,rid,body);assert closed['state']==STATE and closed['execution_outcome']=='unknown' + assert close(web,rid,body)==closed and len(closed['closure_evidence']['observations'])==2 + web.status_local=lambda *a:{'state':'completed','downstream_id':did,'artifacts':[{'url':'/api/output/owned'}]} + result=reconcile(web,rid,body) + assert result['state']==STATE and result['late_reconciliation']['receipt']['downstream_id']==did + with pytest.raises(ComputeRoutingError):reconcile(web,rid,{**body,'downstream_id':oid()}) + assert web.router.submit('owner',rid,{'featureId':'text2img'},'local')['state']==STATE + +@pytest.mark.parametrize('damage',['owner','downstream','queue','history','durable','sidecar','malformed_queue','young','unauthorized']) +def test_local_unknown_refuses_incomplete_or_conflicting_evidence(legacy,damage): + from compute_parity.local_closure import close + from compute_routing import ComputeRoutingError + web,rid,did,clock,s=legacy;body={'authorize':True,'downstream_id':did} + if damage=='owner':web.owner='intruder' + if damage=='downstream':body['downstream_id']=oid() + if damage=='queue':s['queue']['queue_running']=[[0,did]] + if damage=='history':s['history']={did:{}} + if damage=='durable':s['durable']={'state':'completed'} + if damage=='sidecar':s['direct']={'state':'completed'} + if damage=='malformed_queue':s['queue']={} + if damage=='young':clock[0]=30 + if damage=='unauthorized':body['authorize']=False + with pytest.raises((ComputeRoutingError,PermissionError)):close(web,rid,body) + assert web.router.status('owner',rid)['state']=='submission_uncertain' + +def test_late_measurement_via_verified_runner_mapping(tmp_path,bundle,monkeypatch): + from compute_parity import measurement_mapping as mapping + from compute_parity.hosted_estimates import measurement_from_journal + old=copy.deepcopy(bundle);new=copy.deepcopy(bundle);new['runner_sources']={'worker.py':{'bytes':1,'sha256':'a'*64}};seal(new) + entry=mapping.link(old,new);monkeypatch.setattr(mapping,'sources',lambda b:{old['bundle_sha256']:entry} if b==new else {}) + j=Journal(tmp_path/'j.db');rid=oid();j.reserve('owner',rid,'local','account',bundle['case_id'],'i',{'unit':'local','amount':0}) + assert measurement_from_journal(j.path,'owner',new) is None + j.update('owner',rid,state='completed',bundle_sha256=old['bundle_sha256'],completed_at=time.time(),wall_seconds=100.0) + m=measurement_from_journal(j.path,'owner',new) + assert m['request_id']==rid and m['mapping_version']==mapping.VERSION and m['source_bundle']==old['bundle_sha256'] + assert measurement_from_journal(j.path,'intruder',new) is None + + +def test_http_nested_id_and_shape_no_context(): + t=Transport('runninghub','synthetic-test-key',enabled=True) + body={'data':{'taskId':'known'},'private':'never','msg':'secret'} + def open(*a,**k):raise urllib.error.HTTPError('https://private.invalid/key',502,'private',{},io.BytesIO(json.dumps(body).encode())) + t._opener=NS(open=open) + with pytest.raises(ParityError) as e:t.request('POST','/prompt',body={}) + assert e.value.prompt_id=='known' and e.value.__context__ is None + assert e.value.diagnostics['http_status']==502 and e.value.diagnostics['transport_error_type']=='http' + assert e.value.diagnostics['response_keys']==['data','msg'] + +def test_list_api_never_recovers_historical_receipts(monkeypatch): + import server,compute_web + saved=[];rid=oid() + router=NS(list_jobs=lambda *a,**k:[{'request_id':rid,'lane':'runninghub','state':'submission_uncertain'}], + status=lambda *a,**k:pytest.fail('Listing must not recover')) + monkeypatch.setattr(compute_web,'ComputeWeb',lambda *a:NS(owner='owner',user={},router=router)) + handler=NS(path='/api/compute/jobs',send_json=lambda data,*a,**kw:saved.append(data)) + server.Handler.api_compute(handler,'/api/compute/jobs',False) + assert saved[0]['jobs'][0]['request_id']==rid + +def test_quality_flows_from_owned_orchestrator(monkeypatch): + from compute_web import ComputeWeb + from quality_rejection import QualityRejected + diagnostic={'stage':'speaker_gate','best_similarity':.819,'threshold':.82,'attempts':2} + w=object.__new__(ComputeWeb) + w._owned_orchestrator_run=lambda task:{'status':'failed','tasks':[{'error':str(QualityRejected(diagnostic))}]} + result=w._orchestrator_local_result('run_test') + assert result['state']=='quality_rejected' and result['diagnostics']==diagnostic + +def test_completed_output_contract_failure_stops_only_video(tmp_path,bundle): + p=product(tmp_path,bundle) + for case in ('dance.anime.chatgpt','video-replace.anime.claude'): + rid=oid();p.journal.reserve('owner',rid,'autoip','account',case,rid,{'amount':50,'unit':'credits'}) + job=p.journal.update('owner',rid,state='completed',artifacts=[{'index':0}]) + p.artifact=lambda *a:(_ for _ in ()).throw(ParityError('duration_short','safe')) + assert p.receipt(job)['state']=='failed' + p.journal.check_admission('owner','autoip','voice-speak.anime.chatgpt') + with pytest.raises(ParityError) as e:p.journal.check_admission('owner','autoip','dance.realistic.example-b') + assert e.value.code=='lane_stopped' + +def test_revalidation_http_requires_explicit_owner_authorization(): + from compute_parity.http import handle + from compute_routing import ComputeRoutingError + for body in ({'lane':'colab'},{'lane':'colab','authorize':False},{'lane':'colab','authorize':True,'owner':'other'}): + with pytest.raises(ComputeRoutingError):handle(NS(),NS(),['parity','revalidate'],True,body) + + +def test_two_unknown_execution_closures_stop_until_reviewed_fix(tmp_path): + j=Journal(tmp_path/'j.db') + for _ in range(2): + rid=oid();j.reserve('owner',rid,'runninghub','account','dance.anime.chatgpt',rid,{'unit':'POINT','amount':50}) + j.update('owner',rid,state='closed_no_execution_evidence',root_cause='no_execution_evidence') + with pytest.raises(ParityError) as e:j.check_admission('owner','runninghub','dance.anime.claude') + assert e.value.code=='lane_stopped' + j.revalidate('owner','runninghub','20261111-r31',authorized=True) + j.check_admission('owner','runninghub','dance.anime.chatgpt') + assert j.ledger('owner')['runninghub']['attempts']==2 + +def test_voxcpm_child_quality_diagnostic_keeps_threshold(tmp_path,monkeypatch): + from orchestrator import tasks + from quality_rejection import QualityRejected + work=tmp_path/'work';(work/'tmp').mkdir(parents=True) + diagnostic={'stage':'speaker_gate','best_similarity':.819,'threshold':.82,'attempts':2} + monkeypatch.setattr(tasks,'_trusted_existing_path',lambda *a,**k:tmp_path) + monkeypatch.setattr(tasks,'_safe_output_path',lambda p,*a:Path(p)) + monkeypatch.setattr(tasks,'gpu_queue_cmd',lambda args,payload:args) + seen=[] + def child(args,**kw): + seen.extend(args) + side=Path(args[args.index('--sidecar')+1]);Path(str(side)+'.quality.json').write_text(str(QualityRejected(diagnostic))) + raise tasks.subprocess.CalledProcessError(1,args) + monkeypatch.setattr(tasks.subprocess,'check_call',child) + with pytest.raises(QualityRejected) as e: + tasks.run_castle_voxcpm_tts({'output_path':str(tmp_path/'result.wav'),'sidecar_path':str(tmp_path/'result.json'),'speaker_gate':True,'speaker_threshold':.82,'speaker_max_attempts':2},work,work/'cancel') + assert e.value.diagnostics==diagnostic + assert seen[seen.index('--speaker-threshold')+1]=='0.82' and seen[seen.index('--speaker-max-attempts')+1]=='2' + assert not list(work.rglob('*.quality.json')) + +def test_task_wrapper_saves_only_structured_quality(tmp_path,monkeypatch): + from orchestrator import task_wrapper as wrapper + from quality_rejection import QualityRejected,from_error + diagnostic={'stage':'speaker_gate','best_similarity':.819,'threshold':.82,'attempts':2} + work=tmp_path/'work';work.mkdir();payload=tmp_path/'input.json';payload.write_text('{}');sentinel=work/'done.json' + monkeypatch.setattr(wrapper,'run_task',lambda *a:(_ for _ in ()).throw(QualityRejected(diagnostic))) + monkeypatch.setattr(wrapper,'install_signal_handlers',lambda *a:None) + monkeypatch.setattr(wrapper.sys,'argv',['wrapper','--task-id','task_test','--task-type','castle.voxcpm_tts','--input-json',str(payload),'--work-dir',str(work),'--marker','test','--sentinel',str(sentinel)]) + assert wrapper.main()==1 + result=json.loads(sentinel.read_text()) + assert result['diagnostics']==diagnostic and from_error(result['error'])==diagnostic + assert 'traceback' not in result and result['outputs']==[] + + + +def test_public_predispatch_record_uses_generic_journal(tmp_path): + from compute_parity.revalidation import revalidate + calls=[] + expected={'epoch':'synthetic'} + journal=NS(revalidate=lambda *args,**kwargs: calls.append((args,kwargs)) or expected) + web=NS(owner='owner@example.invalid',parity=NS(journal=journal)) + assert revalidate(web,'colab') == expected + assert calls == [(('owner@example.invalid','colab','20261111-r31'),{'authorized':True})] diff --git a/scripts/test_compute_r32.py b/scripts/test_compute_r32.py new file mode 100644 index 0000000..f696899 --- /dev/null +++ b/scripts/test_compute_r32.py @@ -0,0 +1,220 @@ +"""Offline r32 regressions: no provider, GPU or live state writes.""" +import copy,json,sqlite3,subprocess,time +from pathlib import Path +from types import SimpleNamespace as NS +import pytest +from test_compute_parity_p1 import bundle,files,oid,FakeTransport +from compute_parity.contracts import ParityError +from compute_parity.journal import Journal +from compute_parity.diagnostics import attempt_diagnostics,sanitize,prompt_identity +from compute_parity.provisioning import provisioning_only +from compute_routing import _public_receipt + +@pytest.mark.parametrize('body,kind,empty',[(None,'null',True),({},'object',True),([],'array',True),('','string',True),('private','string',False),(0,'number',False),(False,'bool',False),([1],'array',False),({'data':[]},'object',False)]) +def test_envelope_types_through_router(body,kind,empty): + d=attempt_diagnostics('id_parse',body,status=200) + result=_public_receipt({'state':'submission_uncertain','diagnostics':d})['diagnostics'] + assert result==sanitize(d) + assert result['response_kind']==kind and result['response_empty'] is empty + assert result['data_kind']==('array' if isinstance(body,dict) and 'data' in body else 'null') + assert 'private' not in str(result) + +@pytest.mark.parametrize('length,bucket',[(0,'0'),(1,'1-64'),(64,'1-64'),(65,'65-1024'),(1024,'65-1024'),(1025,'1025-16384'),(16384,'1025-16384'),(16385,'16385+')]) +def test_string_length_buckets_only(length,bucket): + d=attempt_diagnostics('id_parse','!'*length,status=200) + assert d['response_length_bucket']==bucket and '!' not in str(d) + +def test_unknown_names_are_sorted_bounded_and_values_never_stored(): + top={f'field_{i:02}':'SECRET-VALUE' for i in range(20)} + top.update({'with space':'SECRET-VALUE','a'*42:'SECRET-VALUE','中文字':'SECRET-VALUE','data':{'newField':{'nestedSecret':'SECRET-VALUE'},'9bad':'SECRET-VALUE'},'code':0}) + d=sanitize(attempt_diagnostics('id_parse',top,status=200)) + assert d['unknown_keys']=={'top_level':[f'field_{i:02}' for i in range(16)],'data_level':['newField']} + assert d['unknown_key_count']=={'top_level':23,'data_level':2} + assert not any(s in json.dumps(d,ensure_ascii=False) for s in ['SECRET-VALUE','with space','中文字','nestedSecret','9bad','a'*42]) + assert prompt_identity({'id':'unproven','data':{'unknownId':'unproven'}}) is None + assert sanitize({'unknown_keys':{'top_level':[{},'bad-name','ok','ok']},'response_length_bucket':[]})=={'unknown_keys':{'top_level':['ok']}} + +@pytest.mark.parametrize('body',[None,[],False,0,'opaque',{'newEnvelope':{'id':'unproven'}}]) +def test_unknown_envelope_never_reposts(bundle,tmp_path,body): + from compute_parity.adapters import RunningHubNative + t=FakeTransport(bundle);original=t.request;posts=[] + def request(method,path,**kw): + if path=='/prompt':posts.append(path);return body + return original(method,path,**kw) + t.request=request;t.last_diagnostics={'http_status':200} + j=Journal(tmp_path/'j.db');a=RunningHubNative(t,j);rid=oid() + first=a.submit('owner',rid,bundle,files(bundle),quote={'unit':'POINT','amount':10}) + assert first['state']=='submission_uncertain' and first['diagnostics']['response_kind'] + a.submit('owner',rid,bundle,files(bundle),quote={'unit':'POINT','amount':10}) + assert posts==['/prompt'] and j.get('owner',rid)['state']=='submission_uncertain' + +@pytest.mark.parametrize('code',['allocation_unavailable','allocation_rejected','allocation_uncertain']) +@pytest.mark.parametrize('released',[False,True]) +def test_provisioning_survives_every_sanitizer(tmp_path,code,released): + from compute_parity.colab import ColabNative + from scripts.colab_remote.remote_job import sanitize_diagnostics + j=Journal(tmp_path/'j.db');rid=oid();j.reserve('owner',rid,'colab','account','dance.anime.chatgpt',rid,{'unit':'CU','amount':10}) + remote={'id':rid,'phase':'cancelled' if released else 'allocation_uncertain','allocation_code':code, + 'allocation_diagnostics':{'http_status':503,'private':'NEVER'},'runtime_id':None,'released':released,'units_observed':0} + result=ColabNative(None,j)._record('owner',rid,remote) + expected={'stage':'provisioning','error_code':code,'http_status':503} + assert result['diagnostics']==expected==sanitize_diagnostics(result['diagnostics']) + from compute_parity.runtime import Runtime + assert _public_receipt(Runtime.receipt(result))['diagnostics']==expected + assert result['state']==('cancelled' if released else 'submission_uncertain') + +def test_uncertain_stays_uncertain_during_cleanup(tmp_path): + from compute_parity.colab import ColabNative + j=Journal(tmp_path/'j.db');rid=oid();j.reserve('owner',rid,'colab','account','case',rid,{'unit':'CU','amount':10}) + remote={'id':rid,'phase':'stopping','allocation_code':'allocation_uncertain','runtime_id':None,'released':False} + assert ColabNative(None,j)._record('owner',rid,remote)['state']=='submission_uncertain' + +def test_assigned_runtime_retains_execution_diagnostic(tmp_path): + from compute_parity.colab import ColabNative + j=Journal(tmp_path/'j.db');rid=oid();j.reserve('owner',rid,'colab','account','case',rid,{'unit':'CU','amount':10}) + remote={'id':rid,'phase':'running','allocation_code':'allocation_uncertain','runtime_id':'assigned','diagnostics':{'stage':'execute','error_type':'RuntimeError'}} + result=ColabNative(None,j)._record('owner',rid,remote) + assert result['state']=='running' and result['diagnostics']['stage']=='execute' + +def test_503_is_still_ambiguous(): + from scripts.colab_allocation_diagnostics import classify + assert classify(NS(status_code=503))[0]=='allocation_uncertain' + assert classify(NS(status_code=503,reason_code='NO_ASSIGNMENT'))[0]=='allocation_unavailable' + +@pytest.fixture +def evidence(tmp_path): + path=tmp_path/'colab/state.sqlite3';path.parent.mkdir() + with sqlite3.connect(path) as db:db.execute('CREATE TABLE jobs(id TEXT,owner TEXT,account_id TEXT,state TEXT)') + return Journal(tmp_path/'compute-parity/journal.sqlite3'),path + +def provision(evidence,at,case='dance.anime.chatgpt',**changes): + j,path=evidence;rid=oid() + # Seed durable historical evidence: exercise admission separately, never edit live rows. + job={'owner':'owner','request_id':rid,'lane':'colab','account':'account','case_id':case,'identity':rid, + 'state':'failed','cost':{'unit':'CU','amount':10},'reserved_amount':10,'actual_cost':{'unit':'CU','amount':0}, + 'created_at':at,'artifacts':[],'remote_id':rid,'root_cause':'native_runtime_failed'} + state={'id':rid,'account_id':'account','phase':'failed','released':True,'units_observed':0,'allocation_attempted_at':at} + state.update(changes) + with sqlite3.connect(path) as db:db.execute('INSERT INTO jobs VALUES (?,?,?,?)',(rid,'owner','account',json.dumps(state))) + with j.db() as db:db.execute('INSERT INTO jobs VALUES (?,?,?,?,?,?,?,?)',('owner',rid,'colab','account',case,0,'failed',json.dumps(job))) + return job,state + +@pytest.mark.parametrize('damage',[{'runtime_id':'ever-assigned'},{'runtime_ever_assigned':True},{'released':False},{'units_observed':1},{'units_observed':False},{'remote_phase':'execute'},{'upload_index':1},{'artifacts':[{}]},{'phase':'allocation_uncertain'}]) +def test_exemption_requires_complete_evidence(evidence,damage): + job,state=provision(evidence,time.time()-1000,**damage) + assert not provisioning_only(job,('account',state)) + +def test_owner_account_cost_and_request_binding(evidence): + job,state=provision(evidence,time.time()-1000) + assert provisioning_only(job,('account',state)) + for key,value in [('actual_cost',None),('actual_cost',{'unit':'CU','amount':False}),('remote_id','other'),('lane','runninghub'),('account','other')]: + assert not provisioning_only({**job,key:value},('account',state)) + j,path=evidence + with sqlite3.connect(path) as db:db.execute('UPDATE jobs SET owner="other"') + from compute_parity.provisioning import classify + assert not classify([job],path,'owner') + +def test_legacy_exemption_cap_stop_and_no_rewrite(evidence): + j,path=evidence + for i in range(3):provision(evidence,time.time()-3000-i*700) + before=j.path.read_bytes();colab_before=path.read_bytes() + j.check_admission('owner','colab','dance.anime.chatgpt') + assert j.path.read_bytes()==before and path.read_bytes()==colab_before + assert j.ledger('owner')['colab']['attempts']==3 + # Execution failures in another case still stop the entire lane. + for i in range(2):provision(evidence,time.time()-1500-i*700,case='dance.anime.claude',runtime_id='assigned') + with pytest.raises(ParityError) as e:j.check_admission('owner','colab','voice-speak.anime.chatgpt') + assert e.value.code=='lane_stopped' + +@pytest.mark.parametrize('seconds,blocked',[(599,True),(600,False),(601,False)]) +def test_ten_minute_boundary_across_cases_and_epochs(evidence,monkeypatch,seconds,blocked): + j,path=evidence;monkeypatch.setattr('compute_parity.journal.time.time',lambda:100000) + provision(evidence,100000-seconds) + if blocked: + with pytest.raises(ParityError) as e:j.check_admission('owner','colab','voice-speak.anime.chatgpt') + assert e.value.code=='provisioning_retry_wait' + else:j.check_admission('owner','colab','voice-speak.anime.chatgpt') + +@pytest.mark.parametrize('oldest,blocked',[(86399,True),(86400,False),(86401,False)]) +def test_rolling_six_across_cases(evidence,monkeypatch,oldest,blocked): + j,path=evidence;monkeypatch.setattr('compute_parity.journal.time.time',lambda:100000) + for i in range(5):provision(evidence,100000-1000-i*700,case=f'case.{i}') + provision(evidence,100000-oldest,case='old') + if blocked: + with pytest.raises(ParityError) as e:j.reserve('owner',oid(),'colab','rotated','new','new',{'unit':'CU','amount':10}) + assert e.value.code=='provisioning_retry_cap' + else:j.reserve('owner',oid(),'colab','rotated','new','new',{'unit':'CU','amount':10}) + +def test_unreleased_and_missing_evidence_count_toward_cap(evidence): + j,path=evidence + for i in range(3):provision(evidence,time.time()-3000-i*700,released=False) + with pytest.raises(ParityError) as e:j.check_admission('owner','colab','dance.anime.chatgpt') + assert e.value.code=='attempt_cap' + path.unlink() + with pytest.raises(ParityError) as e:j.check_admission('owner','colab','dance.anime.chatgpt') + assert e.value.code=='attempt_cap' + +def test_runninghub_closure_counts_cap(evidence): + j,path=evidence + for i in range(3): + rid=oid();j.reserve('owner',rid,'runninghub','account','case',rid,{'unit':'POINT','amount':10}) + j.update('owner',rid,state='closed_no_execution_evidence',root_cause=f'cause{i}') + with pytest.raises(ParityError) as e:j.check_admission('owner','runninghub','case') + assert e.value.code=='attempt_cap' + +def test_poll_scope_node_regressions(): + subprocess.run(['node',str(Path(__file__).with_name('test_compute_r32_poll.cjs'))],check=True) + +def test_allocation_time_not_earlier_reservation_controls_spacing(evidence,monkeypatch): + j,path=evidence;monkeypatch.setattr('compute_parity.journal.time.time',lambda:100000) + provision(evidence,98000,allocation_attempted_at=99500) + with pytest.raises(ParityError) as e:j.check_admission('owner','colab','new') + assert e.value.code=='provisioning_retry_wait' + +def test_native_allocation_cannot_auto_retry_outside_admission(evidence): + from colab_service import ColabService,BridgeError,ColabError + j,path=evidence;job,state=provision(evidence,time.time()-1000) + service=object.__new__(ColabService);service.root=path.parent;service.clock=lambda:100000 + service._db_local=__import__('threading').local();service._db_strict=True;service.nested_db_events=0;service.nested_db_sites=set() + state=service.update(job['request_id'],phase='queued',native_parity=True,deadline_epoch=101000, + gpu='A100',allocation_id=oid(),uploads=['pinned'],watchdog_sha256='pinned') + calls=[] + def call(state,op,**kw): + calls.append(op);raise BridgeError('allocation_unavailable',False,{'http_status':503,'reason_code':'NO_ASSIGNMENT'}) + service._call=call;service.tick(state);service.tick(state) + saved=service.job('owner',job['request_id']) + assert calls==['runtime_allocate'] and saved['phase']=='failed' and saved['released'] is True + service.update(job['request_id'],runtime_id='assigned') + with pytest.raises(ColabError):service.update(job['request_id'],runtime_id=None) + assert service.job('owner',job['request_id'])['runtime_ever_assigned'] is True + +def test_admission_reservation_serializes_sixth_slot(evidence,monkeypatch): + from concurrent.futures import ThreadPoolExecutor + j,path=evidence;monkeypatch.setattr('compute_parity.journal.time.time',lambda:100000) + for i in range(5):provision(evidence,98000-i*700,case=f'case.{i}') + def reserve(i): + try:j.reserve('owner',oid(),'colab',f'account{i}',f'new{i}',str(i),{'unit':'CU','amount':10});return 'accepted' + except ParityError as e:return e.code + with ThreadPoolExecutor(max_workers=2) as pool:results=list(pool.map(reserve,range(2))) + assert sorted(results)==['accepted','provisioning_retry_cap'] + + +def test_legacy_multiple_allocations_consume_each_retry_slot(evidence,monkeypatch): + j,path=evidence;monkeypatch.setattr('compute_parity.journal.time.time',lambda:100000) + for i in range(3):provision(evidence,98000-i*700,case=f'case.{i}',allocation_attempts=2) + with pytest.raises(ParityError) as e:j.check_admission('owner','colab','new') + assert e.value.code=='provisioning_retry_cap' + + +def test_cancelled_before_assignment_still_qualifies(evidence): + job,state=provision(evidence,time.time()-1000,allocation_attempted_at=None) + assert provisioning_only(job,('account',state)) + +def test_missing_allocation_code_preserves_ambiguity_through_cleanup(tmp_path): + from compute_parity.colab import ColabNative + j=Journal(tmp_path/'j.db');rid=oid();j.reserve('owner',rid,'colab','account','case',rid,{'unit':'CU','amount':10}) + adapter=ColabNative(None,j) + for phase in ('allocation_uncertain','cleanup_pending'): + result=adapter._record('owner',rid,{'id':rid,'phase':phase,'released':False,'runtime_id':None}) + assert result['state']=='submission_uncertain' + assert result['diagnostics']=={'stage':'provisioning','error_code':'allocation_uncertain'} diff --git a/scripts/test_compute_r32_poll.cjs b/scripts/test_compute_r32_poll.cjs new file mode 100644 index 0000000..c126c7b --- /dev/null +++ b/scripts/test_compute_r32_poll.cjs @@ -0,0 +1,33 @@ +// Run the real function body in an isolated browser-state harness; no HTTP. +const fs=require('fs'),path=require('path'),assert=require('assert'); +const source=fs.readFileSync(path.join(__dirname,'../webui/static/compute-placement.js'),'utf8'); +const refresh=source.slice(source.indexOf(' async function refreshJobs(){'),source.indexOf(' async function cancel(id){')); +const manual=source.slice(source.indexOf(' async function refreshOne(id){'),source.indexOf(' async function refreshJobs(){')); +const AsyncFunction=Object.getPrototypeOf(async function(){}).constructor; +(async()=>{ + for(const fallback of [false,true]) { + const run=new AsyncFunction('assert','fallback',` + const id='11111111-1111-4111-8111-111111111111', historical='22222222-2222-4222-8222-222222222222'; + const calls=[],jobs=new Map(),currentJobs=new Map([[id,{lane:'colab',caseId:'dance.anime.chatgpt'}]]); + let selected='dance.anime.chatgpt',pending={id},nextCursor=null,olderPagesLoaded=false; + const placement={value:'colab'},parity={selected:()=>({parity_case_id:selected})}; + const terminal=new Set(['completed']),live=()=>true,cursor=x=>x,receipt=x=>x,renderJobs=()=>{},jobNotice={}; + const job={request_id:id,state:'submission_uncertain'}; + const accept=value=>{if(value?.request_id)jobs.set(value.request_id,value);}; + const api=async url=>{calls.push(url);if(url==='/api/compute/jobs')return {jobs:[{request_id:historical,state:'submission_uncertain'},...(fallback?[]:[job])]};return job;}; + ${refresh}\n${manual} + const gets=()=>calls.filter(u=>u.includes('/jobs/')); + await refreshJobs();assert.deepEqual(gets(),['/api/compute/jobs/'+id]); + if(fallback)jobs.delete(id); + calls.length=0;selected='dance.anime.claude';await refreshJobs();assert.deepEqual(gets(),[]); + calls.length=0;selected='dance.anime.chatgpt';placement.value='local';await refreshJobs();assert.deepEqual(gets(),[]); + calls.length=0;placement.value='colab';await refreshJobs();assert.deepEqual(gets(),['/api/compute/jobs/'+id]); + assert.equal(pending.id,id);assert(!calls.some(u=>u.endsWith(historical))); + calls.length=0;selected='dance.anime.claude';await refreshOne(id);assert.deepEqual(gets(),['/api/compute/jobs/'+id]); + calls.length=0;await refreshOne(historical);assert.deepEqual(gets(),['/api/compute/jobs/'+historical]); + assert.equal(pending.id,id); + `); + await run(assert,fallback); + } + console.log('I1 active and pending fallback: scope, resume, historical and manual passed'); +})().catch(error=>{console.error(error);process.exit(1);}); diff --git a/scripts/test_compute_r33.py b/scripts/test_compute_r33.py new file mode 100644 index 0000000..6cc1f16 --- /dev/null +++ b/scripts/test_compute_r33.py @@ -0,0 +1,195 @@ +"""Offline boundary and lifecycle regressions; every temp is disk-backed.""" +import contextlib,hashlib,json,sqlite3,uuid +from pathlib import Path +from types import SimpleNamespace as NS +import pytest +from test_compute_parity_p1 import bundle,files,oid,FakeTransport +from compute_parity.diagnostics import attempt_diagnostics +from compute_parity.journal import Journal +from compute_parity.runtime import Runtime +from compute_routing import _public_receipt +from colab_service import ColabService,BridgeError +from scripts.colab_upload_diagnostics import classify,sanitize + +@pytest.mark.parametrize('body,code',[({},'empty_response_object'),([], 'missing_prompt_id'),(None,'missing_prompt_id'),({'id':'not-a-contract'},'missing_prompt_id'),({'clientId':'not-a-job'},'missing_prompt_id')]) +def test_runninghub_diagnostics_and_single_post(bundle,tmp_path,body,code): + from compute_parity.adapters import RunningHubNative + t=FakeTransport(bundle);original=t.request;posts=[] + def request(m,p,**kw): + if p=='/prompt':posts.append(kw['body']);return body + return original(m,p,**kw) + t.request=request;t.last_diagnostics={'http_status':200} + j=Journal(tmp_path/'journal.db');a=RunningHubNative(t,j);rid=oid() + result=a.submit('owner',rid,bundle,files(bundle),quote={'unit':'POINT','amount':10}) + d=_public_receipt(Runtime.receipt(result))['diagnostics'] + assert d['stage']=='id_parse' and d['error_code']==code and d['http_status']==200 + assert result['state']=='submission_uncertain' and not result.get('remote_id') + a.submit('owner',rid,bundle,files(bundle),quote={'unit':'POINT','amount':10}) + assert len(posts)==1 and posts[0]['client_id']==rid + +@pytest.mark.parametrize('rid_body',[{'prompt_id':'accepted','node_errors':{'1':{'errors':[{'type':'invalid_prompt'}]}}},{'data':{'taskId':'accepted'}}]) +def test_id_wins_and_no_empty_code(rid_body): + d=attempt_diagnostics('id_parse',rid_body,status=200) + assert d['prompt_id_present'] and 'error_code' not in d + +@pytest.mark.parametrize('status',[100,401,403,413,429,500,599]) +@pytest.mark.parametrize('substage',['runtime_lookup','directory_put','file_put']) +def test_upload_http_safe_status(status,substage): + error=Exception('SECRET URL voice text');error.response=NS(status_code=status) + d=classify(error,substage) + assert d=={'stage':'upload','error_code':'input_upload_failed','bridge_error_code':'upload_http_error','http_status':status,'upload_substage':substage} + assert 'SECRET' not in str(d) + +@pytest.mark.parametrize('status',[True,False,99,600,'503',None]) +def test_reject_bad_status(status): + assert sanitize({'http_status':status,'upload_substage':'SECRET','bridge_error_code':[]})=={} + +@pytest.fixture +def upload_job(tmp_path): + root=tmp_path/'controller';root.mkdir();rid=oid();now=[1000.0] + service=object.__new__(ColabService);service.root=root;service.clock=lambda:now[0] + service._db_local=__import__('threading').local();service._db_strict=True;service.nested_db_events=0;service.nested_db_sites=set() + directory=root/'jobs'/rid;directory.mkdir(parents=True) + uploads=[] + for i in range(3): + p=directory/str(i);p.write_bytes(bytes([i])*5) + uploads.append({'path':str(i),'size':5,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()}) + state={'id':rid,'account_id':oid(),'phase':'preparing','runtime_id':oid(),'native_parity':True,'deadline_epoch':2000,'watchdog_armed':True,'usage_checked_at':1000,'baseline_units':100,'units_observed':0,'uploads':uploads,'upload_index':1,'released':False,'created_at':1000} + with sqlite3.connect(root/'state.sqlite3') as db: + db.execute('CREATE TABLE jobs(id TEXT,owner TEXT,account_id TEXT,state TEXT)') + db.execute('INSERT INTO jobs VALUES (?,?,?,?)',(rid,'owner',state['account_id'],json.dumps(state))) + return service,state,now + +def test_bounded_retry_resume_and_cleanup_pending(upload_job): + s,state,now=upload_job;calls=[];release=[False] + def call(state,op,**kw): + calls.append((op,kw)) + if op=='upload':raise BridgeError('upload_http_error',diagnostics={'http_status':429,'upload_substage':'file_put','token':'SECRET'}) + if op=='runtime_stop':return {'stopped':release[0]} + raise AssertionError(op) + s._call=call + for delta in [0,9,1,29,1]: + now[0]+=delta;s.tick(state) + saved=s.job('owner',state['id']) + assert saved['phase']=='cleanup_pending' and not saved['released'] and saved['outcome']=='failed' + assert saved['upload_index']==1 and saved['upload_attempts']==3 + assert len([c for c in calls if c[0]=='upload'])==3 + assert all(Path(c[1]['local_path']).name=='1' for c in calls if c[0]=='upload') + assert saved['remote_diagnostics']['http_status']==429 + # A new controller instance resumes the durable cleanup, never the upload. + other=object.__new__(ColabService);other.root=s.root;other.clock=s.clock;other._call=call + other._db_local=__import__('threading').local();other._db_strict=True;other.nested_db_events=0;other.nested_db_sites=set() + other.tick(state);assert other.job('owner',state['id'])['phase']=='cleanup_pending' + release[0]=True;other.tick(state);final=other.job('owner',state['id']) + assert final['phase']=='failed' and final['released'] and final['runtime_id']==state['runtime_id'] + assert final['remote_diagnostics']==saved['remote_diagnostics'] + assert len([c for c in calls if c[0]=='upload'])==3 and not any(c[0]=='remote_exec' for c in calls) + j=Journal(s.root/'parity.db');j.reserve('owner',state['id'],'colab','account','case',state['id'],{'unit':'CU','amount':10}) + from compute_parity.colab import ColabNative + a=ColabNative(None,j) + pending=a._record('owner',state['id'],s.public_job(saved)) + assert pending['state']=='cancelling' + result=a._record('owner',state['id'],s.public_job(final)) + assert _public_receipt(Runtime.receipt(result))['diagnostics']==saved['remote_diagnostics'] + + +def test_restart_resumes_index_then_resets_retry(upload_job): + s,state,now=upload_job;calls=[] + def failed(*a,**kw):raise BridgeError('timeout') + s._call=failed;s.tick(state) + now[0]+=10 + other=object.__new__(ColabService);other.root=s.root;other.clock=s.clock + other._db_local=__import__('threading').local();other._db_strict=True;other.nested_db_events=0;other.nested_db_sites=set() + other._call=lambda state,op,**kw:calls.append((op,Path(kw['local_path']).name)) or {} + other.tick(state);other.tick(state) + saved=other.job('owner',state['id']) + assert calls==[('upload','1'),('upload','2')] and saved['upload_index']==3 + assert saved['upload_attempts']==0 and saved['upload_retry_at']==0 and saved['remote_diagnostics']=={} + +@pytest.mark.parametrize('cancel,expire',[(True,False),(False,True)]) +def test_cancel_deadline_during_backoff_release_without_upload(upload_job,cancel,expire): + s,state,now=upload_job;calls=[] + s.update(state['id'],upload_retry_at=1100,cancel_requested=cancel,deadline_epoch=999 if expire else 2000, + remote_diagnostics={'stage':'upload','error_code':'input_upload_failed'}) + s._call=lambda state,op,**kw:calls.append(op) or {'stopped':True} + s.tick(state) + assert calls==['runtime_stop'] and s.job('owner',state['id'])['phase']==('cancelled' if cancel else 'failed') + + +def test_crash_after_last_attempt_does_not_grant_extra_upload(upload_job): + s,state,now=upload_job;calls=[] + s.update(state['id'],upload_attempt_index=1,upload_attempts=3) + s._call=lambda state,op,**kw:calls.append(op) or {'stopped':True} + s.tick(state) + assert calls==['runtime_stop'] and s.job('owner',state['id'])['phase']=='failed' + + +def test_local_corruption_stops_without_network_upload(upload_job): + s,state,now=upload_job;calls=[] + (s.root/'jobs'/state['id']/'1').write_bytes(b'changed') + s._call=lambda state,op,**kw:calls.append(op) or {'stopped':True} + s.tick(state);saved=s.job('owner',state['id']) + assert calls==['runtime_stop'] and saved['remote_diagnostics']['bridge_error_code']=='upload_local_invalid' + +@pytest.mark.parametrize('step',['runtime_lookup','directory_put','file_put']) +def test_real_bridge_upload_step_and_response_close(tmp_path,step): + from scripts.colab_bridge import Bridge as Worker,BridgeError as WorkerError + local=tmp_path/'file';local.write_bytes(b'abc');closed=[] + class Response: + def __init__(self,fail):self.fail=fail + def raise_for_status(self): + if self.fail: + error=Exception('SECRET response');error.response=NS(status_code=413);raise error + def json(self):return {'type':'directory'} + def close(self):closed.append(True) + class HTTP: + def __enter__(self):return self + def __exit__(self,*a):pass + def request(self,method,url,**kw):return Response(step==('directory_put' if kw['json']['type']=='directory' else 'file_put')) + worker=Worker(tmp_path/'account',NS(http=HTTP)) + def runtime(rid): + if step=='runtime_lookup': + error=Exception('SECRET URL');error.response=NS(status_code=413);raise error + return {'url':'https://synthetic.invalid','token':('test-' + 'key-not-' + 'secret-0001')} + worker.runtime=runtime + with pytest.raises(WorkerError) as caught:worker.upload({'runtime_id':oid(),'local_path':str(local),'remote_path':'/content/test/file','max_bytes':32}) + d=caught.value.public()['diagnostics'] + assert d['upload_substage']==step and d['http_status']==413 and d['bridge_error_code']=='upload_http_error' + assert 'SECRET' not in str(caught.value.public()) + assert len(closed)==(0 if step=='runtime_lookup' else 1 if step=='directory_put' else 2) + +@pytest.mark.parametrize('error',[TimeoutError('SECRET'),BridgeError('timeout'),BridgeError('operation_timeout')]) +def test_timeout_classification(error): + assert classify(error)['bridge_error_code']=='upload_timeout' + + +def test_cleanup_diagnostic_fetch_cannot_overwrite_upload(upload_job): + s,state,now=upload_job;saved=s.update(state['id'],phase='cleanup_pending',outcome='failed',remote_diagnostics={'stage':'upload','error_code':'input_upload_failed','http_status':503}) + s._exec=lambda *a:(_ for _ in ()).throw(AssertionError('Must not fetch unlaunched worker status')) + s._call=lambda *a,**k:{'stopped':True};s.tick(saved) + assert s.job('owner',state['id'])['remote_diagnostics']==saved['remote_diagnostics'] + +@pytest.mark.parametrize('code',['upload_http_error','upload_timeout','upload_transport_failed','upload_local_invalid']) +def test_parent_bridge_and_receipt_sanitizers_keep_fixed_upload_diagnostic(tmp_path,monkeypatch,code): + from colab_service import Bridge + from compute_parity.colab import ColabNative + d={'stage':'upload','error_code':'input_upload_failed','bridge_error_code':code,'upload_substage':'file_put','http_status':413,'secret':'NEVER'} + monkeypatch.setattr('colab_service.subprocess.run',lambda *a,**kw:NS(returncode=0,stdout=json.dumps({'ok':False,'error':{'code':code,'diagnostics':d}}))) + with pytest.raises(BridgeError) as caught:Bridge('/usr/bin/python3')('upload',tmp_path) + safe=classify(caught.value);rid=oid();j=Journal(tmp_path/'journal.db');j.reserve('owner',rid,'colab','account','case',rid,{'unit':'CU','amount':1}) + state={'id':rid,'phase':'cleanup_pending','runtime_id':'runtime','remote_diagnostics':safe} + recorded=ColabNative(None,j)._record('owner',rid,ColabService.public_job(None,state)) + assert _public_receipt(Runtime.receipt(recorded))['diagnostics']=={k:v for k,v in d.items() if k!='secret'} + + +def test_upload_sanitizer_does_not_widen_allocation_status(): + assert BridgeError('allocation_uncertain',True,{'http_status':413,'upload_substage':'file_put'}).diagnostics=={} + + +def test_legacy_null_diagnostic_does_not_block_release(upload_job): + s,state,now=upload_job;calls=[] + saved=s.update(state['id'],phase='cleanup_pending',outcome='failed',remote_diagnostics=None) + s._exec=lambda *a:{'status':{}} + s._call=lambda state,op,**kw:calls.append(op) or {'stopped':True} + s.tick(saved) + assert calls==['runtime_stop'] and s.job('owner',state['id'])['released'] diff --git a/scripts/test_compute_r34.py b/scripts/test_compute_r34.py new file mode 100644 index 0000000..1a679d5 --- /dev/null +++ b/scripts/test_compute_r34.py @@ -0,0 +1,153 @@ +"""Membership-native contracts, using observed shapes and real frozen video inputs.""" +import copy,io,json,traceback,urllib.error,uuid +from pathlib import Path +from contextlib import contextmanager +from types import SimpleNamespace as NS +import pytest +from compute_parity.adapters import RunningHubNative +from compute_parity.contracts import ParityError,compile_request +from compute_parity.journal import Journal +from compute_parity.transport import Transport +from compute_parity.runninghub_native import require_membership,no_execution_attempt,exempt_attempts +from test_compute_parity_p1 import FakeTransport +ROOT=Path(__file__).resolve().parents[1] +RID='2120000000000000001' +SUB='0123456789abcdef0123456789abcdef/' +NAME='castle_probe_00001_abcde_1794400000.png' +@pytest.fixture +def frozen(tmp_path): + from test_compute_parity_p1 import synthetic_material_bundle + return synthetic_material_bundle(tmp_path) +def setup(tmp,b): + t=FakeTransport(b);t.info['ResizeImageMaskNode']=json.loads((Path(__file__).parent/'fixtures/r34/runninghub-resize-node.json').read_text());t.rid=RID;j=Journal(tmp/'j.sqlite3');a=RunningHubNative(t,j) + files={i['slot']:Path(i['local_path']).read_bytes() for i in b['inputs']};rid=str(uuid.uuid4()) + return a,t,j,files,rid +def start(tmp,b): + a,t,j,files,rid=setup(tmp,b);a.submit('owner',rid,b,files,quote={'unit':'POINT','amount':100}) + return a,t,j,rid +def entry(kind='images',name=NAME,sub=SUB,status=None): + return {'outputs':{'2':{kind:[{'filename':name,'subfolder':sub,'type':'output'}]}},'status':{'status_str':'success'} if status is None else status} +@pytest.mark.parametrize('kind,name',[('images',NAME),('gifs','castle_video_00001_abcde_1794400000.mp4')]) +def test_exact_observed_success_without_completed_or_prompt(frozen,tmp_path,kind,name): + a,t,j,rid=start(tmp_path,frozen);t.history={RID:entry(kind,name)} + result=a.poll('owner',rid) + assert result['state']=='completed' and result['artifacts']==[{'filename':name,'subfolder':SUB,'type':'output'}] + assert j.get('owner',rid)['remote_id']==RID + assert len([1 for _,p,_ in t.calls if p=='/prompt'])==1 +@pytest.mark.parametrize('status,expected',[({'status_str':'error'},'failed'),({'completed':True},'completed'),({'status_str':'running'},'running'),({},'running'),({'completed':'true'},'running')]) +def test_completion_variants(frozen,tmp_path,status,expected): + a,t,j,rid=start(tmp_path,frozen);t.history={RID:entry(status=status)} + assert a.poll('owner',rid)['state']==expected + +def test_success_requires_outputs(frozen,tmp_path): + a,t,j,rid=start(tmp_path,frozen);t.history={RID:{'outputs':{},'status':{'status_str':'success'}}} + with pytest.raises(ParityError,match='沒有成果'):a.poll('owner',rid) + assert j.get('owner',rid)['state']!='completed' +@pytest.mark.parametrize('sub',['../','/root/','a//','a//b/','a/../','a\\b/','/',None]) +def test_trailing_slash_does_not_weaken_path_validation(frozen,tmp_path,sub): + a,t,j,rid=start(tmp_path,frozen);t.history={RID:entry(sub=sub)} + with pytest.raises(ParityError,match='路徑'):a.poll('owner',rid) + +@pytest.mark.parametrize('kind',['SHARED','NORMAL',None,'OTHER']) +def test_key_gate_before_quote_and_any_submit_post(frozen,tmp_path,monkeypatch,kind): + from compute_parity.hosted_readiness import refresh, PUBLIC_MD5 + from test_compute_parity_p1 import seal + frozen['hosted_model_proof']={name:{'page_id':page,'md5':md5} for name,(page,md5) in PUBLIC_MD5.items()} + seal(frozen) + a,t,j,files,rid=setup(tmp_path,frozen);t.account_type=kind + @contextmanager + def db():yield None + c=NS(root=tmp_path,owner='owner',prefs=NS(db=db),_raw=lambda *a:{'credential_version':1,'account_type':kind}) + monkeypatch.setattr(Transport,'for_owner',lambda *a,**kw:t) + if kind=='NORMAL': + r=refresh(c,frozen,'runninghub',estimates={'runninghub_points':100},persist=False);assert r['ready'] and r['quote']['unit']=='POINT' + assert a.submit('owner',rid,frozen,files,quote=r['quote'])['state']=='queued' + else: + message='企業共享金鑰不接受原生工作' if kind=='SHARED' else '尚未確認 RunningHub 金鑰類型' + with pytest.raises(ParityError,match=message):refresh(c,frozen,'runninghub',persist=False) + with pytest.raises(ParityError,match=message):a.submit('owner',rid,frozen,files,quote={'unit':'POINT','amount':100}) + assert t.calls==[] and j.get('owner',rid) is None + +def test_v2_rejection_retains_point_observations_and_unknown_bill(frozen,tmp_path): + a,t,j,files,rid=setup(tmp_path,frozen);values=iter((1000,999.94));a.observe_point=lambda:next(values) + original=t.request + def request(m,p,**kw):return {'code':404} if p=='/openapi/v2/query' else original(m,p,**kw) + t.request=request;a.submit('owner',rid,frozen,files,quote={'unit':'POINT','amount':100});t.history={RID:entry()} + result=a.poll('owner',rid);job=j.get('owner',rid) + assert result['state']=='completed' and result.get('actual_cost') is None + assert job['cost']['unit']=='POINT' and job['pre_submission_point']['value']==1000 + assert job['balance_observation']['value']==999.94 and job['point_balance_delta']==pytest.approx(.06) + assert job['reserved_amount']==100 + +class Response(io.BytesIO): + status=200 + def __init__(self,raw=b'png',declared='3'):super().__init__(raw);self.headers={} if declared is None else {'Content-Length':declared} +def transport():return Transport('runninghub','placeholder-membership-secret',enabled=True) +def artifact():return {'filename':NAME,'subfolder':SUB,'type':'output'} +def test_exact_two_hop_redirect_chain_no_auth_or_persisted_urls(): + t=transport();calls=[] + locations=['https://www.runninghub.ai/view?Rh-Identify=placeholder-identity&filename='+NAME+'&token=placeholder-token&type=output','https://rh-hk-images.xiaoyaoyou.com/'+SUB+NAME] + def open(req,**kw): + calls.append(req);assert req.get_header('Authorization') is None + if len(calls)<=2:raise urllib.error.HTTPError(req.full_url,302,'private',{'Location':locations[len(calls)-1]},io.BytesIO()) + return Response() + t._opener=NS(open=open) + assert t.download_runninghub_output(artifact())==b'png' and len(calls)==3 + assert '/proxy-plus/' in calls[0].full_url and 'subfolder='+SUB.replace('/','%2F') in calls[0].full_url + assert all('placeholder-token' not in repr(v) for k,v in vars(t).items() if k!='_opener') + assert 'placeholder-membership-secret' not in repr(t) +@pytest.mark.parametrize('location',['http://www.runninghub.ai/view','https://evil.invalid/x','https://www.runninghub.ai.evil.invalid/x','https://www.runninghub.ai:444/view','https://user:password@www.runninghub.ai/view','https://www.runninghub.ai/view#fragment','https://www.runninghub.ai/\nview']) +def test_redirect_allowlist_rejects_before_next_request(location): + t=transport();calls=[] + def open(req,**kw): + calls.append(req);raise urllib.error.HTTPError(req.full_url,302,'private',{'Location':location},io.BytesIO()) + t._opener=NS(open=open) + with pytest.raises(ParityError):t.download_runninghub_output(artifact()) + assert len(calls)==1 + +def test_redirect_limit_and_safe_error_traceback(): + t=transport();calls=[] + def open(req,**kw): + calls.append(req);raise urllib.error.HTTPError(req.full_url,302,'placeholder-sensitive-text',{'Location':'https://www.runninghub.ai/view?token=placeholder-sensitive-token'},io.BytesIO()) + t._opener=NS(open=open) + with pytest.raises(ParityError) as e:t.download_runninghub_output(artifact()) + assert len(calls)==4 + rendered=''.join(traceback.format_exception(e.type,e.value,e.tb)) + assert 'placeholder-sensitive' not in rendered and e.value.__context__ is None +@pytest.mark.parametrize('length',['2','4',None,'-1','536870913','nonnumeric','0']) +def test_download_length_required_and_bounded(length): + t=transport();t._opener=NS(open=lambda *a,**kw:Response(declared=length)) + with pytest.raises(ParityError,match='大小或長度不符'):t.download_runninghub_output(artifact()) + +def historical(rid=None): + return {'owner':'owner','request_id':rid or str(uuid.uuid4()),'lane':'runninghub','case_id':'dance.anime.chatgpt','state':'closed_no_execution_evidence','account':'account-A','root_cause':'no_execution_evidence','artifacts':[], + 'diagnostics':{'http_status':200,'stage':'id_parse','error_code':'empty_response_object','prompt_id_present':False,'transport_error_type':None}, + 'closure_evidence':{'queue_absent':True,'history_absent':True,'unexplained_drop':False,'new_submissions':0,'account':'account-A'}} +@pytest.mark.parametrize('shape',['empty_response_object','missing_prompt_id','legacy']) +def test_exemption_from_durable_receipt_shapes(shape): + j=historical() + if shape=='legacy':j['diagnostics'].pop('error_code');j['diagnostics'].update(response_keys=[],data_keys=[]) + else:j['diagnostics']['error_code']=shape + assert no_execution_attempt(j) +@pytest.mark.parametrize('damage',['remote_id','prompt_id','taskId','artifacts','actual_cost','state','http_status','stage','prompt_id_present','error_code','transport_error_type','queue_absent','history_absent','unexplained_drop','new_submissions','account','no_diagnostics']) +def test_missing_or_conflicting_evidence_is_not_exempt(damage): + j=historical() + if damage in ('remote_id','prompt_id','taskId'):j[damage]=RID + elif damage=='artifacts':j[damage]=[artifact()] + elif damage=='actual_cost':j[damage]={'unit':'POINT','amount':0} + elif damage=='state':j[damage]='submission_uncertain' + elif damage=='no_diagnostics':j['diagnostics']={} + elif damage in ('http_status','stage','prompt_id_present','error_code','transport_error_type'):j['diagnostics'][damage]={'http_status':500,'stage':'upload','prompt_id_present':True,'error_code':'different','transport_error_type':'timeout'}[damage] + else:j['closure_evidence'][damage]={'queue_absent':False,'history_absent':False,'unexplained_drop':True,'new_submissions':1,'account':'different-account'}[damage] + assert not no_execution_attempt(j) + +def test_cap_and_lane_stop_derive_exemptions_without_rewrite(tmp_path): + j=Journal(tmp_path/'j.db');ids=[] + for _ in range(3): + rid=str(uuid.uuid4());j.reserve('owner',rid,'runninghub','account-A','dance.anime.chatgpt',rid,{'unit':'POINT','amount':10}) + row=historical(rid);row.pop('owner');row.pop('request_id');j.update('owner',rid,**row);ids.append(rid) + before=[j.get('owner',rid) for rid in ids] + assert exempt_attempts(before)==set(ids) + j.check_admission('owner','runninghub','dance.anime.chatgpt') + assert [j.get('owner',rid) for rid in ids]==before + assert j.ledger('owner')['runninghub']['unsettled_reserved']==30 diff --git a/scripts/test_compute_r35.py b/scripts/test_compute_r35.py new file mode 100644 index 0000000..c43cca4 --- /dev/null +++ b/scripts/test_compute_r35.py @@ -0,0 +1,498 @@ +"""Disk-only r35 sessions with a fixed dance bundle and materials. + +No SDK instance, external HTTP, allocation, CUDA, or private voice data is used. +""" +import base64 +import hashlib +import json +from pathlib import Path +import shutil +import uuid +import pytest +from colab_service import ColabService, BridgeError, ColabError, encoded +from compute_parity.colab import submit_native, ColabNative +from compute_parity.journal import Journal +from compute_parity.runtime import Runtime +from compute_routing import _public_receipt + +ROOT=Path(__file__).resolve().parents[1] +OWNER='owner' +def oid():return str(uuid.uuid4()) + +class FakeBridge: + installed=True + def __init__(self): + self.calls=[];self.balance=1000;self.allocations=[];self.found=False;self.stopped=True;self.status={} + def __call__(self,op,account_dir,**kw): + self.calls.append((op,kw)) + if op=='account_identity':return {'bound':True,'subject_key':'a'*64} + if op=='account_status':return {'authenticated':True,'balance_compute_units':self.balance,'active_assignments':0} + if op=='runtime_allocate': + result=self.allocations.pop(0) if self.allocations else {'found':True,'runtime_id':kw['allocation_id'],'accelerator':kw['gpu']} + if isinstance(result,Exception):raise result + return result + if op=='runtime_lookup':return {'found':self.found,'runtime_id':kw['allocation_id'],'accelerator':kw['gpu']} + if op=='runtime_stop':return {'stopped':self.stopped} + if op=='upload':return {} + if op=='remote_exec': + code=kw['code'] + # Compile actual remote snippets; never execute notebook code locally. + compile(code,'remote-code','exec') + if "'armed':True" in code: + import re + sid=re.search(r"'session_id':'([^']+)'",code).group(1) + value={'armed':True,'session_id':sid,'watchdog_identity':{'pid':1,'start_ticks':'42','deadline':1021600.0,'lock_dev':1,'lock_ino':2}} + elif 'archive_verified' in code:value={'archive_verified':True} + elif 'bootstrap-status.json' in code:value={'phase':'ready','gpu':'A100','gpu_name':'NVIDIA A100-SXM4-40GB','vram_mib':40536} + elif "'heartbeat':True" in code:value={'heartbeat':True,'watchdog_identity':{'pid':1,'start_ticks':'42','deadline':1021600.0,'lock_dev':1,'lock_ino':2}} + elif 'reusable-clean.json' in code: + import re + jid=re.search(r'/content/web-comfyui/([a-f0-9-]{36})',code).group(1) + value={'clean':True,'job_id':jid,'manifest_sha256':self.service.job(OWNER,jid)['manifest_sha256']} + elif "'status':read('status.json')" in code:value=self.status + else:value={'launched':True} + if 'r.update(heartbeat=True' in code and value.get('phase')=='ready': + import ast + expected=next(line.strip() for line in code.splitlines() if line.strip().startswith('expected=json.loads(')) + value.update(heartbeat=True,watchdog_identity=json.loads(ast.literal_eval(expected[len('expected=json.loads('):-1]))) + value.update(progress_at=self.service.clock(),heartbeat_cycle=ast.literal_eval(next(line.split('=',1)[1] for line in code.splitlines() if line.startswith('probe_cycle='))),heartbeat_at=float(next(line.strip().split('==')[1] for line in code.splitlines() if line.strip().startswith('assert float(lease_heartbeat.read_text())==')))) + return {'stdout':'WEB_COMFYUI_JSON='+json.dumps(value)} + raise AssertionError(op) + +@pytest.fixture +def rig(tmp_path,monkeypatch): + clock=[1000000.0];bridge=FakeBridge() + monkeypatch.setattr(ColabService,'start',lambda self:None) + service=ColabService(tmp_path/'colab',bridge,lambda:clock[0]) + bridge.service=service + account=service.create_account(OWNER,'acct1')['id'] + service.account_action(OWNER,account,'refresh',{}) + from test_compute_parity_p1 import synthetic_material_bundle + bundle = synthetic_material_bundle(tmp_path) + return service,bridge,clock,account,bundle + + +def native(rig): + s,b,clock,account,bundle=rig + body={'request_id':oid(),'account_id':account,'gpu':'A100','max_minutes':60,'quote_amount':15, + 'files':[{'name':Path(i['name']).name,'data':base64.b64encode(Path(i['local_path']).read_bytes()).decode()} for i in bundle['inputs']]} + result=submit_native(s,OWNER,body,bundle) + return s.job(OWNER,result['id']) + + +def ready(rig): + s,b,clock,account,bundle=rig + state=s.sessions.open(OWNER,account,15) + for _ in range(80): + s.sessions.tick_all();state=s.sessions.get(state['id']);clock[0]+=10 + if state['phase']=='ready':return state + assert state['phase']!='closed' + raise AssertionError('not ready') + + +def attach_ready(rig,job): + # r36 prepares the admitted plan lazily before attachment. + s,b,clock,account,bundle=rig + s.tick(job) + for _ in range(8): + s.sessions.tick_all();clock[0]+=1 + if s.job(OWNER,job['id'])['phase']=='preparing':return + raise AssertionError('admitted plan did not become ready') + + +def test_open_bootstrap_once_reuse_two_jobs_and_idle_release(rig): + s,b,clock,account,bundle=rig + state=ready(rig) + first=native(rig);second=native(rig) + for job in (first,second): + attach_ready(rig,job);job=s.job(OWNER,job['id']) + assert job['runtime_id']==state['runtime_id'] and job['phase']=='preparing' + assert not any(x['path'].startswith('runner/') for x in job['uploads']) + assert json.loads((s.root/'jobs'/job['id']/'manifest.json').read_text())['job_id']==job['id'] + b.balance-=2 + job=s.update(job['id'],phase='cleanup_pending',outcome='completed') + s._cleanup(job) + assert s.job(OWNER,job['id'])['units_observed']==2 + assert s.job(OWNER,job['id'])['session_runtime_retained'] + assert len([1 for op,_ in b.calls if op=='runtime_allocate'])==1 + assert len([1 for op,k in b.calls if op=='remote_exec' and "'bootstrap'," in k['code']])==1 + # Heartbeats keep the idle lease alive until the selected idle deadline. + for _ in range(21):clock[0]+=60;s.sessions.tick_all() + final=s.sessions.get(state['id']);assert final['released'] and final['reason']=='idle_timeout' + assert len([1 for op,_ in b.calls if op=='runtime_stop'])==1 + + +def test_admitted_native_job_opens_session_and_launches_isolated_worker(rig): + s,b,clock,account,bundle=rig;job=native(rig) + s.tick(job) + sid=s.job(OWNER,job['id'])['session_id'] + for _ in range(90): + s.sessions.tick_all();s.tick(job);clock[0]+=10 + current=s.job(OWNER,job['id']) + if current['phase']=='running':break + assert current['phase']=='running' + code=next(k['code'] for op,k in b.calls if op=='remote_exec' and "tmp=d/'launch.tmp'" in k['code']) + assert 'session_worker.py' in code and "'job'" in code and sid in code and job['id'] in code + assert 'os.link' in code # Frozen runner bytes are verified for each job. + remote_uploads=[k['remote_path'] for op,k in b.calls if op=='upload' and '/web-comfyui/' in k['remote_path']] + assert remote_uploads and all('/'+job['id']+'/' in path for path in remote_uploads) + assert not any('/runner/' in path for path in remote_uploads) + + +@pytest.mark.parametrize('trigger,reason',[('hard','watchdog_or_hard_cap'),('lost','watchdog_or_hard_cap'),('cu','cu_cap')]) +def test_session_caps_and_watchdog_release_current_job(rig,trigger,reason): + s,b,clock,account,bundle=rig;state=ready(rig);job=native(rig);attach_ready(rig,job) + if trigger=='hard':s.sessions.save(state['id'],deadline_epoch=clock[0]) + elif trigger=='lost':clock[0]+=301 + else:b.balance-=120;clock[0]+=60 + s.sessions.tick_all();state=s.sessions.get(state['id']) + assert state['released'] and state['reason']==reason + assert s.job(OWNER,job['id'])['phase']=='failed' + + +def test_close_waits_for_current_and_cancels_queue(rig): + s,b,clock,account,bundle=rig;state=ready(rig) + job=native(rig);waiting=native(rig);attach_ready(rig,job);s.tick(waiting) + s.sessions.close(OWNER);s.sessions.tick_all() + assert not s.sessions.get(state['id'])['released'] + s._cleanup(s.update(job['id'],phase='cleanup_pending',outcome='completed')) + s.sessions.tick_all() + assert s.sessions.get(state['id'])['released'] + assert s.job(OWNER,waiting['id'])['phase']=='cancelled' + assert s.public_job(s.job(OWNER,waiting['id']))['status_label']=='工作已取消' + + +@pytest.mark.parametrize('ambiguous',[False,True]) +def test_gpu_fallback_order_and_original_id_lookup(rig,ambiguous): + s,b,clock,account,bundle=rig + b.allocations=[BridgeError('allocation_uncertain',True),BridgeError('allocation_unavailable'),{'found':True,'runtime_id':oid(),'accelerator':'G4'}] if ambiguous else [BridgeError('allocation_unavailable'),BridgeError('allocation_unavailable'),{'found':True,'runtime_id':oid(),'accelerator':'G4'}] + state=s.sessions.open(OWNER,account,15) + s.sessions.tick_all() + if ambiguous: + saved=s.sessions.get(state['id']);original=saved['allocation_id'] + s.sessions.tick_all();assert len([1 for op,_ in b.calls if op=='runtime_allocate'])==1 + clock[0]+=150;s.sessions.tick_all() + assert all(k['allocation_id']==original for op,k in b.calls if op=='runtime_lookup') + for _ in range(4):s.sessions.tick_all() + assert [k['gpu'] for op,k in b.calls if op=='runtime_allocate']==['A100','H100','G4'] + assert s.sessions.get(state['id'])['gpu']=='G4' + + +@pytest.mark.parametrize('gpu',['L4','T4']) +def test_native_parity_rejects_small_gpu_before_allocation(rig,gpu): + s,b,clock,account,bundle=rig + from compute_parity.contracts import ParityError + with pytest.raises(ParityError):submit_native(s,OWNER,{'gpu':gpu},bundle) + assert not any(op=='runtime_allocate' for op,_ in b.calls) + + +def test_request_round_spacing_twelve_cap_and_zero_runtime_cost(rig): + s,b,clock,account,bundle=rig + b.allocations=[BridgeError('allocation_unavailable') for _ in range(36)] + state=s.sessions.open(OWNER,account,15) + for index in range(12): + for _ in range(3):s.sessions.tick_all() + saved=s.sessions.get(state['id']);assert saved['attempts']==index+1 + count=len([1 for op,_ in b.calls if op=='runtime_allocate']) + clock[0]+=599;s.sessions.tick_all() + assert len([1 for op,_ in b.calls if op=='runtime_allocate'])==count + clock[0]+=1 + s.sessions.tick_all();s.sessions.tick_all() + final=s.sessions.get(state['id']) + assert final['phase']=='closed' and final['reason']=='attempt_cap' and final['units_observed']==0 + with s.db() as db:dates=[r[0] for r in db.execute('SELECT at FROM session_attempts ORDER BY at')] + assert len(dates)==12 and all(y-x>=600 for x,y in zip(dates,dates[1:])) + + +def test_twenty_four_rolling_lane_cap_and_expiry(rig): + s,b,clock,account,bundle=rig;state=s.sessions.open(OWNER,account,15) + with s.db() as db: + for i in range(24):db.execute('INSERT INTO session_attempts VALUES (?,?,?)',(oid(),'other-owner-session',clock[0]-86400+100+i)) + s.sessions.tick_all();s.sessions.tick_all() + assert s.sessions.get(state['id'])['reason']=='rolling_24h_cap' + assert not any(op=='runtime_allocate' for op,_ in b.calls) + clock[0]+=200;s.sessions.open(OWNER,account,15);s.sessions.tick_all() + assert len([1 for op,_ in b.calls if op=='runtime_allocate'])==1 + + +def test_cancel_acquisition_waits_for_uncertain_original_lease(rig): + s,b,clock,account,bundle=rig;b.allocations=[BridgeError('allocation_uncertain',True)] + job=native(rig);s.tick(job);state=s.sessions.rows(OWNER)[0];s.sessions.tick_all() + s.sessions.close(OWNER);s.sessions.tick_all() + assert not s.sessions.get(state['id'])['released'] + clock[0]+=150;s.sessions.tick_all() + assert s.sessions.get(state['id'])['released'] + assert s.job(OWNER,job['id'])['phase']=='cancelled' + assert len([1 for op,_ in b.calls if op=='runtime_allocate'])==1 + + +def test_restart_reconciles_without_allocate_or_launch_replay(rig): + s,b,clock,account,bundle=rig;b.allocations=[BridgeError('allocation_uncertain',True)] + state=s.sessions.open(OWNER,account,15);s.sessions.tick_all();b.found=True + restarted=ColabService(s.root,b,s.clock);restarted.sessions.tick_all() + state=restarted.sessions.get(state['id']) + assert state['runtime_id'] and state['phase']=='uploading' and state['watchdog_armed'] + assert len([1 for op,_ in b.calls if op=='runtime_allocate'])==1 + restarted.sessions.save(state['id'],phase='bootstrap_launch',uploads=[{}],launch_at=clock[0]) + restarted.sessions.tick_all() + assert not any(op=='remote_exec' and "'bootstrap'," in k['code'] for op,k in b.calls) + + +def test_restart_after_heartbeat_gap_closes_no_reuse(rig): + s,b,clock,account,bundle=rig;state=ready(rig);clock[0]+=301 + restarted=ColabService(s.root,b,s.clock);restarted.sessions.tick_all() + assert restarted.sessions.get(state['id'])['released'] + assert len([1 for op,_ in b.calls if op=='runtime_allocate'])==1 + + +def test_account_with_quote_balance_only_no_rotation(rig): + s,b,clock,account,bundle=rig + empty=s.create_account(OWNER,'acct2')['id'];s.account_action(OWNER,empty,'refresh',{}) + original=b.__call__ + class Accounts: + installed=True + def __call__(self,op,path,**kw): + if op=='account_status' and path.name==empty:return {'authenticated':True,'balance_compute_units':0} + return original(op,path,**kw) + s.bridge=Accounts() + assert s.sessions.select_account(OWNER,15)==account + with pytest.raises(ColabError):s.sessions.select_account(OWNER,15,empty) + b.balance=14 + with pytest.raises(ColabError):s.sessions.open(OWNER,account,15) + assert not any(op=='runtime_allocate' for op,_ in b.calls) + + +def test_session_cost_separate_from_jobs_and_receipt_gpu(rig): + s,b,clock,account,bundle=rig;state=ready(rig) + b.balance-=3;clock[0]+=60;s.sessions.tick_all() # bootstrap/idle + job=native(rig);attach_ready(rig,job);job=s.job(OWNER,job['id']) + b.balance-=2;s._cleanup(s.update(job['id'],phase='cleanup_pending',outcome='completed')) + j=Journal(s.root.parent/'compute-parity/journal.sqlite3') + j.reserve(OWNER,job['id'],'colab',account,bundle['case_id'],'identity',{'unit':'CU','amount':15}) + result=ColabNative(s,j).poll(OWNER,job['id']) + receipt=_public_receipt(Runtime.receipt(result)) + assert receipt['gpu']=='A100' and receipt['gpu_name']=='NVIDIA A100-SXM4-40GB' and receipt['session_id']==state['id'] + ledger=j.ledger(OWNER) + assert ledger['colab']['actual']==2 and ledger['colab_sessions']['actual']==3 + assert ledger['colab_sessions']['sessions'][0]['total_observed']==5 + + +@pytest.mark.parametrize('idle',[9,61,10.5,True]) +def test_owner_idle_bounds(rig,idle): + s,*_=rig + with pytest.raises(ColabError):s.sessions.settings(OWNER,{'idle_minutes':idle}) + + +@pytest.mark.parametrize('cap',[0,-1,float('nan'),float('inf'),True]) +def test_owner_cu_bounds(rig,cap): + s,*_=rig + with pytest.raises(ColabError):s.sessions.settings(OWNER,{'max_units':cap}) + + +def test_session_owner_isolation_and_live_setting(rig): + s,b,clock,account,bundle=rig;state=ready(rig) + s.sessions.close('different-owner') + assert not s.sessions.get(state['id']).get('close_requested') + assert s.sessions.snapshot('different-owner')['session_ledger']==[] + s.sessions.settings(OWNER,{'idle_minutes':10,'max_units':50}) + assert s.sessions.get(state['id'])['settings']=={'idle_minutes':10,'hard_hours':6,'max_units':50} + + +def test_watchdog_child_is_fail_closed_and_syntax_valid(): + from scripts.colab_session_watchdog import build,WORKER + compile(build(oid(),1000000),'watchdog-bootstrap','exec');compile(WORKER,'watchdog-worker','exec') + assert "time.time()-float((root/'heartbeat').read_text())<300" in WORKER + assert "while True:" in WORKER and 'runtime.unassign()' in WORKER + + + + +def load_worker(monkeypatch): + import importlib.util + monkeypatch.syspath_prepend(str(Path(__file__).parent/'colab_remote')) + spec=importlib.util.spec_from_file_location('r35_worker',Path(__file__).parent/'colab_session_worker.py') + module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) + return module + + +@pytest.mark.parametrize('gpu',['NVIDIA L4, 24000','Tesla T4, 16000','NVIDIA A100, 20000']) +def test_runtime_gpu_check_never_accepts_low_vram(monkeypatch,gpu): + worker=load_worker(monkeypatch) + with pytest.raises(RuntimeError):worker.verify_gpu(gpu) + + +@pytest.mark.parametrize('gpu',['NVIDIA A100-SXM4-40GB, 40536','NVIDIA H100 80GB HBM3, 81559','NVIDIA RTX PRO 6000 Blackwell, 97887']) +def test_runtime_gpu_check_accepts_class_memory(monkeypatch,gpu): + worker=load_worker(monkeypatch) + assert worker.verify_gpu(gpu)[1]>=39000 + + +def test_bootstrap_public_once_and_no_private_plan(rig,monkeypatch): + s,b,clock,account,bundle=rig + state=s.sessions.open(OWNER,account,15);state=s.sessions.freeze(state) + folder=s.root/'sessions'/state['id'] + plans=json.loads((folder/'bootstrap.json').read_text()) + assert len(plans)==1 and all(not m.get('private') for p in plans for m in p['models']) + assert all('voice_export' not in p and 'inputs' not in p and 'graph' not in p for p in plans) + worker=load_worker(monkeypatch);calls=[] + monkeypatch.setattr(worker,'comfy_identity',lambda *a,**kw:{'verified':True}) + monkeypatch.setattr(worker.subprocess,'check_output',lambda *a,**kw:'NVIDIA A100, 40536') + monkeypatch.setattr(worker,'bootstrap',lambda plan,cache,**kw:calls.append(plan)) + # This test stubs the entire bootstrap; actual inventory/reuse has separate tests. + monkeypatch.setattr(worker,'verify_cached_overlays',lambda plans,cache:None) + monkeypatch.setattr(worker,'verify_ready',lambda *a:None) # Whole-bootstrap mock; real gate covered in r40v4. + assert worker.bootstrap_session(folder)==0 + count=len(calls);assert count>0 + assert worker.bootstrap_session(folder)==0 and len(calls)==count + assert json.loads((folder/'bootstrap-status.json').read_text())['phase']=='ready' + + +def test_real_manifest_worker_isolation_and_single_submit(rig,monkeypatch,tmp_path): + s,b,clock,account,bundle=rig + jobs=[native(rig),native(rig)] + worker=load_worker(monkeypatch) + monkeypatch.setattr(worker,'comfy_identity',lambda *a,**kw:{'verified':True}) + session=tmp_path/'remote-session';session.mkdir();cache=session/'cache';cache.mkdir();core=cache/'ComfyUI';core.mkdir() + monkeypatch.setattr(worker,'prepared',lambda bundle,session:(core,'/mock/python')) + monkeypatch.setattr(worker,'dependency_probe',lambda *a:{'ready':True}) + monkeypatch.setattr(worker,'output_check',lambda path,contract:None) + monkeypatch.setattr(worker.time,'time',lambda:clock[0]) + monkeypatch.setattr(worker.subprocess,'check_output',lambda *a,**kw:'NVIDIA H100, 81559' if 'name,memory.total' in str(a) else '1024') + realpath=Path + # Redirect the frozen graph's fixed video alias onto disk for offline tests. + monkeypatch.setattr(worker,'Path',lambda p:tmp_path/'alias' if str(p)=='/content/castle-parity-input' else realpath(p)) + commands=[];submits=[];current=[None] + monkeypatch.setattr(worker,'stop_group',lambda proc:None) # Exercised with real CPU process groups in safety suite. + class Process: + def poll(self):return None + def terminate(self):pass + def wait(self,**kw):return 0 + monkeypatch.setattr(worker.subprocess,'Popen',lambda args,**kw:commands.append(args) or Process()) + def request(method,path,body=None): + if path=='/object_info':return {} + if path=='/prompt': + submits.append(body) + jobroot=current[0];output=jobroot/'comfy-output';output.mkdir(exist_ok=True) + src=next(i for i in bundle['inputs'] if i['kind']=='video') + shutil.copyfile(src['local_path'],output/'result.mp4') + return {'prompt_id':'accepted'} + return {'accepted':{'status':{'completed':True},'outputs':{'1':{'videos':[{'type':'output','filename':'result.mp4'}]}}}} + monkeypatch.setattr(worker,'local_request',request) + for job in jobs: + folder=s.root/'jobs'/job['id'];current[0]=folder + assert worker.run_native(folder,job['manifest_sha256'],session)==0 + result=json.loads((folder/'artifacts.json').read_text()) + assert result['job_id']==job['id'] and result['manifest_sha256']==job['manifest_sha256'] + assert (folder/result['artifacts'][0]['path']).is_file() + assert not (folder/'comfy-input').exists() and not (folder/'comfy-output').exists() + assert not (tmp_path/'alias').exists() + # A repeated launch cannot POST the graph again, even after completion. + before=len(submits) + with pytest.raises(FileNotFoundError):worker.run_native(folder,job['manifest_sha256'],session) + assert json.loads((folder/'reusable-clean.json').read_text())['clean'] + assert len(submits)==before + assert len(submits)==2 and len(commands)==2 + assert commands[0][commands[0].index('--input-directory')+1]!=commands[1][commands[1].index('--input-directory')+1] + assert commands[0][commands[0].index('--output-directory')+1]!=commands[1][commands[1].index('--output-directory')+1] + + +def test_watchdog_heartbeat_failure_closes_lease(rig,monkeypatch): + s,b,clock,account,bundle=rig;state=ready(rig);original=s._exec + def broken(state,code): + if "'heartbeat':True" in code:raise BridgeError('remote_execution_failed') + return original(state,code) + monkeypatch.setattr(s,'_exec',broken) + s.sessions.tick_all();s.sessions.tick_all() + assert s.sessions.get(state['id'])['released'] + assert s.sessions.get(state['id'])['reason']=='watchdog_state_lost' + + +def test_release_is_not_terminal_until_provider_confirms(rig): + s,b,clock,account,bundle=rig;state=ready(rig);b.stopped=False + s.sessions.close(OWNER);s.sessions.tick_all() + assert not s.sessions.get(state['id'])['released'] + b.stopped=True;s.sessions.tick_all() + assert s.sessions.get(state['id'])['released'] + + +@pytest.mark.parametrize('heartbeat',['missing','stale','fresh_hard_cap']) +def test_runtime_watchdog_executes_release_on_lost_state(tmp_path,monkeypatch,heartbeat): + import os,sys,time,subprocess + from scripts.colab_session_watchdog import WORKER + root=tmp_path/'watchdog';root.mkdir();now=time.time() + if heartbeat!='missing':(root/'heartbeat').write_text(str(now-301 if heartbeat=='stale' else now)) + deadline=now-1 if heartbeat=='fresh_hard_cap' else now+600 + monkeypatch.setattr(sys,'argv',['watchdog',str(root),str(deadline)]) + calls=[];fds=[];real_open=os.open + def opened(*args,**kw): + fd=real_open(*args,**kw);fds.append(fd);return fd + monkeypatch.setattr(os,'open',opened) + def released(args,**kw): + calls.append(args);raise SystemExit(0) + monkeypatch.setattr(subprocess,'run',released) + try: + with pytest.raises(SystemExit):exec(compile(WORKER,'runtime-watchdog','exec'),{}) + finally: + for fd in fds:os.close(fd) + assert len(calls)==1 and 'runtime.unassign()' in calls[0][-1] + + +def test_controller_pending_session_allows_queue_not_duplicate_job(rig): + s,b,clock,account,bundle=rig + a=native(rig);second=native(rig) + assert a['session_id']==second['session_id'] and a['id']!=second['id'] + assert len(s.sessions.rows(OWNER))==1 + j=Journal(s.root.parent/'compute-parity/journal.sqlite3') + for job in (a,second): + _,new=j.reserve(OWNER,job['id'],'colab',account,bundle['case_id'],job['id'],{'unit':'CU','amount':15}) + assert new + _,new=j.reserve(OWNER,a['id'],'colab',account,bundle['case_id'],a['id'],{'unit':'CU','amount':15}) + assert not new + + +@pytest.mark.parametrize('action',['get','open','close','settings']) +def test_real_authenticated_session_routes_are_owner_scoped(rig,action): + import ast,types + s,b,clock,account,bundle=rig + tree=ast.parse((Path(__file__).resolve().parents[1]/'webui/server.py').read_text()) + method=next(node for node in ast.walk(tree) if isinstance(node,ast.FunctionDef) and node.name=='api_colab') + method.decorator_list=[] + module=ast.Module(body=[method],type_ignores=[]);ast.fix_missing_locations(module) + import colab_service,urllib + scope={'get_colab_service':lambda:s,'colab_service':colab_service,'urllib':urllib,'RequestBodyError':type('RequestBodyError',(Exception,),{})} + exec(compile(module,'session-route','exec'),scope) + class Handler: + def current_user(self):return {'email':OWNER} + def read_provider_json(self,*a):return {'idle_minutes':10} if action=='settings' else {} + def send_json(self,result,status=200,**kw):self.result=result;self.status=status + h=Handler();scope['api_colab'](h,'/api/colab/session'+('' if action=='get' else '/'+action),action!='get') + assert h.status==200 and h.result['ok'] and 'session_ledger' in h.result + assert s.sessions.snapshot('other-owner')['session_ledger']==[] + if action=='open':assert h.result['session']['phase']=='requesting' + if action=='settings':assert h.result['settings']['idle_minutes']==10 + assert not any(op=='runtime_allocate' for op,_ in b.calls) + + +def test_unknown_usage_never_becomes_zero_settlement(rig,monkeypatch): + s,b,clock,account,bundle=rig;state=ready(rig);job=native(rig);attach_ready(rig,job) + original=s._call + def unavailable(state,op,**kw): + if op=='account_status':raise BridgeError('timeout') + return original(state,op,**kw) + monkeypatch.setattr(s,'_call',unavailable) + s.sessions.close(OWNER);s.sessions.save(state['id'],phase='closing');s.sessions.tick_all() + assert not s.job(OWNER,job['id'])['released'] + assert s.sessions.get(state['id'])['phase']=='released_unsettled' + line=s.sessions.snapshot(OWNER)['session_ledger'][0] + assert line['amount'] is None and line['usage_unknown'] and not line['settled'] + journal=Journal(s.root.parent/'compute-parity/journal.sqlite3') + ledger=journal.ledger(OWNER)['colab_sessions'] + assert ledger['actual_is_lower_bound'] and ledger['unsettled_sessions']==1 + + +def test_closing_session_never_uploads_or_launches_next(rig): + s,b,clock,account,bundle=rig;state=ready(rig);job=native(rig);attach_ready(rig,job) + s.sessions.save(state['id'],phase='closing',reason='watchdog_state_lost') + before=len(b.calls);s.tick(job) + assert not any(op in {'upload','runtime_allocate'} or op=='remote_exec' and 'Popen' in k['code'] for op,k in b.calls[before:]) + assert s.job(OWNER,job['id'])['released'] diff --git a/scripts/test_compute_r36.py b/scripts/test_compute_r36.py new file mode 100644 index 0000000..1e96cb8 --- /dev/null +++ b/scripts/test_compute_r36.py @@ -0,0 +1,310 @@ +"""P1m diagnostic regressions and r36 boundaries; disk fixtures, mocked bridge.""" +import importlib.util,json,os,sqlite3,sys,urllib.error,subprocess,uuid +from pathlib import Path +from types import SimpleNamespace +import pytest +from test_compute_r35 import load_worker,rig,native,ready,OWNER +from scripts.colab_session_diagnostics import plan,plan_id,sanitize_diagnostics,telemetry,redacted_tail +from compute_parity.provisioning import states,provisioning_only + +GPU='NVIDIA RTX PRO 6000 Blackwell Server Edition' + +@pytest.mark.parametrize('http',[False,True]) +def test_live_bootstrap_discards_distinct_failure_diagnostics(tmp_path,monkeypatch,http): + # Port of both P1m observed-loss probes, flipped to preserved evidence. + worker=load_worker(monkeypatch) + (tmp_path/'bootstrap.json').write_text(json.dumps([{'models':[]}])) + monkeypatch.setattr(worker.subprocess,'check_output',lambda *a,**kw:GPU+', 97887') + def fail(*a,**kw): + kw['stage']('model_download') + if http:raise urllib.error.HTTPError('https://invalid.example/?secret=hidden',503,'private',{},None) + raise RuntimeError('private') + monkeypatch.setattr(worker,'bootstrap',fail) + monkeypatch.setattr(worker,'prepare_supplement',lambda *a:None) + monkeypatch.setattr(worker,'node_gate',lambda *a:None) # Test post-gate download exception. + assert worker.bootstrap_session(tmp_path)==1 + status=json.loads((tmp_path/'bootstrap-status.json').read_text()) + assert status['phase']=='failed' and status['gpu_name']==GPU + assert status['diagnostics']=={'stage':'session_bootstrap','substage':'model_download','error_type':'HTTPError' if http else 'RuntimeError','error_code':'stage_failed',**({'http_status':503} if http else {})} + assert 'private' not in json.dumps(list(status.values())) and 'invalid.example' not in json.dumps(status) + assert status['disk_free_gib']>0 and status['python_version'] + +@pytest.mark.parametrize('phase,alive,age,reason',[('failed',False,0,'bootstrap_failed'),('missing',False,0,'bootstrap_process_lost'),('running',True,121,'bootstrap_stalled'),('ready',False,0,None)]) +def test_live_controller_collapses_reported_failure_and_missing_status(rig,monkeypatch,phase,alive,age,reason): + s,b,clock,account,bundle=rig + state=s.sessions.open(OWNER,account,15) + state=s.sessions.save(state['id'],phase='bootstrap',uploads=[{}],launch_at=clock[0]) + result={'phase':phase,'alive':alive,'progress_at':clock[0]-age,'identity':{'pid':1,'start_ticks':'1'},'gpu':'G4','gpu_name':GPU,'vram_mib':97887} + if phase=='failed':result['diagnostics']={'stage':'session_bootstrap','substage':'runtime_lock','error_code':'stage_failed','error_type':'CalledProcessError','exit_code':1} + monkeypatch.setattr(s,'_exec',lambda st,code:result if 'bootstrap-status.json' in code else {'tail':'[redacted]\nframe native_runner.py:98\nhttps://secret.invalid/?token=private'}) + if reason=='bootstrap_stalled': + from colab_service import BridgeError + before=state['last_tick'] + for streak in (1,2): + with pytest.raises(BridgeError) as caught:s.sessions.bootstrap(s.sessions.get(state['id'])) + s.sessions.record_fault(state,caught.value) + current=s.sessions.get(state['id']) + assert current['last_tick']==before and current['fault_streak']==streak + assert current['private_rpc_error']=={'bootstrap_probe':{'type':'progress_stale'}} + assert current['phase']=='closing' + return + s.sessions.bootstrap(state);current=s.sessions.get(state['id']) + if reason: + assert current['reason']==reason and current['phase']=='closing' + assert current['bootstrap_diagnostics']['stage']=='session_bootstrap' + path=s.root/'sessions'/state['id']/'bootstrap.stderr.txt' + assert path.stat().st_mode&0o777==0o600 + assert path.read_text()=='[redacted]\nframe native_runner.py:98' + assert 'tail' not in json.dumps(current) + else:assert current['phase']=='ready' + assert current['gpu_name']==GPU + +@pytest.mark.parametrize('error',[subprocess.CalledProcessError(3,['secret']),ImportError('private'),PermissionError('private')]) +def test_patch_keeps_safe_diagnostics_and_verified_gpu(tmp_path,monkeypatch,error): + worker=load_worker(monkeypatch);(tmp_path/'bootstrap.json').write_text('[{"models":[]}]') + monkeypatch.setattr(worker.subprocess,'check_output',lambda *a,**kw:GPU+', 97887') + def fail(*a,**kw):raise error + monkeypatch.setattr(worker,'bootstrap',fail) + monkeypatch.setattr(worker,'prepare_supplement',lambda *a:None) + monkeypatch.setattr(worker,'node_gate',lambda *a:None) # Test post-gate download exception. + assert worker.bootstrap_session(tmp_path)==1 + status=json.loads((tmp_path/'bootstrap-status.json').read_text()) + assert status['gpu_name']==GPU and status['diagnostics']['error_type']==type(error).__name__ + assert status['diagnostics'].get('exit_code')==(3 if isinstance(error,subprocess.CalledProcessError) else None) + +@pytest.mark.parametrize('bad',[{},[],None,0,True,'https://private.invalid']) +def test_untrusted_diagnostics_and_telemetry_are_bounded(bad): + value={k:bad for k in ['stage','substage','error_type','error_code','gpu','gpu_name','vram_mib','disk_free_gib','python_version','exit_code','http_status']} + assert sanitize_diagnostics(value)==({'exit_code':0} if type(bad) is int and bad==0 else {}) + assert telemetry(value)==({'disk_free_gib':0} if type(bad) is int and bad==0 else {}) + from compute_routing import _public_receipt + receipt=_public_receipt({'state':'failed','requested_gpu':bad,'assigned_gpu':bad}) + assert 'requested_gpu' not in receipt and 'assigned_gpu' not in receipt + +def test_stderr_tail_drops_all_message_text_and_paths(tmp_path): + p=tmp_path/'stderr';p.write_text('x'*20000+'\nFile "/home/private/native_runner.py", line 98\nValueError: https://example.invalid/?token=hidden\nfoo@example.invalid /home/private/file api_key=hidden\n') + tail=redacted_tail(p) + assert len(tail)<=4096 and 'frame native_runner.py:98' in tail + assert all(secret not in tail for secret in ['https','hidden','@','/home/','api_key']) + link=tmp_path/'link';link.symlink_to(p);assert redacted_tail(link)=='' + +@pytest.mark.parametrize('failure',['argv','import','lock']) +def test_shim_reports_before_native_import_or_lock(tmp_path,monkeypatch,failure): + # Only tests override the hard-coded Colab path validation. + import scripts.colab_session_bootstrap as shim + root=tmp_path/'content/castle-sessions'/str(uuid.uuid4());root.mkdir(parents=True) + monkeypatch.setattr(shim,'__file__',str(root/'session_bootstrap.py')) + if failure=='argv': + assert shim.main(['bad'])==1 + else: + real=shim.Path + class RemotePath(type(real())): + def __str__(self): + text=super().__str__() + return '/content/castle-sessions' if text==str(root.parent) else text + # Instead intercept the path boundary in the test copy, never product. + source=Path(shim.__file__).parent # no real remote directories + code=Path(__file__).resolve().parent/'colab_session_bootstrap.py' + local=tmp_path/'shim.py' + local.write_text(code.read_text().replace("'/content/castle-sessions'",repr(str(root.parent)))) + spec=importlib.util.spec_from_file_location('test_shim',local);m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) + monkeypatch.setattr(m,'__file__',str(root/'session_bootstrap.py')) + if failure=='import':monkeypatch.setitem(sys.modules,'session_worker',None) + else: + w=load_worker(monkeypatch) + monkeypatch.setattr(w.fcntl,'flock',lambda *a:(_ for _ in ()).throw(PermissionError('private'))) + monkeypatch.setitem(sys.modules,'session_worker',w) + assert m.main(['bootstrap',str(root)])==1 + status=json.loads((root/'bootstrap-status.json').read_text()) + assert status['phase']=='failed' and status['diagnostics']['substage']==failure + + +def test_worker_prepares_only_selected_plan_and_deduplicates(tmp_path,monkeypatch): + worker=load_worker(monkeypatch);plans=[{'feature':'dance','models':[]},{'feature':'voice-speak','models':[]}] + monkeypatch.setattr(worker,'comfy_identity',lambda *a,**kw:{'verified':True}) + (tmp_path/'bootstrap.json').write_text(json.dumps(plans+[plans[0]]));calls=[] + monkeypatch.setattr(worker.subprocess,'check_output',lambda *a,**kw:GPU+', 97887') + monkeypatch.setattr(worker,'bootstrap',lambda p,c,**kw:calls.append((p,c))) + monkeypatch.setattr(worker,'verify_ready',lambda *a:None) # Whole-bootstrap mock. + for p in plans: + ident=plan_id(p) + assert worker.bootstrap_session(tmp_path,ident)==0 + assert worker.bootstrap_session(tmp_path,ident)==0 + assert [p['feature'] for p,c in calls]==['dance','voice-speak'] and calls[0][1]!=calls[1][1] + + +def test_preopen_is_lazy_then_admitted_job_plan_only(rig): + s,b,clock,account,bundle=rig;state=ready(rig) + assert state['prepared_plans']==[] + assert not any(op=='remote_exec' and "'bootstrap'," in k['code'] for op,k in b.calls) + job=native(rig) + for _ in range(8):s.sessions.tick_all();clock[0]+=10 + state=s.sessions.get(state['id']);current=s.job(OWNER,job['id']) + assert current['phase']=='preparing' + assert state['prepared_plans']==[plan_id(plan(bundle))] + assert len(state['plan_catalog'])==1 + + +def test_failed_plan_only_fails_matching_jobs_and_reuses_other_plan(rig,monkeypatch): + import copy + from test_compute_parity_p1 import seal + s,b,clock,account,bundle=rig + other_bundle=copy.deepcopy(bundle) + other_bundle['case_id']='dance.anime.claude' + other_bundle['core']['commit']='c'*40 + seal(other_bundle) + (s.root.parent/'compute-parity/bundles-r29'/('dance.anime.claude.json')).write_text(json.dumps(other_bundle)) + state=ready(rig) + one=native(rig);first=one['bootstrap_plan_id'] + two=native((s,b,clock,account,other_bundle));other=two['bootstrap_plan_id'] + assert other!=first + state=s.sessions.save(state['id'],phase='bootstrap',bootstrap_plan_id=first,launch_at=clock[0],assigned_gpu='G4') + monkeypatch.setattr(s,'_exec',lambda st,code:{'clean':True}) + diagnostic={'stage':'session_bootstrap','substage':'node_checkout','error_type':'ValueError','error_code':'stage_failed'} + s.sessions.fail_plan(state,diagnostic,'bootstrap_failed') + assert s.job(OWNER,one['id'])['phase']=='failed' and s.job(OWNER,one['id'])['released'] + assert s.job(OWNER,one['id'])['assigned_gpu']=='G4' + assert s.job(OWNER,two['id'])['phase']=='queued' + state=s.sessions.get(state['id']);assert state['phase']=='ready' and first in state['failed_plans'] + s.sessions.attach(state,s.job(OWNER,two['id'])) + assert s.sessions.get(state['id'])['bootstrap_plan_id']==other + assert not any(op=='runtime_stop' for op,k in b.calls) + + +def test_last_failed_plan_closes_and_cu_stays_on_session(rig,monkeypatch): + s,b,clock,account,bundle=rig;state=ready(rig);one=native(rig) + state=s.sessions.save(state['id'],phase='bootstrap',bootstrap_plan_id=one['bootstrap_plan_id'],launch_at=clock[0]) + monkeypatch.setattr(s,'_exec',lambda st,code:{'clean':True}) + s.sessions.fail_plan(state,{'stage':'session_bootstrap','error_code':'stage_failed'},'bootstrap_failed') + assert s.sessions.get(state['id'])['phase']=='closing' + b.balance-=.12;s.sessions.release(s.sessions.get(state['id'])) + state=s.sessions.get(state['id']) + assert state['released'] and state['session_units']==pytest.approx(.12) and state['job_units']==0 + assert s.job(OWNER,one['id'])['units_observed']==0 + +@pytest.mark.parametrize('cause',['runtime','launch','cu','unknown','missing','wrong_owner','clean']) +def test_exemption_joins_session_by_owner_and_id(rig,cause): + s,b,clock,account,bundle=rig;one=native(rig);sid=one['session_id'] + s.update(one['id'],phase='failed',released=True,units_observed=0) + changes={'phase':'closed','released':True,'usage_unknown':False,'units_observed':0} + if cause=='runtime':changes['runtime_id']='runtime' + if cause=='launch':changes['launch_at']=clock[0] + if cause=='cu':changes['units_observed']=.12 + if cause=='unknown':changes['usage_unknown']=True + s.sessions.save(sid,**changes) + if cause in {'missing','wrong_owner'}: + with s.db() as db: + if cause=='missing':db.execute('DELETE FROM work_sessions WHERE id=?',(sid,)) + else:db.execute('UPDATE work_sessions SET owner=? WHERE id=?',('different',sid)) + receipt={'lane':'colab','request_id':one['id'],'remote_id':one['id'],'account':account,'state':'failed','actual_cost':{'unit':'CU','amount':0}} + assert provisioning_only(receipt,states(s.root/'state.sqlite3',OWNER)[one['id']]) is (cause=='clean') + + +def test_gpu_truth_and_bootstrap_diagnostic_on_receipt(rig): + from compute_parity.colab import ColabNative + from compute_parity.journal import Journal + from compute_routing import _public_receipt + s,b,clock,account,bundle=rig;ready(rig);one=native(rig) + s.sessions.save(one['session_id'],phase='closing',assigned_gpu='G4',gpu='G4',gpu_name=None,bootstrap_diagnostics={'stage':'session_bootstrap','substage':'import','error_type':'ModuleNotFoundError','error_code':'stage_failed'}) + s.sessions.release(s.sessions.get(one['session_id'])) + journal=Journal(s.root.parent/'journal.sqlite3') + journal.reserve(OWNER,one['id'],'colab',account,bundle['case_id'],'identity',{'unit':'CU','amount':15},None) + result=ColabNative(s,journal)._record(OWNER,one['id'],s.public_job(s.job(OWNER,one['id']))) + assert result['requested_gpu']=='A100' and result['assigned_gpu']=='G4' and result['gpu']=='G4' and result['gpu_name'] is None + assert result['diagnostics']['stage']=='session_bootstrap' + +@pytest.mark.parametrize('failure',['dead','stale','timeout']) +def test_plan_budget_and_unknown_cleanup_close_lease(rig,monkeypatch,failure): + s,b,clock,account,bundle=rig;state=ready(rig);one=native(rig) + state=s.sessions.save(state['id'],phase='bootstrap',bootstrap_plan_id=one['bootstrap_plan_id'],launch_at=clock[0]-(1801 if failure=='timeout' else 0)) + status={'phase':'running','alive':failure!='dead','progress_at':clock[0]-(121 if failure=='stale' else 0)} + monkeypatch.setattr(s,'_exec',lambda st,code:status if 'bootstrap-status.json' in code else {'clean':False}) + if failure=='stale': + from colab_service import BridgeError + for _ in range(2): + with pytest.raises(BridgeError) as caught:s.sessions.bootstrap(s.sessions.get(state['id'])) + s.sessions.record_fault(state,caught.value) + final=s.sessions.get(state['id']) + assert final['phase']=='closing' and final['last_tick']==state['last_tick'] + assert final['private_rpc_error']=={'bootstrap_probe':{'type':'progress_stale'}} + assert not s.job(OWNER,one['id'])['released'] + return + s.sessions.bootstrap(state) + final=s.sessions.get(state['id']);assert final['phase']=='closing' + assert final['bootstrap_diagnostics']['error_code']=={'dead':'bootstrap_process_lost','stale':'bootstrap_stalled','timeout':'bootstrap_timeout'}[failure] + assert not s.job(OWNER,one['id'])['released'] + + + + +def test_preopen_records_startup_telemetry_without_claiming_verified_gpu(rig,monkeypatch): + s,b,clock,account,bundle=rig;state=s.sessions.open(OWNER,account,15) + state=s.sessions.save(state['id'],runtime_id='fixture',deadline_epoch=clock[0]+21600) + def remote(st,code): + compile(code,'arm-probe','exec') + assert code.index('while not alive()') < code.index("raw=subprocess.check_output(['nvidia-smi'") + assert 'timeout=10' in code + return {'armed':True,'watchdog_identity':{'pid':1,'start_ticks':'42','deadline':1021600.0,'lock_dev':1,'lock_ino':2},'session_id':state['id'],'startup_telemetry':{'disk_free_gib':150.5,'python_version':'3.12.8','gpu_name':GPU,'vram_mib':97887,'raw':'secret'}} + monkeypatch.setattr(s,'_exec',remote) + result=s.sessions.arm(state) + assert result['watchdog_armed'] and result['startup_telemetry']=={'disk_free_gib':150.5,'python_version':'3.12.8','gpu_name':GPU,'vram_mib':97887} + assert result.get('gpu_name') is None + + +def test_queued_receipt_carries_current_session_bootstrap_stage(rig): + from compute_parity.colab import ColabNative + from compute_parity.journal import Journal + s,b,clock,account,bundle=rig;one=native(rig) + s.sessions.save(one['session_id'],phase='bootstrap',assigned_gpu='G4',bootstrap_diagnostics={'stage':'session_bootstrap','substage':'node_checkout'}) + journal=Journal(s.root.parent/'journal.sqlite3') + journal.reserve(OWNER,one['id'],'colab',account,bundle['case_id'],'identity',{'unit':'CU','amount':15},None) + result=ColabNative(s,journal)._record(OWNER,one['id'],s.public_job(one)) + assert result['diagnostics']=={'stage':'session_bootstrap','substage':'node_checkout'} + assert result['requested_gpu']=='A100' and result['assigned_gpu']=='G4' and result['gpu_name'] is None + +@pytest.mark.parametrize('late_lookup',[False,True]) +def test_cancelled_late_assignment_keeps_assigned_gpu_without_upload(rig,monkeypatch,late_lookup): + from colab_service import BridgeError + s,b,clock,account,bundle=rig;one=native(rig);original=s._call + def call(state,op,**kw): + if op=='runtime_allocate': + if late_lookup:raise BridgeError('allocation_uncertain',True) + s.sessions.close(OWNER) + return {'found':True,'runtime_id':kw['allocation_id'],'accelerator':'G4'} + if op=='runtime_lookup':return {'found':True,'runtime_id':kw['allocation_id'],'accelerator':'G4'} + return original(state,op,**kw) + monkeypatch.setattr(s,'_call',call) + s.sessions.tick_all() + if late_lookup:s.sessions.close(OWNER);s.sessions.tick_all() + state=s.sessions.get(one['session_id']);job=s.job(OWNER,one['id']) + assert state['released'] and state['assigned_gpu']=='G4' + assert job['released'] and job['requested_gpu']=='A100' and job['assigned_gpu']=='G4' and job['gpu']=='G4' and job.get('gpu_name') is None + assert not any(op=='upload' for op,kw in b.calls) + assert sum(op=='runtime_stop' for op,kw in b.calls)==1 + + +def test_r35_historical_session_gpu_is_assignment_only_with_runtime(rig,monkeypatch): + from compute_parity.colab import ColabNative + from compute_parity.journal import Journal + s,b,clock,account,bundle=rig;one=native(rig) + legacy={'id':one['session_id'],'phase':'closed','gpu':'G4','runtime_id':'historical-runtime'} + monkeypatch.setattr(s,'owner_session',lambda owner,sid:legacy if owner==OWNER else {}) + journal=Journal(s.root.parent/'journal.sqlite3') + journal.reserve(OWNER,one['id'],'colab',account,bundle['case_id'],'identity',{'unit':'CU','amount':15},None) + adapter=ColabNative(s,journal) + result=adapter._record(OWNER,one['id'],s.public_job({**one,'phase':'failed','released':True,'units_observed':0})) + assert result['assigned_gpu']=='G4' and result['gpu_name'] is None + legacy.pop('runtime_id') + result=adapter._record(OWNER,one['id'],s.public_job({**one,'phase':'failed','released':True,'units_observed':0})) + assert result['assigned_gpu'] is None and result['gpu'] is None + + +def test_close_racing_plan_failure_keeps_cancelled_receipt_and_owner_settings(rig,monkeypatch): + s,b,clock,account,bundle=rig;state=ready(rig);one=native(rig) + stale=s.sessions.save(state['id'],phase='bootstrap',bootstrap_plan_id=one['bootstrap_plan_id'],launch_at=clock[0]) + s.sessions.close(OWNER);s.sessions.settings(OWNER,{'idle_minutes':37}) + monkeypatch.setattr(s,'_exec',lambda st,code:{'clean':True}) + s.sessions.fail_plan(stale,{'stage':'session_bootstrap','error_code':'stage_failed'},'bootstrap_failed') + current=s.sessions.get(state['id']);job=s.job(OWNER,one['id']) + assert current['close_requested'] and current['settings']['idle_minutes']==37 and current['phase']=='closing' + assert job['phase']=='cancelled' and job['released'] and job['cancel_requested'] diff --git a/scripts/test_compute_r36b.py b/scripts/test_compute_r36b.py new file mode 100644 index 0000000..e8aea81 --- /dev/null +++ b/scripts/test_compute_r36b.py @@ -0,0 +1,71 @@ +"""Exact source overlay and scoped build-tool regressions; all offline.""" +import difflib,json,subprocess +from pathlib import Path +import pytest +from scripts import colab_session_dependencies as dep +from scripts.colab_session_diagnostics import failure_diagnostics,sanitize_diagnostics + +@pytest.fixture +def overlay(tmp_path,monkeypatch): + root=tmp_path/'repo';root.mkdir();registry=tmp_path/'registry';registry.mkdir() + old=b'first\nold\nlast\n';new=b'first\nnew\nlast\n' + (root/'file.py').write_bytes(old) + patch=''.join(difflib.unified_diff(old.decode().splitlines(True),new.decode().splitlines(True),fromfile='a/file.py',tofile='b/file.py')).encode() + (registry/'fix.patch').write_bytes(patch) + row=dict(repository='public-repo',commit='a'*40,path='file.py',upstream_sha256=dep.digest(old),pinned_sha256=dep.digest(new),patch='fix.patch',patch_sha256=dep.digest(patch)) + (registry/'registry.json').write_text(json.dumps([row])) + monkeypatch.setattr(dep.subprocess,'check_output',lambda *a,**kw:'a'*40+'\n') + return root,registry,row,old,new + +def apply(f,**changes): + root,registry,row,*_=f + args={k:row[k] for k in ('repository','commit')};args.update(root=root,relative=row['path'],pinned=row['pinned_sha256'],registry=registry);args.update(changes) + return dep.apply_overlay(**args) + +def test_overlay_apply_verify_exact_bytes(overlay): + assert apply(overlay) + assert (overlay[0]/'file.py').read_bytes()==overlay[4] + +@pytest.mark.parametrize('change',['upstream','result','repository','commit','path','head','patch','symlink']) +def test_overlay_rejects_wrong_identity_or_bytes(overlay,change,monkeypatch): + root,registry,row,old,new=overlay;changes={} + if change=='upstream':(root/'file.py').write_text('unknown source\n') + if change=='result': + row['pinned_sha256']='0'*64;(registry/'registry.json').write_text(json.dumps([row])) + if change in {'repository','commit'}:changes[change]='different' + if change=='path':changes['relative']='other.py' + if change=='head':monkeypatch.setattr(dep.subprocess,'check_output',lambda *a,**kw:'b'*40) + if change=='patch':(registry/'fix.patch').write_text('changed patch') + if change=='symlink': + (root/'file.py').rename(root/'real.py');(root/'file.py').symlink_to('real.py') + with pytest.raises(dep.OverlayMismatch) as caught:apply(overlay,**changes) + diagnostic=failure_diagnostics(caught.value,'node_checkout') + assert sanitize_diagnostics(diagnostic)['error_code']=='node_overlay_mismatch' + +def test_matching_pack_has_no_overlay_or_subprocess(overlay,monkeypatch): + root,registry,row,old,new=overlay;(root/'file.py').write_bytes(new) + (registry/'registry.json').unlink() + monkeypatch.setattr(dep.subprocess,'run',lambda *a,**kw:pytest.fail('No overlay for matching bytes')) + assert apply(overlay) is False + +def test_voice_build_constraint_is_scoped_and_pinned(tmp_path): + from scripts import colab_session_voice as voice + registry=json.loads(voice.REGISTRY.read_text()) + envs={x['provenance']['label']:x['build_constraint'] for x in registry['environments'].values()} + assert envs=={'local voice venv':'cython==3.2.5\nnumpy==1.26.4\npackaging==26.3\nsetuptools==70.2.0\nwheel==0.48.0\n','local voxcpm venv':'setuptools==70.2.0\n'} + assert all('--hash=sha256:' in x for x in registry['tool_requirements']) + args=['unrelated','command'];calls=[] + voice.run_command({},tmp_path,args,lambda *a,**k:calls.append(a),{}) + assert calls==[(args,)] + +def test_voice_build_refuses_changed_tool_pins(tmp_path): + from scripts import colab_session_voice as voice + with pytest.raises(voice.VoiceEnvironmentMismatch):voice.entry({'feature':'voice-speak','runtime_lock':{'voice':['pip==different']}},'voice') + +def test_registry_matches_frozen_disk_pin(): + row=json.loads((dep.REGISTRY/'registry.json').read_text())[0] + assert row['commit']=='4ee72c065db22c9d96c2427954dc69e7b908444b' + assert row['pinned_sha256']=='57a5ca6b4d3ea6c2306675235711ab82f7c3ceac6aab87441b7f9e357ccff425' + assert row['upstream_sha256']=='ea3d02e0f41dc6b59685fcf6de9217d4b7729766e05e44200433c74e75466a6a' + assert dep.digest((dep.REGISTRY/row['patch']).read_bytes())==row['patch_sha256'] + assert 'GPL-3.0' in (dep.REGISTRY/'NOTICE.md').read_text() diff --git a/scripts/test_compute_r36c.py b/scripts/test_compute_r36c.py new file mode 100644 index 0000000..60269b7 --- /dev/null +++ b/scripts/test_compute_r36c.py @@ -0,0 +1,97 @@ +import json,hashlib,subprocess +from pathlib import Path +from types import SimpleNamespace as NS +import pytest +from scripts.review_r36_support import rig,allocated,job +from scripts import colab_session_voice as voice +from scripts.colab_session_diagnostics import decode_tail,ERRORS,failure_diagnostics + +@pytest.mark.parametrize('verified,phase,assigned',[(False,'queued','G4'),(True,'failed','G4'),(False,'failed',None),(False,'queued',None)]) +def test_owner_gpu_projection_on_read(rig,verified,phase,assigned): + s,b,clock,account,initial=rig;st=allocated(rig,'bootstrap') + s.sessions.save(st['id'],assigned_gpu=assigned,gpu_name='NVIDIA RTX PRO 6000 Blackwell Server Edition' if verified else None) + j=job(rig,st['id'],phase,requested_gpu='A100') + result=s.snapshot('owner')['jobs'][0] + assert result['assigned_gpu']==assigned and result['gpu']==assigned + assert result['requested_gpu']=='A100' and bool(result['gpu_name'])==verified + assert s.project_session_gpu('different-owner',j)['assigned_gpu'] is None + assert s.job('owner',j['id'])['gpu']=='A100' # Read projection never rewrites history. + +@pytest.mark.parametrize('error',sorted(ERRORS)) +def test_tail_exact_error_vocabulary(error): + assert decode_tail(error+': [redacted]')==error+': [redacted]' + assert decode_tail('FORGED'+error+': [redacted]')=='' + + + +def test_voice_registry_has_no_home_paths_and_all_three_routes(): + text=voice.REGISTRY.read_text();r=json.loads(text) + assert '/home/' not in text + assert {(x['feature'],x['lock']) for x in r['entries']}=={('voice-speak','voice'),('voxcpm-tts','voice'),('voxcpm-tts','voxcpm')} + assert r['interpreter']['version_info']==[3,11,15] + assert len(r['interpreter']['sha256'])==64 + assert all(x['install_mode']=='no-deps' for x in r['environments'].values()) + assert next(x for x in r['environments'].values() if x['provenance']['label']=='local voice venv')['last']==['onnxruntime'] + + +@pytest.mark.parametrize('mutation',['none','version','binary','missing_dist','extra_dist','duplicate_dist','hash','extra_file','missing_file','symlink']) +def test_voice_selfcheck_exact_distribution_set_and_overlap(tmp_path,monkeypatch,mutation): + file=tmp_path/'shared/x.py';file.parent.mkdir();file.write_bytes(b'known') + binary=tmp_path/'python';binary.write_bytes(b'python') + expected={'dists':{'one':'1'},'overlap_roots':['shared'],'overlap_files':{'shared/x.py':voice.sha(file)}} + registry={'interpreter':{'version_info':[3,11,15],'version':'build','sha256':voice.sha(binary)}} + distributions=[NS(metadata={'Name':'one'},version='1')] + if mutation=='missing_dist':distributions=[] + if mutation=='extra_dist':distributions.append(NS(metadata={'Name':'other'},version='1')) + if mutation=='duplicate_dist':distributions*=2 + if mutation=='hash':file.write_bytes(b'changed') + if mutation=='extra_file':(file.parent/'extra').touch() + if mutation=='missing_file':file.unlink() + if mutation=='symlink':file.rename(tmp_path/'outside');file.symlink_to(tmp_path/'outside') + if mutation=='binary':binary.write_bytes(b'changed') + monkeypatch.setattr(voice,'sys',NS(version_info=(3,11,14) if mutation=='version' else (3,11,15),version='build',executable=str(binary))) + monkeypatch.setattr(voice,'sysconfig',NS(get_path=lambda _:str(tmp_path))) + monkeypatch.setattr(voice,'importlib',NS(metadata=NS(distributions=lambda **kw:distributions))) + if mutation=='none':voice.verify_environment(registry,expected) + else: + with pytest.raises(voice.VoiceEnvironmentMismatch) as e:voice.verify_environment(registry,expected) + assert failure_diagnostics(e.value,'runtime_lock')['error_code']=='voice_env_mismatch' + +def test_runtime_tool_install_has_hashes_and_never_user_uv_store(tmp_path,monkeypatch): + root=tmp_path/'voice-tools';py=root/'python/build/bin/python3.11';calls=[] + registry={'interpreter':{'build_label':'build','sha256':hashlib.sha256(b'python').hexdigest()},'tool_requirements':['uv==0.11.20 --hash=sha256:'+'a'*64]} + def run(args,**kw): + calls.append((args,kw)) + if 'venv' in args: + p=Path(args[-1])/'bin/python';p.parent.mkdir(parents=True);p.touch() + if '3.11.15' in args:py.parent.mkdir(parents=True);py.write_bytes(b'python') + py.parent.mkdir(parents=True);py.write_bytes(b'python') + registry['interpreters']={'comfy':{'version':'3.12.13'},'voice':{'version':'3.11.15'}} + monkeypatch.setattr(voice,'provision_python',lambda *a:str(py)) + monkeypatch.setattr(voice,'verify_python',lambda *a:None) + voice.tools(tmp_path,registry,run,{}) + assert any('--require-hashes' in args for args,kw in calls) + assert not any('python' in args and 'install' in args for args,kw in calls) # shared archive provisioner, no user uv installation + for args,kw in calls: + for key in ['UV_PYTHON_INSTALL_DIR','UV_CACHE_DIR','UV_TOOL_DIR','UV_PYTHON_BIN_DIR','PIP_CACHE_DIR']: + assert Path(kw['env'][key]).is_relative_to(root) + + + + +def test_missing_voxcpm_wheel_fails_closed(tmp_path, monkeypatch): + registry=json.loads(voice.REGISTRY.read_text()) + environment=next(v for v in registry['environments'].values() if v.get('package_wheel')) + package=environment['package_wheel'] + assert not (voice.REGISTRY.parent / package['filename']).exists() + pins=['unit-test==1'] + plan={'feature':'voxcpm-tts','runtime_lock':{'voxcpm':pins}} + (tmp_path/'voxcpm-constraints.txt').write_text('\n'.join(pins)+'\n') + expected={'last':[], 'build_constraint':'', 'package_wheel':package} + monkeypatch.setattr(voice,'entry',lambda *args:(registry,expected,'\n'.join(pins)+'\n')) + monkeypatch.setattr(voice,'tools',lambda *args:('test-python','test-tool',{})) + monkeypatch.setattr(voice,'verify_python',lambda *args:None) + calls=[] + with pytest.raises(voice.VoiceEnvironmentMismatch,match='voice_env_mismatch'): + voice.run_command(plan,tmp_path,[str(tmp_path/'voxcpm-venv/bin/python'),'-m','pip','install','-r',str(tmp_path/'voxcpm-constraints.txt')],lambda args,**kw:calls.append(args),{}) + assert not any('--no-index' in args for args in calls) diff --git a/scripts/test_compute_r37.py b/scripts/test_compute_r37.py new file mode 100644 index 0000000..593ebec --- /dev/null +++ b/scripts/test_compute_r37.py @@ -0,0 +1,199 @@ +"""P1m2 admission, absent-job closure, frozen archive and bounded tick faults.""" +import base64,copy,hashlib,io,json,tarfile,uuid +from pathlib import Path +import pytest +from scripts.test_compute_r35 import rig,OWNER,oid,native +from colab_service import ColabError,BridgeError,encoded +from compute_parity.colab import ColabNative +from compute_parity.journal import Journal +from compute_parity.runtime import Runtime +from colab_inputs import input_name,preflight +from scripts.colab_session_archive import pack,extract + +def adapter(rig): + s,b,c,a,bundle=rig + return ColabNative(s,Journal(s.root.parent/'compute-parity/journal.sqlite3',colab_state_path=s.root/'state.sqlite3')) +def inputs(bundle):return {i['slot']:Path(i['local_path']).read_bytes() for i in bundle['inputs']} +def reserve(a,rig,rid=None): + s,b,c,account,bundle=rig;rid=rid or oid() + a.journal.reserve(OWNER,rid,'colab',account,bundle['case_id'],'identity',{'unit':'CU','amount':15}) + a.journal.update(OWNER,rid,state='submission_uncertain') + return rid + +@pytest.mark.parametrize('code',['unsupported_input_format','input_too_large','invalid_manifest','invalid_media_image','account_unavailable','insufficient_balance','lane_busy','unexpected']) +def test_live_predurable_failure_is_rejected_and_reserved_cu_released(rig,monkeypatch,code): + from colab_inputs import ADMISSION_MESSAGES + s,b,c,account,bundle=rig;a=adapter(rig);rid=oid() + def reject(*args,**kw): + if code=='unexpected':raise RuntimeError('private diagnostic must not escape') + raise ColabError(ADMISSION_MESSAGES[code]) + monkeypatch.setattr(s,'_submit',reject) + result=a.submit(OWNER,rid,bundle,inputs(bundle),account_id=account,quote={'unit':'CU','amount':15}) + receipt=Runtime.receipt(result) + assert receipt['state']=='rejected' and receipt['actual_cost']=={'unit':'CU','amount':0} and receipt['cancel_supported'] is False + assert receipt['diagnostics']['stage']=='admission' and receipt['error']['code']==('admission_unavailable' if code=='unexpected' else code) + assert a.journal.ledger(OWNER)['colab']['unsettled_reserved']==0 + assert s.find_job(OWNER,rid) is None and not any(op=='runtime_allocate' for op,kw in b.calls) + assert 'private diagnostic' not in json.dumps(receipt) + if code=='unexpected':assert receipt['diagnostics']['error_type']=='RuntimeError' + +def test_predurable_bridge_exception_has_safe_http_diagnostic(rig,monkeypatch): + s,b,c,account,bundle=rig;a=adapter(rig) + def reject(*args,**kw):raise BridgeError('timeout',diagnostics={'http_status':503,'message':'private URL'}) + monkeypatch.setattr(s,'_submit',reject) + result=a.submit(OWNER,oid(),bundle,inputs(bundle),account_id=account,quote={'unit':'CU','amount':15}) + assert result['state']=='rejected' and result['error']['code']=='admission_unavailable' + assert result['diagnostics']['http_status']==503 and 'private URL' not in json.dumps(result) + +@pytest.mark.parametrize('operation',['poll','recover','cancel']) +def test_p1m2_uncertain_without_job_closes_by_owner_product_read(rig,operation): + s,b,c,account,bundle=rig;a=adapter(rig);rid=reserve(a,rig,'00000000-0000-4000-8000-00000000d002') + assert Runtime.receipt(a.journal.get(OWNER,rid))['downstream_id']==rid + assert not (s.root/'jobs'/rid).exists() + receipt=Runtime.receipt(getattr(a,operation)(OWNER,rid)) + assert receipt['state']=='closed_no_execution_evidence' and receipt['actual_cost']['amount']==0 and not receipt['cancel_supported'] + assert a.poll(OWNER,rid)==getattr(a,operation)(OWNER,rid) + a.journal.check_admission(OWNER,'colab',bundle['case_id']) + assert not any(op in {'runtime_allocate','runtime_stop','upload','remote_exec'} for op,kw in b.calls) + +@pytest.mark.parametrize('lock',['request','account']) +def test_recovery_does_not_close_in_flight_submit(rig,lock): + s,b,c,account,bundle=rig;a=adapter(rig);rid=reserve(a,rig) + with (s.native_submission_guard(OWNER,rid) if lock=='request' else s.account_guard(account)): + result=a.poll(OWNER,rid) + assert result['state']=='submission_uncertain' and result['diagnostics']['error_code']=='admission_in_flight' + assert a.poll(OWNER,rid)['state']=='closed_no_execution_evidence' + +def test_lookup_failure_remains_uncertain(rig,monkeypatch): + s,b,c,account,bundle=rig;a=adapter(rig);rid=reserve(a,rig) + def broken(*a):raise OSError('private database path') + monkeypatch.setattr(s,'find_job',broken) + result=a.poll(OWNER,rid) + assert result['state']=='submission_uncertain' and result['diagnostics']['error_code']=='admission_lookup_failed' + +def test_request_input_rejections_do_not_stop_other_cases(rig): + a=adapter(rig) + for _ in range(2): + rid=reserve(a,rig);a.journal.update(OWNER,rid,state='rejected',failure_kind='admission',root_cause='invalid_input',actual_cost={'unit':'CU','amount':0}) + a.journal.check_admission(OWNER,'colab','video-replace.realistic.example-b') + + +def test_signature_mismatch_and_invalid_preview_are_rejected(rig): + s,b,c,account,bundle=rig;raw=inputs(bundle)['reference'] + with pytest.raises(ColabError,match='副檔名'):input_name('wrong.mp4',raw,'image') + with pytest.raises(ColabError):input_name('unknown',b'garbage','image') + broken=inputs(bundle);broken['reference']=b'garbage' + with pytest.raises(ColabError):preflight(bundle,broken,s.root) + +def test_archive_is_deterministic_and_verified_before_publication(tmp_path): + pairs=[('runner/x.py',b'code'),('bootstrap.json',b'{}')];raw=pack(pairs);assert raw==pack(list(reversed(pairs))) + expected=[{'path':n,'size':len(v),'sha256':hashlib.sha256(v).hexdigest()} for n,v in pairs] + p=tmp_path/'archive';p.write_bytes(raw);root=tmp_path/'remote';root.mkdir() + assert extract(p,root,expected,hashlib.sha256(raw).hexdigest()) + assert extract(p,root,expected,hashlib.sha256(raw).hexdigest()) + expected[-1]['sha256']='0'*64;(root/'runner/x.py').write_bytes(b'existing') + with pytest.raises(ValueError):extract(p,root,expected,hashlib.sha256(raw).hexdigest()) + assert (root/'runner/x.py').read_bytes()==b'existing' + +@pytest.mark.parametrize('kind',['symlink','hardlink','absolute','parent','duplicate','extra','wrong_size','wrong_hash','directory']) +def test_archive_rejects_unsafe_members(tmp_path,kind): + out=io.BytesIO();name={'absolute':'/x','parent':'../x'}.get(kind,'x');entry=tarfile.TarInfo(name);entry.size=1 + if kind in {'symlink','hardlink','directory'}:entry.type={'symlink':tarfile.SYMTYPE,'hardlink':tarfile.LNKTYPE,'directory':tarfile.DIRTYPE}[kind];entry.linkname='/outside';entry.size=0 + with tarfile.open(fileobj=out,mode='w') as tar: + tar.addfile(entry,io.BytesIO(b'x')) + if kind=='duplicate':tar.addfile(entry,io.BytesIO(b'x')) + raw=out.getvalue();p=tmp_path/'archive';p.write_bytes(raw);root=tmp_path/'remote';root.mkdir() + expected=[{'path':name if kind in {'absolute','parent'} else 'y' if kind=='extra' else 'x','size':2 if kind=='wrong_size' else 1,'sha256':'0'*64 if kind=='wrong_hash' else hashlib.sha256(b'x').hexdigest()}] + with pytest.raises(ValueError):extract(p,root,expected,hashlib.sha256(raw).hexdigest()) + assert not list(root.iterdir()) + +@pytest.mark.parametrize('code',['timeout','transport_failed']) +@pytest.mark.parametrize('stage',['observe','heartbeat','upload']) +def test_transient_tick_fault_retries_bounded_without_renewing_heartbeat(rig,monkeypatch,stage,code): + s,b,c,account,bundle=rig;st=s.sessions.open(OWNER,account,15);s.sessions.tick_all();st=s.sessions.get(st['id']);last=st['last_tick'] + def tick(state):s.sessions.operation(state,stage);raise BridgeError(code) + monkeypatch.setattr(s.sessions,'tick',tick) + for n in range(2): + c[0]+=30;s.sessions.tick_all();st=s.sessions.get(st['id']) + assert st['last_tick']==last and st['fault']['count']==n+1 and st['fault']['code']==code + assert (st['phase']=='closing')==(n==1) + assert s.sessions.public(st)['fault']==st['fault'] + +@pytest.mark.parametrize('stage,ambiguous',[('upload',True),('attach',False),('bootstrap',False),('allocation',False),('release',False)]) +def test_nonidempotent_or_ambiguous_tick_fault_closes(rig,monkeypatch,stage,ambiguous): + s,b,c,account,bundle=rig;st=s.sessions.open(OWNER,account,15);s.sessions.tick_all() + def tick(state):s.sessions.operation(state,stage);raise BridgeError('timeout',ambiguous) + monkeypatch.setattr(s.sessions,'tick',tick);s.sessions.tick_all() + assert s.sessions.get(st['id'])['phase']=='closing' + +def test_session_frozen_set_uses_one_upload(rig): + s,b,c,account,bundle=rig;st=s.sessions.open(OWNER,account,15);s.sessions.tick_all();s.sessions.tick_all() + st=s.sessions.get(st['id']);assert st['archive_uploaded'] and st['upload_index']==len(st['uploads']) + uploads=[kw for op,kw in b.calls if op=='upload'];assert len(uploads)==1 and uploads[0]['remote_path'].endswith('/bootstrap.tar') + +def test_faulted_upload_cannot_extend_remote_heartbeat_beyond_last_success(rig,monkeypatch): + s,b,c,account,bundle=rig;st=s.sessions.open(OWNER,account,15);s.sessions.tick_all() + st=s.sessions.get(st['id']);last=st['last_tick'];codes=[];original=s._exec + def execute(state,code,*a,**kw): + if "(p/'heartbeat').write_text" in code:codes.append(code) + return original(state,code,*a,**kw) + original_call=s._call + def call(state,operation,*a,**kw): + if operation=='upload':raise BridgeError('timeout') + return original_call(state,operation,*a,**kw) + monkeypatch.setattr(s,'_exec',execute);monkeypatch.setattr(s,'_call',call) + for _ in range(2):c[0]+=30;s.sessions.tick_all() + assert len(codes)==2 and all("(p/'heartbeat').write_text(str("+repr(last)+"))" in code for code in codes) + assert s.sessions.get(st['id'])['last_tick']==last + +def test_owner_router_get_closes_original_receipt_and_preview_capacity(rig): + from compute_routing import ComputeRouter,ComputeAdapter + s,b,c,account,bundle=rig;a=adapter(rig);rid=reserve(a,rig) + def forbidden(*a,**kw):raise AssertionError('No submission/provider call during receipt recovery') + inspect=lambda *a,**kw:{'eligible':True,'estimated_cost':15,'currency':'compute_units','reasons':[]} + router=ComputeRouter(s.root.parent/'compute-routing.sqlite3',{'colab':ComputeAdapter(inspect,forbidden,lambda o,r:Runtime.receipt(a.poll(o,r)),forbidden)},clock=s.clock) + with router._db() as db: + db.execute('INSERT INTO compute_requests VALUES (?,?,?,?,?,?,?,?,?,?,?)',(OWNER,rid,'hash','colab','colab','submission_uncertain','{}','{}',json.dumps({'state':'submission_uncertain','downstream_id':rid,'cancel_supported':True}),c[0],c[0])) + receipt=router.status(OWNER,rid,refresh=True) + assert receipt['state']=='closed_no_execution_evidence' and receipt['actual_cost']['amount']==0 and receipt['cancel_supported'] is False + assert receipt['retry_submission_allowed'] is False + assert router._get(OWNER,rid)['state']=='closed_no_execution_evidence' + with router._db() as db: + assert db.execute("SELECT count(*) FROM compute_requests WHERE lane='colab' AND state NOT IN ('closed_no_execution_evidence','rejected','completed','failed','cancelled')").fetchone()[0]==0 + assert not (s.root/'jobs'/rid).exists() + +def test_fault_streak_time_limit_checked_before_renewal(rig): + s,b,c,account,bundle=rig;st=s.sessions.open(OWNER,account,15);s.sessions.tick_all() + st=s.sessions.save(st['id'],fault_streak=1,fault_since=c[0]-91) + b.calls.clear();s.sessions.tick_all();st=s.sessions.get(st['id']) + assert st['phase']=='closed' and st['reason']=='watchdog_state_lost' + assert not any(op=='remote_exec' and "'heartbeat':True" in kw.get('code','') for op,kw in b.calls) + +def test_unknown_fault_never_leaks_exception_message(rig,monkeypatch): + s,b,c,account,bundle=rig;st=s.sessions.open(OWNER,account,15);s.sessions.tick_all() + def broken(state):s.sessions.operation(state,'upload');raise OSError('private://owner/path?secret=value') + monkeypatch.setattr(s.sessions,'tick',broken);s.sessions.tick_all();state=s.sessions.get(st['id']) + assert state['fault']['code']=='OSError' and state['phase']=='closing' + assert 'secret' not in json.dumps(s.sessions.public(state)) + + + +@pytest.mark.parametrize('feature,label,expected',[('voice-speak','voice','voice_imports'),('voxcpm-tts','voxcpm','voxcpm_imports'),('voxcpm-tts','voice','speaker_imports')]) +def test_real_import_failures_are_fixed_substages_no_ready(tmp_path,monkeypatch,feature,label,expected): + from scripts import colab_session_voice as voice + import builtins + real=builtins.__import__ + def missing(name,*a,**kw): + if name=='pkg_resources':raise ImportError('private path must not survive') + return real(name,*a,**kw) + monkeypatch.setattr(builtins,'__import__',missing) + with pytest.raises(voice.VoiceEnvironmentMismatch) as e:voice.import_smoke({'dists':{}},tmp_path,label,feature) + assert e.value.substage==expected and str(e.value)=='voice_env_mismatch' + assert not list(tmp_path.glob('*ready.json')) + +def test_voice_heartbeat_telemetry_redacts_unrecognized_values(): + from scripts.colab_session_diagnostics import telemetry + value={'voice_environments':{'voice':{'python_build':'main Jun 2 2026','python_version':'3.11.15','torch_version':'2.8.0+cu128','onnx_providers':['CPUExecutionProvider'],'imports_ready':True},'private-path':{'token':'secret'}}} + assert telemetry(value)=={'voice_environments':{'voice':value['voice_environments']['voice']}} + value['voice_environments']['voice'].update(python_build='/home/private',onnx_providers=['private-provider']) + safe=telemetry(value)['voice_environments']['voice'];assert 'python_build' not in safe and 'onnx_providers' not in safe diff --git a/scripts/test_compute_r38.py b/scripts/test_compute_r38.py new file mode 100644 index 0000000..e33bc55 --- /dev/null +++ b/scripts/test_compute_r38.py @@ -0,0 +1,163 @@ +"""P1m3 failure boundaries: mocks and disk-only fixtures; never call a provider.""" +import json,subprocess,uuid +from pathlib import Path +import pytest +from review_r37_fixture import rig,reserve,submit,session +from colab_service import BridgeError,ColabError +from scripts.colab_transport_diagnostics import capture,sanitize + +@pytest.mark.parametrize('written',[False,True]) +@pytest.mark.parametrize('kind',['TimeoutError','ConnectionResetError']) +def test_ambiguous_heartbeat_survives_once_then_proves_identity(rig,written,kind): + r=rig;receipt=submit(r);st=r.s.sessions.get(r.s.job(r.owner,receipt['request_id'])['session_id']) + r.s.sessions.tick_all();st=r.s.sessions.get(st['id']);last=st['last_tick'];hits=[];writes=[] + def fault(op,kw): + if op=='remote_exec' and "'heartbeat':True" in kw['code'] and not hits: + hits.append(written) + if written:writes.append(last) + raise BridgeError('execution_uncertain',True,{'error_type':kind,'transport_phase':'wait'}) + if op=='remote_exec' and "'heartbeat':True" in kw['code']:writes.append(last) + r.b.hook=fault;r.t[0]+=10;r.s.sessions.tick_all();st=r.s.sessions.get(st['id']) + assert st['phase']=='uploading' and st['last_tick']==last and st['fault']['error_type']==kind + assert writes==([last] if written else []) + r.t[0]+=11;r.s.sessions.tick_all();st=r.s.sessions.get(st['id']) + assert st['phase']=='uploading' and st['fault_streak']==0 and st['last_tick']==r.t[0] + assert r.s.job(r.owner,receipt['request_id'])['phase']=='queued' + assert writes==[last]*(2 if written else 1) + codes=[kw['code'] for op,kw in r.b.calls if op=='remote_exec' and "'heartbeat':True" in kw['code']] + assert len(codes)==2 and all('assert actual==expected' in c and "proc[19]==actual['start_ticks']" in c for c in codes) + +@pytest.mark.parametrize('stage',['heartbeat','bootstrap_probe']) +def test_second_ambiguous_probe_fault_closes_without_renewal(rig,monkeypatch,stage): + r=rig;st=session(r);last=st['last_tick'] + def fail(state):r.s.sessions.operation(state,stage);raise BridgeError('execution_uncertain',True) + monkeypatch.setattr(r.s.sessions,'tick',fail) + for n in (1,2): + r.t[0]+=20;r.s.sessions.tick_all();st=r.s.sessions.get(st['id']) + assert st['last_tick']==last and st['fault_streak']==n + assert (st['phase']=='closing')==(n==2) + +@pytest.mark.parametrize('stage',['bootstrap','attach','upload','arm','release']) +def test_ambiguous_mutation_is_never_retried(rig,monkeypatch,stage): + r=rig;st=session(r);calls=[] + def fail(state):calls.append(stage);r.s.sessions.operation(state,stage);raise BridgeError('execution_uncertain',True) + monkeypatch.setattr(r.s.sessions,'tick',fail);r.s.sessions.tick_all() + assert calls==[stage] and r.s.sessions.get(st['id'])['phase']=='closing' + +def test_fault_receipt_preserves_system_cause(rig): + r=rig;receipt=submit(r);job=r.s.job(r.owner,receipt['request_id']);r.s.sessions.tick_all();st=r.s.sessions.get(job['session_id']) + fault={'stage':'heartbeat','code':'execution_uncertain','error_type':'ReadTimeout','http_status':504,'transport_phase':'read','timeout_kind':'read','ambiguous':True,'private':'never emitted'} + st=r.s.sessions.save(st['id'],phase='closing',reason='watchdog_state_lost',close_requested=True,fault=fault) + r.s.sessions.release(st);got=r.a.poll(r.owner,job['id']) + assert got['state']=='failed' and got['diagnostics']=={'stage':'session_fault','substage':'heartbeat','error_code':'execution_uncertain','error_type':'ReadTimeout','http_status':504,'transport_phase':'read','timeout_kind':'read','ambiguous':True} + from compute_parity.runtime import Runtime + from compute_routing import _public_receipt + assert _public_receipt(Runtime.receipt(got))['diagnostics']==got['diagnostics'] + assert 'private' not in json.dumps(got) + +def test_transport_diagnostics_never_include_exception_text(): + e=TimeoutError('secret URL and credential');e.status_code=504 + got=capture(e);assert got=={'error_type':'TimeoutError','transport_phase':'wait','timeout_kind':'execution','http_status':504} + assert sanitize({**got,'url':'secret','error_type':'private-name','http_status':True})=={'transport_phase':'wait','timeout_kind':'execution'} + +def test_archive_durable_timestamps(rig): + r=rig;st=r.s.sessions.open(r.owner,r.account,15) + for _ in range(4):r.s.sessions.tick_all();r.t[0]+=10 + st=r.s.sessions.get(st['id']) + assert st['upload_started_at']<=st['upload_completed_at']<=st['digest_verified_at'] + assert len([1 for op,_ in r.b.calls if op=='upload'])==1 + +@pytest.mark.parametrize('failure',['account_authorization','invalid_input']) +def test_confirm_foreign_owner_can_claim_legacy_orphan_before_account_validation(rig,failure): + r=rig;rid=reserve(r);body={'request_id':rid,'account_id':r.account,'gpu':'A100','max_units':20,'max_minutes':60,'job':{'type':'image','prompt':'offline'},'files':[]} + if failure=='invalid_input': + body['account_id']=r.s.create_account('another-owner','offline')['id'];body['files']=[{'name':'invalid.exe','data':''}] + with pytest.raises(ColabError):r.s.submit('another-owner',body) + with r.s.db() as db:assert db.execute('SELECT owner FROM request_claims WHERE id=?',(rid,)).fetchone() is None + for fn in [r.a.poll,r.a.cancel,r.a.recover]:assert fn(r.owner,rid)['state']=='closed_no_execution_evidence' + assert r.j.ledger(r.owner)['colab']['unsettled_reserved']==0 + assert not r.s.find_job(r.owner,rid) and not any(op=='runtime_allocate' for op,_ in r.b.calls) + +def test_session_controls(): + subprocess.run(['node',str(Path(__file__).with_name('test_session_controls_r38.js'))],check=True) + +def test_real_heartbeat_code_checks_lock_process_identity(tmp_path,capsys): + import os,fcntl + from scripts.colab_session_watchdog import heartbeat + sid=str(uuid.uuid4());root=tmp_path/sid;root.mkdir() + lock=os.open(root/'watchdog.lock',os.O_CREAT|os.O_RDWR,0o600) + try: + fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB);st=os.fstat(lock) + identity={'pid':os.getpid(),'start_ticks':Path('/proc/self/stat').read_text().rsplit(')',1)[1].split()[19],'deadline':12345,'lock_dev':st.st_dev,'lock_ino':st.st_ino} + (root/'watchdog.json').write_text(json.dumps({k:v for k,v in identity.items() if not k.startswith('lock_')})) + code=heartbeat(sid,identity,1000).replace('/content/castle-sessions/'+sid,str(root)) + exec(compile(code,'offline-heartbeat','exec'),{}) + assert (root/'heartbeat').read_text()=='1000' + identity['start_ticks']='wrong' + with pytest.raises(AssertionError):exec(compile(heartbeat(sid,identity,2000).replace('/content/castle-sessions/'+sid,str(root)),'offline-heartbeat','exec'),{}) + assert (root/'heartbeat').read_text()=='1000' + finally:os.close(lock) + +def test_retry_budget_does_not_outlive_fault_window(rig): + r=rig;st=session(r);st=r.s.sessions.save(st['id'],fault_since=r.t[0]-80,fault_streak=1) + r.s._exec(st,"print('WEB_COMFYUI_JSON={}')") + op,kw=r.b.calls[-1];assert kw['_timeout_seconds']==10 and kw['timeout_seconds']==10 + r.t[0]+=11 + with pytest.raises(BridgeError):r.s._exec(st,"print('WEB_COMFYUI_JSON={}')") + + +def test_job_progress_probe_ambiguous_is_bounded(rig): + r=rig;receipt=submit(r);job=r.s.job(r.owner,receipt['request_id']);st=r.s.sessions.get(job['session_id']) + r.s.sessions.tick_all();st=r.s.sessions.get(st['id']);last=st['last_tick'] + job=r.s.update(job['id'],phase='running',runtime_id=st['runtime_id'],deadline_epoch=r.t[0]+1000,manifest_sha256='0'*64,launch_requested_at=r.t[0]) + def fail(op,kw): + if op=='remote_exec':raise BridgeError('execution_uncertain',True,{'error_type':'ConnectionResetError','transport_phase':'read'}) + r.b.hook=fail + for n in (1,2): + r.s.tick(r.s.job(r.owner,job['id']));st=r.s.sessions.get(st['id']) + assert st['last_tick']==last and (st['phase']=='closing')==(n==2) + assert st['fault']['stage']=='job_probe' + +@pytest.mark.parametrize('point',['execute','transport']) +def test_real_bridge_wraps_only_safe_exception_metadata(tmp_path,point): + from types import SimpleNamespace + from contextlib import contextmanager + from scripts.colab_bridge import Bridge as RemoteBridge,BridgeError as RemoteError + class ReadTimeout(Exception):pass + error=ReadTimeout('private content must never appear');error.response=SimpleNamespace(status_code=503) + class Runtime: + def __init__(self,*a,**kw):pass + def execute_code(self,*a,**kw):raise error + def stop(self,**kw):pass + @contextmanager + def transport(): + if point=='transport':raise error + yield + bridge=object.__new__(RemoteBridge);bridge.sdk=SimpleNamespace(Runtime=Runtime,execution_transport=transport) + bridge.runtime=lambda rid:{'url':'offline','token':'offline'} + with pytest.raises(RemoteError) as caught:bridge.remote_exec({'runtime_id':str(uuid.uuid4()),'code':'pass'}) + assert caught.value.ambiguous and caught.value.code=='execution_uncertain' + assert caught.value.diagnostics=={'error_type':'ReadTimeout','transport_phase':'read','timeout_kind':'read','http_status':503} + assert 'private content' not in json.dumps(caught.value.public()) + +def test_wrong_watchdog_runtime_cannot_renew(rig): + r=rig;st=session(r);last=st['last_tick'];r.s.sessions.save(st['id'],runtime_id='replacement') + r.t[0]+=10;r.s.sessions.tick_all();st=r.s.sessions.get(st['id']) + assert st['last_tick']==last and st['phase']=='closing' + assert not any(op=='remote_exec' for op,_ in r.b.calls) + +def test_ambiguous_bootstrap_launch_is_dispatched_once(rig): + r=rig;job=submit(r);sid=r.s.job(r.owner,job['request_id'])['session_id'];attempts=[] + def hook(op,kw): + if op=='remote_exec' and "bootstrap-launch.tmp" in kw['code']: + attempts.append(kw);raise BridgeError('execution_uncertain',True) + r.b.hook=hook + for _ in range(8):r.s.sessions.tick_all();r.t[0]+=10 + assert len(attempts)==1 and r.s.sessions.get(sid)['phase']=='closed' + +def test_sweeper_preserves_terminal_fault_in_receipt(rig): + r=rig;receipt=submit(r);job=r.s.job(r.owner,receipt['request_id']);r.s.sessions.tick_all();st=r.s.sessions.get(job['session_id']) + fault={'stage':'heartbeat','code':'execution_uncertain','error_type':'TimeoutError','ambiguous':True} + r.s.sessions.save(st['id'],phase='closing',close_requested=True,terminal_fault=fault) + r.s.sessions.sweep_leases();got=r.a.poll(r.owner,job['id']) + assert got['state']=='failed' and got['diagnostics']['stage']=='session_fault' and got['diagnostics']['error_type']=='TimeoutError' diff --git a/scripts/test_compute_r39.py b/scripts/test_compute_r39.py new file mode 100644 index 0000000..c7e21e1 --- /dev/null +++ b/scripts/test_compute_r39.py @@ -0,0 +1,136 @@ +"""r39 T2/T3/T4/T5: mocked subprocess/network only; real parser/privacy boundaries.""" +import copy,hashlib,io,json,subprocess,tarfile +from pathlib import Path +from types import SimpleNamespace as NS +import pytest +from scripts import colab_session_voice as v,colab_session_diagnostics as d +from scripts.colab_remote import native_runner as runner +ROOT=Path(__file__).resolve().parents[1] + +def registry():return json.loads(v.REGISTRY.read_text()) + +@pytest.mark.parametrize('kind',['comfy','voice']) +def test_python_archive_and_executable_hashes_fail_closed(tmp_path,monkeypatch,kind): + pin=registry()['interpreters'][kind];raw=b'bad';pin.update(bytes=len(raw)) + monkeypatch.setattr(v.urllib.request,'urlopen',lambda *a,**k:io.BytesIO(raw)) + with pytest.raises(v.PythonMismatch):v.provision_python(tmp_path,pin,lambda *a,**k:pytest.fail('exec before hash')) + assert list((tmp_path/'python-builds').iterdir())==[] + +def test_provision_verifies_archive_binary_and_version(tmp_path,monkeypatch): + pin=registry()['interpreters']['comfy'];buf=io.BytesIO();payload=b'python' + with tarfile.open(fileobj=buf,mode='w:gz') as source: + info=tarfile.TarInfo(pin['executable']);info.size=len(payload);source.addfile(info,io.BytesIO(payload)) + raw=buf.getvalue();pin.update(bytes=len(raw),sha256=hashlib.sha256(raw).hexdigest(),executable_sha256=hashlib.sha256(payload).hexdigest()) + monkeypatch.setattr(v.urllib.request,'urlopen',lambda *a,**k:io.BytesIO(raw)) + called=[] + def run(*a,**k):called.append(a);return NS(stdout='3.12.13\n') + python=v.provision_python(tmp_path,pin,run);assert Path(python).read_bytes()==payload and len(called)==2 + Path(python).write_bytes(b'changed') + with pytest.raises(v.PythonMismatch):v.provision_python(tmp_path,pin,run) + + + + + +@pytest.mark.parametrize('raw,forbidden,replacement',[ + ('https://example.invalid/?secret=abc','example.invalid',''), + ('/home/private/folder/file.txt','/home',''), + ('file=/home/private/folder/file.txt','/home',''), + ('file=C:\\Users\\private\\file','Users',''), + ('person@example.invalid','person',''), + ('0123456789abcdef'*4,'0123456789',''), + ('abCDefGHIJKL0123+/xyz'*3,'abCDef',''), + ('C:\\Users\\private\\file','Users','')]) +def test_excerpt_masks_each_class(raw,forbidden,replacement): + value=d.stderr_excerpt(raw);assert forbidden not in value and replacement in value + +def test_excerpt_bounds_and_public_sanitizer(): + raw='\n'.join('line '+str(i)+' '+('x '*300) for i in range(30));value=d.stderr_excerpt(raw) + assert len(value.splitlines())==12 and all(len(x)<=200 for x in value.splitlines()) + assert 'private_bootstrap_stderr' not in d.sanitize_diagnostics({'private_bootstrap_stderr':value}) + from compute_parity.adapters import public + from compute_routing import _public_receipt + receipt={'state':'failed','private_bootstrap_stderr':value} + assert 'private_bootstrap_stderr' not in public(receipt) + assert 'private_bootstrap_stderr' not in _public_receipt(receipt) + +@pytest.mark.parametrize('label',sorted(d.COMMANDS)) +def test_command_exit_distribution_survive(label): + e=subprocess.CalledProcessError(1,['private']);e.command_label=label;e.failing_distribution='numpy==1.26.4' + result=d.failure_diagnostics(e,'runtime_lock') + assert result['command_label']==label and result['exit_code']==1 and result['failing_distribution']=='numpy==1.26.4' + assert d.sanitize_diagnostics({'failing_distribution':'https://secret.invalid/x'})=={} + + + +def test_worker_publishes_masked_stderr_and_command(tmp_path,monkeypatch): + from test_compute_r35 import load_worker + worker=load_worker(monkeypatch) + (tmp_path/'bootstrap.json').write_text('[{"models":[]}]') + monkeypatch.setattr(worker.subprocess,'check_output',lambda *a,**k:'NVIDIA A100, 40960') + def bootstrap(p,cache,run,stage):run([str(cache/'venv/bin/python'),'-m','pip','install','numpy'],check=True) + monkeypatch.setattr(worker,'bootstrap',bootstrap) + def guarded(p,c,args,run,kw): + run([str(c/'venv/bin/python'),'-I','-c','import sys;print(sys.version_info)'],check=True) + return run(args,**kw) + monkeypatch.setattr(worker,'run_command',guarded) + def fail(args,**kw): + if '-I' in args:return NS(stdout='3.12.13') + kw['stderr'].write(b'ERROR: No matching distribution found for numpy==1.26.4\nhttps://private.invalid/x /home/private/file person@example.invalid\n');raise subprocess.CalledProcessError(1,args) + monkeypatch.setattr(worker.subprocess,'run',fail) + assert worker.bootstrap_session(tmp_path)==1 + result=json.loads((tmp_path/'bootstrap-status.json').read_text()) + assert result['diagnostics']['command_label']=='pip_core' + assert result['diagnostics']['failing_distribution']=='numpy==1.26.4' + assert '' in result['private_bootstrap_stderr'] and 'private.invalid' not in result['private_bootstrap_stderr'] + assert result['venv_python_version']=='3.12.13' + assert set(result['system_python'])=={'version','ensurepip_available','headers_available'} + +@pytest.mark.parametrize('text',['ftp://private.invalid/file','token=short-secret','Authorization: Bearer short-secret','cookie=short-secret']) +def test_excerpt_additional_secrets(text): + assert 'private.invalid' not in d.stderr_excerpt(text) + assert 'short-secret' not in d.stderr_excerpt(text) + +def test_private_excerpt_is_durable_but_not_public_receipt(tmp_path,monkeypatch): + from test_compute_r35 import rig as fixture,native,ready,OWNER + # Fixture is consumed directly through the same offline service setup. + r=fixture.__wrapped__(tmp_path,monkeypatch);s,bridge,clock,account,bundle=r + state=ready(r);job=native(r);pid=job['bootstrap_plan_id'] + state=s.sessions.save(state['id'],phase='bootstrap',bootstrap_plan_id=pid,private_bootstrap_stderr='ERROR: ensurepip missing') + monkeypatch.setattr(s,'_exec',lambda *a,**k:{'clean':True}) + diagnostic={'stage':'session_bootstrap','substage':'venv_create','command_label':'venv_create','error_type':'CalledProcessError','error_code':'stage_failed','exit_code':1} + s.sessions.fail_plan(state,diagnostic,'bootstrap_failed') + from compute_parity.journal import Journal + from compute_parity.colab import ColabNative + journal=Journal(tmp_path/'parity-journal.sqlite3');journal.reserve(OWNER,job['id'],'colab',account,bundle['case_id'],'test',{'unit':'CU','amount':15}) + result=ColabNative(s,journal)._record(OWNER,job['id'],s.public_job(s.job(OWNER,job['id']))) + assert journal.get(OWNER,job['id'])['private_bootstrap_stderr']=='ERROR: ensurepip missing' + assert 'private_bootstrap_stderr' not in result + assert 'ensurepip missing' not in json.dumps(s.sessions.snapshot(OWNER)) + assert 'ensurepip missing' not in json.dumps(s.snapshot(OWNER)) + assert result['diagnostics']['command_label']=='venv_create' + + +def test_later_job_gets_its_failed_plan_excerpt_not_another_plans(tmp_path,monkeypatch): + from test_compute_r35 import rig as fixture,native,ready,OWNER + r=fixture.__wrapped__(tmp_path,monkeypatch);s,bridge,clock,account,bundle=r + state=ready(r);first=native(r);pid=first['bootstrap_plan_id'] + diagnostic={'stage':'session_bootstrap','substage':'pip_core','command_label':'pip_core','error_code':'stage_failed','exit_code':1} + state=s.sessions.save(state['id'],phase='bootstrap',bootstrap_plan_id=pid,private_bootstrap_stderr='first plan stderr') + monkeypatch.setattr(s,'_exec',lambda *a,**k:{'clean':True}) + s.sessions.fail_plan(state,diagnostic,'bootstrap_failed') + # Other admitted plans can run; a later request for the already failed plan + # must retain that plan's evidence, never the last observed plan's excerpt. + s.sessions.save(state['id'],phase='ready',private_bootstrap_stderr='another plan stderr') + later=native(r) + assert later['session_id']==state['id'] + current=s.sessions.get(state['id']) + s.sessions.fail_plan({**current,'bootstrap_plan_id':pid},diagnostic,'bootstrap_failed') + assert s.job(OWNER,later['id'])['private_bootstrap_stderr']=='first plan stderr' + assert 'first plan stderr' not in json.dumps(s.sessions.snapshot(OWNER)) + + +@pytest.fixture(autouse=True) +def one_voice_module(monkeypatch): + import sys + monkeypatch.setitem(sys.modules,'colab_session_voice',v) diff --git a/scripts/test_compute_r40.py b/scripts/test_compute_r40.py new file mode 100644 index 0000000..afefb3c --- /dev/null +++ b/scripts/test_compute_r40.py @@ -0,0 +1,23 @@ +"""Cap evidence is narrower than lane-stop evidence; no provider calls.""" +import copy,json,sqlite3,sys +from pathlib import Path +import pytest +C=Path(__file__).resolve().parents[1];sys.path[:0]=[str(C),str(C/'webui')] +from compute_parity.provisioning import pre_ready_infrastructure,cap_exemptions,remaining_attempts,states +from compute_parity.journal import Journal +from compute_parity.contracts import ParityError + + + + +def test_p1m2_missing_job_session_stays_counted(): + job={'request_id':'orphan','lane':'colab','state':'closed_no_execution_evidence','actual_cost':{'amount':0,'unit':'CU'},'artifacts':[]} + assert not pre_ready_infrastructure(job,None) + assert cap_exemptions([job],'/missing','fixture-owner',evidence={})=={} + + + + + + + diff --git a/scripts/test_compute_r40b.py b/scripts/test_compute_r40b.py new file mode 100644 index 0000000..75e1530 --- /dev/null +++ b/scripts/test_compute_r40b.py @@ -0,0 +1,150 @@ +"""Admission and transport boundaries; real locks, fake provider, no network.""" +import copy,json,threading,time,uuid +from pathlib import Path +import pytest +from review_r38_fixture import rig,session,submit +from colab_service import BridgeError +from compute_parity.provisioning import admission_only,cap_exemptions,states +from scripts.colab_rpc_transport import Budget,NotReady,scoped + +def verified(r,**changes): + v={'owner':r.owner,'account_id':r.account,'subject_key':'b'*64,'identity_at':r.t[0],'balance_at':r.t[0],'balance':1000} + v.update(changes);return session(r,phase='allocating',admission_verification=v) + +def test_account_busy_admits_from_verified_owner_session(rig): + r=rig;verified(r) + def hook(op,kw): + if op in {'account_status','account_identity'}:raise BridgeError('account_busy') + r.b.hook=hook;result=submit(r) + assert r.s.job(r.owner,result['request_id'])['phase']=='queued' + assert not any(op=='runtime_allocate' for op,_ in r.b.calls) + +@pytest.mark.parametrize('changes',[{'identity_at':999399},{'balance_at':999399},{'owner':'other'},{'account_id':'other'},{'subject_key':'c'*64},{'balance':None}]) +def test_busy_bad_snapshot_is_distinct_exempt_rejection(rig,changes): + r=rig;verified(r,**changes) + def hook(op,kw): + if op=='account_status':raise BridgeError('account_busy') + r.b.hook=hook;result=submit(r) + assert result['state']=='rejected' and result['error']['code']=='account_busy' + row=r.j.get(r.owner,result['request_id']) + assert cap_exemptions([row],r.s.root/'state.sqlite3',r.owner)=={row['request_id']:'admission_only'} + assert 'private_admission_error' not in result + +@pytest.mark.parametrize('field,value',[('settlement_status','unknown'),('artifacts',[{}]),('actual_cost',{'unit':'CU','amount':1}),('failure_kind','execution'),('lane','autoip'),('execution_started_at',1)]) +def test_admission_unknown_or_contradiction_counted(rig,field,value): + r=rig + def hook(op,kw): + if op=='account_status':raise BridgeError('account_busy') + r.b.hook=hook;result=submit(r);row=r.j.get(r.owner,result['request_id']);record=states(r.s.root/'state.sqlite3',r.owner)[row['request_id']] + assert admission_only(row,record) + row[field]=value;assert not admission_only(row,record) + + +def test_private_diagnostic_never_public(rig): + from compute_parity.adapters import public + from compute_parity.runtime import Runtime + from scripts.colab_private_diagnostics import capture + r=rig + def hook(op,kw): + if op=='account_status':raise BridgeError('transport_failed',private_diagnostics=capture(RuntimeError('https://secret.invalid/token user:pass@host /home/user/file '+('X'*64)),'account_status')) + r.b.hook=hook;result=submit(r);row=r.j.get(r.owner,result['request_id']) + assert row['private_admission_error']['bridge']['operation']=='account_status' + serialized=json.dumps(row['private_admission_error']);assert 'secret.invalid' not in serialized and '/home/' not in serialized and 'pass@host' not in serialized + from compute_routing import _public_receipt + for projection in [result,public(row),Runtime.receipt(row),_public_receipt(Runtime.receipt(row))]:assert 'private_admission_error' not in json.dumps(projection) + +class Event: + def __init__(self,on=False):self.on=on + def is_set(self):return self.on + def wait(self,timeout=None):return self.on + def set(self):self.on=True + def clear(self):self.on=False +class Client: + def __init__(self,ready=True):self.connection_ready=Event(ready);self._message_received=Event();self.sent=0 + def start_channels(self):pass + def execute(self):self.sent+=1;return 'ack' + def _on_open(self,*args):self.connection_ready.set() + def _on_close(self,*args):self.connection_ready.clear() + +@pytest.mark.parametrize('ready',[False,True]) +def test_transport_never_open_or_close_before_send(ready): + b=Budget(2);c=Client(ready) + with scoped(b,Client): + if not ready: + with pytest.raises(NotReady):c.start_channels() + else: + c.start_channels();c._on_close(None,1006,'PRIVATE reason') + with pytest.raises(NotReady):c.execute() + assert c.sent==0 and b.sent is False and 'PRIVATE' not in json.dumps(b.evidence()) + +def test_transport_close_after_send_stays_ambiguous(): + b=Budget(2);c=Client() + with scoped(b,Client): + c.start_channels();c.execute();c._on_close(None,1006,'private') + assert b.sent and b.evidence()['phase']=='close' and b.evidence()['close_code']==1006 + +@pytest.mark.parametrize('wall,mono',[(0,91),(91,0),(-1,1),(91,91)]) +def test_transport_dual_clock_deadline_freeze_jump_and_late_success(wall,mono): + w=[100.];m=[100.];b=Budget(90,lambda:w[0],lambda:m[0]);w[0]+=wall;m[0]+=mono + with pytest.raises(TimeoutError):b.remaining() + +def test_ready_wait_and_silent_open_are_deadline_bounded(): + class Silent(Event): + def wait(self,timeout=None):time.sleep(timeout);return False + b=Budget(.03);c=Client();c._message_received=Silent() + with scoped(b,Client): + c.start_channels();c.execute() + with pytest.raises(TimeoutError):c._message_received.wait() + assert b.sent + +@pytest.mark.parametrize('modes,expected_calls,ambiguous',[ + (['notready','ok'],2,None),(['notready','notready'],2,False), + (['sentfail','ok'],1,True),(['closed','ok'],2,None),(['lateclose'],1,True)]) +def test_scoped_bridge_reconnects_only_before_send(monkeypatch,modes,expected_calls,ambiguous): + import contextlib + from scripts import colab_bridge as cb,colab_rpc_transport as rpc + real_scoped=rpc.scoped + monkeypatch.setattr(rpc,'scoped',lambda b:real_scoped(b,Client)) + calls=[] + clock=[time.time(),time.monotonic()] + if modes==['lateclose']: + monkeypatch.setattr(rpc,'Budget',lambda seconds:Budget(seconds,lambda:clock[0],lambda:clock[1])) + class Runtime: + def __init__(self,*args,**kwargs):self.mode=modes[len(calls)];calls.append(self.mode) + def execute_code(self,*args,**kwargs): + c=Client(self.mode!='notready');c.start_channels() + if self.mode=='closed':c._on_close(None,1006,'private') + c.execute() + if self.mode=='sentfail':raise RuntimeError('Connection was lost.') + return [] + def stop(self,**kwargs): + if self.mode=='lateclose':clock[0]+=100;clock[1]+=100 + sdk=cb.GoogleSDK.__new__(cb.GoogleSDK);sdk.Runtime=Runtime;sdk.execution_transport=contextlib.nullcontext + b=cb.Bridge.__new__(cb.Bridge);b.sdk=sdk;b.runtime=lambda rid:{'url':'https://example.invalid','token':'fixture'} + args={'runtime_id':str(uuid.uuid4()),'code':'pass','timeout_seconds':3} + if ambiguous is None: + result=b.remote_exec(args);assert result['private_rpc']['attempts']==expected_calls + else: + with pytest.raises(cb.BridgeError) as caught:b.remote_exec(args) + assert caught.value.ambiguous is ambiguous + assert caught.value.code==('execution_uncertain' if ambiguous else 'transport_not_ready') + assert len(calls)==expected_calls + +def test_sdk_cause_captured_before_transport_failed(monkeypatch): + from scripts import colab_bridge as cb + def fail(*args,**kwargs):raise ConnectionError('file:secret user:pass@host /home/private '+('x'*64)) + monkeypatch.setattr(cb,'dispatch',fail) + result=cb.handle({'op':'account_status'})['error'] + assert result['code']=='transport_failed' and result['private_diagnostics']['class']=='ConnectionError' + assert result['private_diagnostics']['operation']=='account_status' + assert 'user:pass' not in json.dumps(result) and '/home/' not in json.dumps(result) + +@pytest.mark.parametrize('field,value',[('state','pending'),('outcome','failed'),('owner','other')]) +def test_terminal_claim_binding_is_required(rig,field,value): + r=rig + def hook(op,kw): + if op=='account_status':raise BridgeError('account_busy') + r.b.hook=hook;result=submit(r);row=r.j.get(r.owner,result['request_id']);record=states(r.s.root/'state.sqlite3',r.owner)[row['request_id']] + assert admission_only(row,record) + record[1]['_claim_evidence'][field]=value + assert not admission_only(row,record) diff --git a/scripts/test_compute_r40c.py b/scripts/test_compute_r40c.py new file mode 100644 index 0000000..85e69b7 --- /dev/null +++ b/scripts/test_compute_r40c.py @@ -0,0 +1,153 @@ +"""r40 rev3: execute generated probes with real local PID/flock, no RPC/network.""" +import ast,contextlib,fcntl,io,json,os +from pathlib import Path +import pytest +from review_r38_fixture import rig,session,submit +from colab_service import BridgeError +from colab_sessions import WorkSessions,bootstrap_progress_fault +from compute_parity.provisioning import cap_exemptions + +@pytest.mark.parametrize('value,previous,kind',[(1000005,None,'progress_future'),(float('nan'),None,'progress_nonfinite'),(float('inf'),None,'progress_nonfinite'),(999879,None,'progress_stale'),(999999,1000000,'progress_regressed')]) +def test_generated_invalid_progress_preserves_budget(rig,tmp_path,monkeypatch,value,previous,kind): + run_probe(rig,tmp_path,monkeypatch,value,previous=previous,expected=kind,prior_fault=True) + + +def run_probe(r,tmp_path,monkeypatch,progress,previous=None,expected=None,prior_fault=False,heartbeat='good',tamper=None): + st=session(r,'bootstrap',launch_at=r.t[0],bootstrap_progress=previous);sid=st['id'];r.s.sessions.freeze(st) + remote=tmp_path/'remote';remote.mkdir() + identity={'pid':os.getpid(),'start_ticks':Path('/proc/self/stat').read_text().rsplit(')',1)[1].split()[19]} + (remote/'bootstrap-process.json').write_text(json.dumps(identity)) + (remote/'bootstrap-status.json').write_text(json.dumps({'phase':'running','progress_at':progress})) + lock=(remote/'watchdog.lock').open('w');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + stat=os.fstat(lock.fileno());wd={**identity,'deadline':r.t[0]+21600,'lock_dev':stat.st_dev,'lock_ino':stat.st_ino} + (remote/'watchdog.json').write_text(json.dumps(wd)) + if heartbeat!='missing':(remote/'heartbeat').write_text(str(r.t[0]-(301 if heartbeat=='stale' else 0))) + before_heartbeat=(remote/'heartbeat').read_bytes() if (remote/'heartbeat').exists() else None + r.s.sessions.save(sid,bootstrap_identity=identity,watchdog_identity=wd) + if prior_fault: + r.s.sessions.operation(st,'bootstrap_probe');r.s.sessions.record_fault(st,BridgeError('execution_uncertain',True)) + before=r.s.sessions.get(sid);r.t[0]+=.1 + def execute(state,code): + assert 'bootstrap-status.json' in code + code=code.replace('/content/castle-sessions/'+sid,str(remote)).replace('time.time()',str(r.t[0])) + output=io.StringIO() + with contextlib.redirect_stdout(output):exec(compile(code,'generated-combined-probe','exec'),{}) + result=json.loads(output.getvalue().strip().split('WEB_COMFYUI_JSON=')[1]) + if tamper:tamper(result) + return result + monkeypatch.setattr(r.s,'_exec',execute) + try:r.s.sessions.tick_all() + finally:lock.close() + after=r.s.sessions.get(sid) + if expected: + assert after['last_tick']==before['last_tick'] + assert after['fault_streak']==(2 if prior_fault else 1) + assert after['phase']==('closing' if prior_fault else 'bootstrap') + assert after['fault']['ambiguous'] and after['fault']['stage']=='bootstrap_probe' + assert after['private_rpc_error']=={'bootstrap_probe':{'type':expected}} + assert 'bootstrap_probe' not in json.dumps(r.s.sessions.public(after).get('private_rpc_error')) + if not tamper: + assert ((remote/'heartbeat').read_bytes() if (remote/'heartbeat').exists() else None)==before_heartbeat + else: + assert after['last_tick']==r.t[0] and after['fault_streak']==0 + assert after['phase']=='bootstrap' + # Remote renewal uses the preceding COMPLETE cycle, never current partial progress. + assert float((remote/'heartbeat').read_text())==before['last_tick'] + return after + +@pytest.mark.parametrize('heartbeat',['missing','stale']) +def test_generated_heartbeat_file_required(rig,tmp_path,monkeypatch,heartbeat): + run_probe(rig,tmp_path,monkeypatch,rig.t[0],heartbeat=heartbeat,expected='heartbeat_unavailable') + +@pytest.mark.parametrize('field,value,kind',[ + ('heartbeat',False,'heartbeat_ack_missing'),('watchdog_identity',{},'heartbeat_identity_mismatch'), + ('heartbeat_cycle','old-cycle','heartbeat_cycle_mismatch'),('heartbeat_at',0,'heartbeat_timestamp_mismatch')]) +def test_ack_bound_to_identity_and_current_cycle(rig,tmp_path,monkeypatch,field,value,kind): + run_probe(rig,tmp_path,monkeypatch,rig.t[0],expected=kind,tamper=lambda result:result.update({field:value})) + + +def test_one_fault_then_actual_complete_probe_recovers(rig,tmp_path,monkeypatch): + run_probe(rig,tmp_path,monkeypatch,rig.t[0],prior_fault=True) + + +def test_fixed_future_tolerance(): + assert bootstrap_progress_fault(100,101) is None + assert bootstrap_progress_fault(100,101.001)=='progress_future' + assert bootstrap_progress_fault(100,100,101)=='progress_regressed' + + +def verified(r,**kw): + v={'owner':r.owner,'account_id':r.account,'subject_key':'b'*64,'balance':1000,'identity_at':r.t[0],'balance_at':r.t[0]};v.update(kw) + return session(r,'allocating',admission_verification=v) + + +def busy(r): + def hook(op,kw): + if op in {'account_status','account_identity'}:raise BridgeError('account_busy') + r.b.hook=hook + + +def rejected(r): + busy(r);got=submit(r) + assert got['state']=='rejected' and got['error']['code']=='account_busy' + row=r.j.get(r.owner,got['request_id']) + assert cap_exemptions([row],r.s.root/'state.sqlite3',r.owner)=={row['request_id']:'admission_only'} + + +def test_released_snapshot_is_uncounted_busy(rig): + st=verified(rig);rig.s.sessions.save(st['id'],released=True);rejected(rig) + + +def test_clock_rewind_never_revives_snapshot(rig): + r=rig;verified(r,identity_at=r.t[0]-500,balance_at=r.t[0]-500) + r.t[0]+=150;assert r.s.sessions.admission_snapshot(r.owner,r.account) is None + r.t[0]-=200;assert r.s.sessions.admission_snapshot(r.owner,r.account) is None + rejected(r) + +@pytest.mark.parametrize('restart',[False,True]) +@pytest.mark.parametrize('field',['last_tick','created_at','upload_started_at','digest_verified_at','bootstrap_progress','fault','admission_verification']) +def test_snapshot_checks_all_durable_observations(rig,field,restart): + r=rig;st=verified(r);value=r.t[0]+10 + if field=='fault':value={'at':value} + if field=='admission_verification':value={**st[field],'balance_at':value} + # Inject a durable observation directly: save() correctly refuses future last_tick. + with r.s.db() as db: + st[field]=value;db.execute('UPDATE work_sessions SET state=? WHERE id=?',(json.dumps(st),st['id'])) + if restart:r.s.sessions=WorkSessions(r.s) + assert r.s.sessions.admission_snapshot(r.owner,r.account) is None + rejected(r) + + +def test_snapshot_monotonic_bound_and_process_rewind(rig): + r=rig;verified(r);mono=[0.];r.s.sessions._monotonic=lambda:mono[0] + assert r.s.sessions.admission_snapshot(r.owner,r.account) + r.t[0]+=200;mono[0]=200 + assert r.s.sessions.admission_snapshot(r.owner,r.account) + r.t[0]-=100;mono[0]+=1 + assert r.s.sessions.admission_snapshot(r.owner,r.account) is None + r.t[0]+=200;mono[0]=601 + assert r.s.sessions.admission_snapshot(r.owner,r.account) is None + + +def test_snapshot_restart_valid_durable_remainder(rig): + r=rig;verified(r,identity_at=r.t[0]-500,balance_at=r.t[0]-500) + r.s.sessions=WorkSessions(r.s);mono=[0.];r.s.sessions._monotonic=lambda:mono[0] + assert r.s.sessions.admission_snapshot(r.owner,r.account) + mono[0]=101 + assert r.s.sessions.admission_snapshot(r.owner,r.account) is None + + +def test_open_captures_monotonic_age_before_first_busy_fallback(rig): + r=rig;mono=[0.];r.s.sessions._monotonic=lambda:mono[0] + r.s.sessions.open(r.owner,r.account) + mono[0]=601 # Wall clock froze; no fallback has ever read the snapshot. + assert r.s.sessions.admission_snapshot(r.owner,r.account) is None + rejected(r) + + +@pytest.mark.parametrize('field,value',[('last_tick',None),('created_at',None),('created_at',float('inf'))]) +def test_snapshot_unknown_clock_evidence_is_uncounted_busy(rig,field,value): + r=rig;st=verified(r);st[field]=value + with r.s.db() as db:db.execute('UPDATE work_sessions SET state=? WHERE id=?',(json.dumps(st),st['id'])) + assert r.s.sessions.admission_snapshot(r.owner,r.account) is None + rejected(r) diff --git a/scripts/test_compute_r40v4.py b/scripts/test_compute_r40v4.py new file mode 100644 index 0000000..219dfb7 --- /dev/null +++ b/scripts/test_compute_r40v4.py @@ -0,0 +1,226 @@ +"""P1m6 dependency gap, private evidence, and pre-model gate. Offline mocks only.""" +import copy,json,os,stat,subprocess +from pathlib import Path +from types import SimpleNamespace as NS +import pytest +from scripts import colab_session_probe as p,colab_session_diagnostics as d,colab_session_voice as voice +from test_compute_r35 import rig,load_worker,native,OWNER +from compute_parity.adapters import public +from compute_parity.provisioning import pre_ready_infrastructure +ROOT=Path(__file__).resolve().parents[1] + + + +@pytest.mark.parametrize('raw,secret',[ + ('https://example.invalid/private?token=abc','example.invalid'),('user:pass@host','user:pass'), + ('/home/private/material.wav','/home'),('person@example.invalid','person'), + ('file:relative/private','relative'),('data:opaque-secret','opaque-secret'), + ('%41%42%43%44','%41'),('a'*64,'a'*32),('token=secret-value','secret-value')]) +def test_private_log_masks_before_limits(tmp_path,raw,secret): + f=tmp_path/'log' + with p.private_log(f) as stream:stream.write(('normal\n'*300)+raw+'\n') + tail=p.log_tail(f) + assert secret not in tail and len(tail.splitlines())<=200 and len(tail.encode())<=16384 + assert stat.S_IMODE(f.stat().st_mode)==0o600 + assert 'startup_tail' not in d.sanitize_diagnostics({'startup_tail':tail}) + +def test_names_only_and_private_projection(): + evidence=p.private_diagnostics({'missing_nodes':['GetImageRangeFromBatch','https://private.invalid/node'],'missing_models':['nested/weights.safetensors'],'missing_inputs':['Node.field','file:private'],'startup_tail':'failure\n'}) + assert evidence['missing_nodes']==['GetImageRangeFromBatch'] + assert evidence['missing_models']==['weights.safetensors'] + assert evidence['missing_inputs']==['Node.field'] + assert 'private_dependency_diagnostics' not in public({'private_dependency_diagnostics':evidence}) + assert d.sanitize_diagnostics({'error_code':'node_import_failed','stage':'session_bootstrap','private_dependency_diagnostics':evidence})=={'stage':'session_bootstrap','error_code':'node_import_failed'} + + + + + + + + +def test_real_worker_dependency_gap_never_posts_prompt(rig,monkeypatch,tmp_path): + s,b,clock,account,bundle=rig;job=native(rig);worker=load_worker(monkeypatch);session=tmp_path/'remote-session';core=session/'cache/ComfyUI';core.mkdir(parents=True) + monkeypatch.setattr(worker,'prepared',lambda *a:(core,'/mock/python')) + monkeypatch.setattr(worker,'comfy_identity',lambda *a,**k:{}) + monkeypatch.setattr(worker.time,'time',lambda:clock[0]) + monkeypatch.setattr(worker.subprocess,'check_output',lambda *a,**k:'NVIDIA A100, 40960') + realpath=Path;monkeypatch.setattr(worker,'Path',lambda x:tmp_path/'alias' if str(x)=='/content/castle-parity-input' else realpath(x)) + monkeypatch.setattr(worker,'stop_group',lambda p:None) + def popen(*a,**k):k['stderr'].write('ImportError: missing node\n');k['stderr'].flush();return NS(poll=lambda:None) + monkeypatch.setattr(worker.subprocess,'Popen',popen);calls=[] + def request(method,path,*args):calls.append((method,path));assert method=='GET';return {} + monkeypatch.setattr(worker,'local_request',request) + monkeypatch.setattr(worker,'dependency_probe',lambda *a:{'ready':False,'missing_nodes':['GetImageRangeFromBatch'],'missing_models':[],'missing_inputs':[]}) + root=s.root/'jobs'/job['id'];assert worker.run_native(root,job['manifest_sha256'],session)==1 + status=json.loads((root/'status.json').read_text()) + assert status['diagnostics']['error_code']=='dependency_gap' + assert status['private_dependency_diagnostics']['missing_nodes']==['GetImageRangeFromBatch'] + assert 'ImportError' in status['private_dependency_diagnostics']['startup_tail'] + assert not (root/'native-submission.json').exists() and calls==[('GET','/object_info')] + assert (root/'reusable-clean.json').exists() + assert stat.S_IMODE((session/'job-evidence'/job['id']/'comfy-startup.log').stat().st_mode)==0o600 + +@pytest.mark.parametrize('later',[False,True]) +def test_failed_plan_private_evidence_reaches_durable_receipt_only(rig,tmp_path,monkeypatch,later): + from test_compute_r35 import ready + from compute_parity.colab import ColabNative + from compute_parity.journal import Journal + from compute_routing import _public_receipt + s,bridge,clock,account,bundle=rig;state=ready(rig);job=native(rig);pid=job['bootstrap_plan_id'] + private={'missing_nodes':['GetImageRangeFromBatch'],'missing_models':[],'missing_inputs':[],'startup_tail':'ImportError: missing component'} + diagnostic={'stage':'session_bootstrap','substage':'import_ready','error_code':'node_import_failed'} + state=s.sessions.save(state['id'],phase='bootstrap',bootstrap_plan_id=pid,private_dependency_diagnostics=private) + monkeypatch.setattr(s,'_exec',lambda *a,**k:{'clean':True}) + s.sessions.fail_plan(state,diagnostic,'bootstrap_failed') + if later: + s.sessions.save(state['id'],phase='ready',private_dependency_diagnostics={'missing_nodes':['OtherPlan']}) + job=native(rig);current=s.sessions.get(state['id']);s.sessions.fail_plan({**current,'bootstrap_plan_id':pid},diagnostic,'bootstrap_failed') + j=Journal(tmp_path/'receipt.sqlite3');j.reserve(OWNER,job['id'],'colab',account,bundle['case_id'],'test',{'unit':'CU','amount':15}) + receipt=ColabNative(s,j)._record(OWNER,job['id'],s.public_job(s.job(OWNER,job['id']))) + assert j.get(OWNER,job['id'])['private_dependency_diagnostics']==private + assert receipt['diagnostics']['error_code']=='node_import_failed' and '尚未開始生成' in receipt['message'] + for projection in (receipt,_public_receipt(receipt),s.snapshot(OWNER),s.sessions.snapshot(OWNER)): + assert 'private_dependency_diagnostics' not in json.dumps(projection) + assert 'missing component' not in json.dumps(projection) and 'GetImageRangeFromBatch' not in json.dumps(projection) + + +@pytest.mark.parametrize('marker',['missing','different_attempt','different_plan','clean','legacy']) +def test_controller_requires_probe_cleanup_evidence(rig,tmp_path,monkeypatch,marker): + import contextlib,io + from test_compute_r35 import ready + s,b,clock,account,bundle=rig;state=ready(rig);job=native(rig);pid=job['bootstrap_plan_id'] + state=s.sessions.save(state['id'],phase='bootstrap',bootstrap_plan_id=pid) + root=tmp_path/'remote'/pid;root.mkdir(parents=True) + (root/'bootstrap-process.json').write_text(json.dumps({'pid':999999999,'start_ticks':'0'})) + if marker!='legacy':(root/'node-probe-attempt.json').write_text(json.dumps({'attempt':'probe-a','plan_id':pid})) + if marker not in {'missing','legacy'}: + (root/'node-probe-clean.json').write_text(json.dumps({'attempt':'other' if marker=='different_attempt' else 'probe-a','plan_id':'other' if marker=='different_plan' else pid,'clean':True})) + def execute(state,code): + assert 'probe_clean' in code + code=code.replace('/content/castle-sessions/'+state['id']+'/plans/'+pid,str(root)) + # No process operations in this actual generated-code regression. + code=code.replace("'/proc/'",repr(str(tmp_path/'no-proc')+'/')).replace("'/proc'",repr(str(tmp_path/'no-proc'))) + monkeypatch.setattr(os,'killpg',lambda *a:pytest.fail('No live process signal')) + stream=io.StringIO() + with contextlib.redirect_stdout(stream):exec(compile(code,'generated-cleanup','exec'),{}) + return json.loads(stream.getvalue().split('WEB_COMFYUI_JSON=')[1]) + monkeypatch.setattr(s,'_exec',execute) + s.sessions.fail_plan(state,{'stage':'session_bootstrap','substage':'import_ready','error_code':'node_import_failed'},'bootstrap_failed') + current=s.sessions.get(state['id']) + assert current['phase']=='closing' + assert current['reason']==('bootstrap_failed' if marker in {'clean','legacy'} else 'bootstrap_process_lost') + + +REQUIREMENTS=b'pillow>=10.3.0\ncolor-matcher\nmatplotlib\nmss\nopencv-python-headless\n' + + + + + +@pytest.mark.parametrize('cause',['specification','inventory','delta']) +def test_supplement_failure_is_private_pre_ready_uncounted(rig,tmp_path,monkeypatch,cause): + from test_compute_r35 import ready + from compute_parity.colab import ColabNative + from compute_parity.journal import Journal + from compute_parity.provisioning import states + error=p.spec_failure(cause,['safe-package']);private=error.private_dependency_diagnostics + assert private['supplement_detail'] in {'supplement_requirements_changed','supplement_requirement_unlisted','supplement_delta_unexpected'} + assert 'private_dependency_diagnostics' not in public({'private_dependency_diagnostics':private}) + diagnostic=d.failure_diagnostics(error,'pip_node:ComfyUI-KJNodes') + assert diagnostic['error_code']=='stage_failed' and diagnostic['command_label']=='pip_node:ComfyUI-KJNodes' + s,bridge,clock,account,bundle=rig;state=ready(rig);job=native(rig);pid=job['bootstrap_plan_id'] + state=s.sessions.save(state['id'],phase='bootstrap',prepared_plans=[],bootstrap_plan_id=pid,private_dependency_diagnostics=private) + monkeypatch.setattr(s,'_exec',lambda *a,**k:{'clean':True}) + s.sessions.fail_plan(state,diagnostic,'bootstrap_failed') + for _ in range(3):s.sessions.tick_all() + j=Journal(tmp_path/'receipt.sqlite3',colab_state_path=s.root/'state.sqlite3') + j.reserve(OWNER,job['id'],'colab',account,bundle['case_id'],'test',{'unit':'CU','amount':15}) + ColabNative(s,j)._record(OWNER,job['id'],s.public_job(s.job(OWNER,job['id']))) + row=j.get(OWNER,job['id']);evidence=states(s.root/'state.sqlite3',OWNER) + assert pre_ready_infrastructure(row,evidence[job['id']]) + assert row['actual_cost']=={'amount':0.0,'unit':'CU'} + + +def test_copy_truncate_append_tail_and_modes(tmp_path): + import fcntl + path=tmp_path/'comfy-bootstrap.log' + with p.private_log(path) as stream: + inode=path.stat().st_ino + assert stat.S_ISREG(os.fstat(stream.fileno()).st_mode) + assert fcntl.fcntl(stream.fileno(),fcntl.F_GETFL)&os.O_APPEND + for i in range(30): + stream.write('newest-line-'+str(i)+'\n'+'x'*1000+'\n');stream.flush() + assert path.stat().st_size<=2048+1100 + p.bound_log(path,budget=2048,keep=1024) + assert path.stat().st_size<=2048 + if Path(str(path)+'.prev').exists():assert Path(str(path)+'.prev').stat().st_size<=1024 + stream.write('tail-before-truncate\n');stream.flush();p.bound_log(path,budget=1,keep=1024) + assert 'tail-before-truncate' in p.log_tail(path) + stream.write('tail-after-truncate\n');stream.flush() + assert path.stat().st_size==len('tail-after-truncate\n') and path.stat().st_ino==inode + p.compact_log(path,tmp_path,keep=1024) + assert path.stat().st_size<=1024 and not Path(str(path)+'.prev').exists() + assert 'tail-after-truncate' in p.log_tail(path) and stat.S_IMODE(path.stat().st_mode)==0o600 + + +def test_compacted_log_retains_only_newest_32(tmp_path): + for i in range(40): + path=tmp_path/'job-evidence'/str(i)/'comfy-startup.log' + with p.private_log(path) as stream:stream.write('x'*2000) + p.bound_log(path,budget=1000,keep=256) + assert stat.S_IMODE(Path(str(path)+'.prev').stat().st_mode)==0o600 + p.compact_log(path,tmp_path,keep=256) + logs=list(tmp_path.rglob('comfy-*.log')) + assert len(logs)==32 and sum(f.stat().st_size for f in logs)<=32*256 + assert not list(tmp_path.rglob('*.prev')) and not (tmp_path/'job-evidence/0/comfy-startup.log').exists() + + +def test_bounder_exception_is_private_and_child_file_unchanged(tmp_path,monkeypatch): + path=tmp_path/'comfy-bootstrap.log' + with p.private_log(path) as stream: + stream.write('before\n'*100);stream.flush() + real=p.os.replace + monkeypatch.setattr(p.os,'replace',lambda a,b:(_ for _ in ()).throw(OSError()) if str(b).endswith('.prev') else real(a,b)) + p.bound_log(path,budget=10,keep=8) + stream.write('after\n');stream.flush() + assert path.read_text().endswith('after\n') and len(path.read_bytes())>700 + assert json.loads(Path(str(path)+'.notes.json').read_text())==['log_bound_failed'] + + +@pytest.mark.parametrize('broken',[False,True]) +def test_real_worker_execution_log_bounder_never_changes_result(rig,tmp_path,monkeypatch,broken): + s,b,clock,account,bundle=rig;job=native(rig);worker=load_worker(monkeypatch) + session=tmp_path/'remote-session';core=session/'cache/ComfyUI';core.mkdir(parents=True) + monkeypatch.setattr(worker,'prepared',lambda *a:(core,'/mock/python')) + monkeypatch.setattr(worker,'comfy_identity',lambda *a,**k:{}) + monkeypatch.setattr(worker.time,'time',lambda:clock[0]);ticks=[0.] + monkeypatch.setattr(worker.time,'monotonic',lambda:ticks[0]) + monkeypatch.setattr(worker.time,'sleep',lambda n:ticks.__setitem__(0,ticks[0]+n)) + monkeypatch.setattr(worker.subprocess,'check_output',lambda *a,**k:'NVIDIA A100, 40960') + realpath=Path;monkeypatch.setattr(worker,'Path',lambda x:tmp_path/'alias' if str(x)=='/content/castle-parity-input' else realpath(x)) + monkeypatch.setattr(worker,'stop_group',lambda proc:None);handles=[];calls=[] + def launch(*a,**kw):handles.append(kw['stdout']);return NS(poll=lambda:None) + monkeypatch.setattr(worker.subprocess,'Popen',launch) + monkeypatch.setattr(worker,'dependency_probe',lambda *a:{'ready':True}) + monkeypatch.setattr(worker,'output_check',lambda *a:None) + def bound(path): + calls.append(ticks[0]) + if broken:raise RuntimeError('simulated bounder error') + p.bound_log(path,budget=1024,keep=256) + monkeypatch.setattr(worker,'bound_log',bound) + root=s.root/'jobs'/job['id'];out=root/'comfy-output';out.mkdir();(out/'output.mp4').write_bytes(b'offline output') + def request(method,path,*args): + if path=='/object_info':return {} + if path=='/prompt':return {'prompt_id':'offline'} + handles[0].write('warning\n'*100);handles[0].flush() + if not broken:assert (session/'job-evidence'/job['id']/'comfy-startup.log').stat().st_size<=1024+1600 + if ticks[0]<20:return {} + return {'offline':{'status':{'completed':True},'outputs':{'1':{'videos':[{'type':'output','filename':'output.mp4'}]}}}} + monkeypatch.setattr(worker,'local_request',request) + assert worker.run_native(root,job['manifest_sha256'],session)==0 + assert json.loads((root/'status.json').read_text())['phase']=='completed' + assert calls and all(b-a>=2 for a,b in zip(calls,calls[1:])) + logfile=session/'job-evidence'/job['id']/'comfy-startup.log' + assert logfile.stat().st_size<=p.LOG_KEEP and not Path(str(logfile)+'.prev').exists() + if broken:assert json.loads(Path(str(logfile)+'.notes.json').read_text())==['log_bound_failed'] diff --git a/scripts/test_compute_r40v5.py b/scripts/test_compute_r40v5.py new file mode 100644 index 0000000..fd02d61 --- /dev/null +++ b/scripts/test_compute_r40v5.py @@ -0,0 +1,155 @@ +import math +import pytest +from review_r38_fixture import rig,session,submit +from colab_service import BridgeError + + +def snapshot(r,st,age=4300): + t=r.t[0]-age + v={'owner':r.owner,'account_id':r.account,'subject_key':'b'*64,'identity_at':t,'balance_at':t,'balance':1000} + return r.s.sessions.save(st['id'],admission_verification=v) + +def status(r,**kw): + def hook(op,args): + if op=='account_status':return {'authenticated':True,'subject_key':'b'*64,'balance_compute_units':1000,**kw} + r.b.hook=hook + +def test_observe_refreshes_busy_admission(rig): + r=rig;st=snapshot(rig,session(rig));status(r);r.s.sessions.observe(st) + def busy(op,args): + if op in {'account_status','account_identity'}:raise BridgeError('account_busy') + r.b.hook=busy;job=submit(r) + j=r.s.job(r.owner,job['request_id']);assert j['phase']=='queued' + assert j['admission_verification']['identity_at']==r.t[0] and j['admission_verification']['balance']==1000 + assert not any(op=='runtime_allocate' for op,_ in r.b.calls) + +@pytest.mark.parametrize('values',[{'subject_key':'c'*64},{'subject_key':None},{'authenticated':1},{'balance_compute_units':0},{'balance_compute_units':-1},{'balance_compute_units':float('nan')}]) +def test_invalid_observation_never_refreshes(rig,values): + r=rig;st=snapshot(r,session(r));old=st['admission_verification'];status(r,**values) + try:r.s.sessions.observe(st) + except ValueError:pass + assert r.s.sessions.get(st['id'])['admission_verification']==old + +@pytest.mark.parametrize('changes',[{'close_requested':True},{'released':True},{'phase':'closing'}]) +def test_closed_and_unusable_session_not_refreshed(rig,changes): + r=rig;st=snapshot(r,session(r));st=r.s.sessions.save(st['id'],**changes);status(r);r.s.sessions.observe(st) + assert r.s.sessions.get(st['id'])['admission_verification']==st['admission_verification'] + +def test_observation_time_before_rpc(rig): + r=rig;st=snapshot(r,session(r));before=r.t[0] + def hook(op,args): + if op=='account_status':r.t[0]+=7;return {'authenticated':True,'subject_key':'b'*64,'balance_compute_units':1000} + r.b.hook=hook;r.s.sessions.observe(st);v=r.s.sessions.get(st['id'])['admission_verification'] + assert v['identity_at']==v['balance_at']==before + +def test_rewind_and_anchors(rig): + r=rig;st=snapshot(r,session(r));status(r) + for i in range(50):r.s.sessions.observe(st);r.t[0]+=1 + assert len([k for k in r.s.sessions._admission_anchors if k[0]==st['id']])==1 + assert r.s.sessions.admission_snapshot(r.owner,r.account) + assert r.s.sessions.admission_snapshot('other',r.account) is None + assert r.s.sessions.admission_snapshot(r.owner,'other') is None + r.t[0]-=30;old=r.s.sessions.get(st['id'])['admission_verification'];assert r.s.sessions.admission_snapshot(r.owner,r.account) is None + r.s.sessions.observe(st);assert r.s.sessions.get(st['id'])['admission_verification']==old + +def test_meter_exception_rolls_back(rig,monkeypatch): + r=rig;st=snapshot(r,session(r));status(r) + def fail(*a,**kw):raise RuntimeError('meter') + monkeypatch.setattr(r.s.sessions,'_meter',fail) + with pytest.raises(RuntimeError):r.s.sessions.observe(st) + assert r.s.sessions.get(st['id'])['admission_verification']==st['admission_verification'] + +def test_one_busy_heartbeat_is_transient(rig): + r=rig;st=session(r) + def hook(op,kw): + if op=='remote_exec':raise BridgeError('account_busy') + r.b.hook=hook;r.t[0]+=10;r.s.sessions.tick_all();cur=r.s.sessions.get(st['id']) + assert cur['phase']=='ready' and cur['fault_streak']==1 and cur['last_tick']==st['last_tick'] + r.b.hook=None;r.t[0]+=10;r.s.sessions.tick_all();assert r.s.sessions.get(st['id'])['fault_streak']==0 + +def test_two_busy_heartbeats_close(rig): + r=rig;st=session(r) + def hook(op,kw): + if op=='remote_exec':raise BridgeError('account_busy') + r.b.hook=hook + for _ in range(2):r.t[0]+=10;r.s.sessions.tick_all() + assert r.s.sessions.get(st['id'])['phase']=='closing' + +def test_stale_snapshot_busy_rejected(rig): + r=rig;st=snapshot(r,session(r)) + def busy(op,args): + if op in {'account_status','account_identity'}:raise BridgeError('account_busy') + r.b.hook=busy;result=submit(r) + assert result['state']=='rejected' and result['error']['code']=='account_busy' + from compute_parity.provisioning import cap_exemptions + row=r.j.get(r.owner,result['request_id']);assert row['actual_cost']['amount']==0 and row['settlement_status']=='settled' + assert cap_exemptions([row],r.s.root/'state.sqlite3',r.owner)=={row['request_id']:'admission_only'} + assert r.s.sessions.get(st['id'])['admission_verification']==st['admission_verification'] + +def test_monotonic_expiry(rig): + r=rig;st=snapshot(r,session(r));mono=[100.];r.s.sessions._monotonic=lambda:mono[0];status(r) + r.s.sessions.observe(st);assert r.s.sessions.admission_snapshot(r.owner,r.account) + mono[0]+=601;assert r.s.sessions.admission_snapshot(r.owner,r.account) is None + + +@pytest.mark.parametrize('stage',['observe','heartbeat','upload','bootstrap_probe','job_probe']) +def test_busy_allowed_only_for_existing_stages(rig,stage): + r=rig;st=session(r);sid=st['id'];r.s.sessions.operation(st,stage) + r.s.sessions.record_fault(st,BridgeError('account_busy'));cur=r.s.sessions.get(sid) + assert cur['phase']=='ready' and cur['fault_streak']==1 and cur['last_tick']==st['last_tick'] + r.s.sessions.operation(st,stage);r.s.sessions.record_fault(st,BridgeError('account_busy')) + assert r.s.sessions.get(sid)['phase']=='closing' + +def test_busy_outside_stages_closes(rig): + r=rig;st=session(r);r.s.sessions.operation(st,'attach');r.s.sessions.record_fault(st,BridgeError('account_busy')) + assert r.s.sessions.get(st['id'])['phase']=='closing' + +def test_busy_expired_lease_closes(rig): + r=rig;st=session(r);r.t[0]+=300;r.s.sessions.operation(st,'heartbeat');r.s.sessions.record_fault(st,BridgeError('account_busy')) + assert r.s.sessions.get(st['id'])['phase']=='closing' + +def test_real_bridge_lock_busy_admission_fallback(rig): + import threading,time + from scripts.colab_bridge import account_lock + r=rig;st=snapshot(r,session(r));status(r);r.s.sessions.observe(st) + locked=threading.Event();done=threading.Event();path=r.s.account_dir(r.account) + def holder(): + with account_lock(path):locked.set();time.sleep(9) + t=threading.Thread(target=holder);t.start();assert locked.wait(3) + from scripts.colab_bridge import BridgeError as RemoteError + def bridge(op,account,**kw): + try: + with account_lock(account):raise AssertionError('provider must not be reached') + except RemoteError as e:raise BridgeError(e.code) + bridge.installed=True;r.s.bridge=bridge;before=time.monotonic() + try: + result=submit(r);elapsed=time.monotonic()-before + assert elapsed<8 and r.s.job(r.owner,result['request_id'])['phase']=='queued' + finally:done.set();t.join() + + +@pytest.mark.parametrize('stage',['observe','heartbeat','upload','bootstrap_probe','job_probe']) +def test_real_busy_stage_survives_complete_next_cycle(rig,stage): + from test_review_r38_faults import running,probe_kind,running_status + r=rig;job=None + if stage=='job_probe':st,job=running(r) + else: + st=session(r,'uploading' if stage=='upload' else 'bootstrap' if stage=='bootstrap_probe' else 'ready',**({'launch_at':r.t[0]} if stage=='bootstrap_probe' else {})) + if stage in {'upload','bootstrap_probe'}:st=r.s.sessions.freeze(st) + if stage=='observe':r.t[0]+=60 + else:r.t[0]+=10 + def hook(op,kw): + if probe_kind(op,kw)==({'observe':'account_status'}.get(stage,stage)):raise BridgeError('account_busy') + if job and probe_kind(op,kw)=='job_probe':return running_status(job) + r.b.hook=hook + if job:r.s.tick(job) + else:r.s.sessions.tick_all() + current=r.s.sessions.get(st['id']);assert current['phase'] not in {'closing','closed'} and current['fault_streak']==1 + assert current['last_tick']==st['last_tick'] + r.b.hook=None;r.t[0]+=10 + if job: + r.s.sessions.tick_all() + r.b.hook=lambda op,kw:running_status(job) if probe_kind(op,kw)=='job_probe' else None + r.s.tick(job) + else:r.s.sessions.tick_all() + assert r.s.sessions.get(st['id'])['fault_streak']==0 diff --git a/scripts/test_compute_r40v5_log_stats.py b/scripts/test_compute_r40v5_log_stats.py new file mode 100644 index 0000000..48564c7 --- /dev/null +++ b/scripts/test_compute_r40v5_log_stats.py @@ -0,0 +1,64 @@ +import pytest +from review_r38_fixture import rig + +@pytest.mark.parametrize('stats,expected',[ + ({'log_bytes':987654321,'previous_log_bytes':876543219},True), + ({'log_bytes':True,'previous_log_bytes':0},False), + ({'log_bytes':1.2,'previous_log_bytes':0},False), + ({'log_bytes':-1,'previous_log_bytes':0},False), + ({'log_bytes':2**40+1,'previous_log_bytes':0},False), + ({'log_bytes':1,'previous_log_bytes':0,'other':1},False), + ({'log_bytes':1},False),([],False),('text',False)]) +def test_private_log_sizes(rig,stats,expected): + import json + from test_review_r38_faults import running,probe_kind + r=rig;st,job=running(r) + def hook(op,kw): + if probe_kind(op,kw)=='job_probe': + return {'stdout':'WEB_COMFYUI_JSON='+json.dumps({'status':{'job_id':job['id'],'manifest_sha256':job['manifest_sha256'],'phase':'running'},'worker_dead':False,'log_stats':stats})} + r.b.hook=hook;r.s.tick(job);current=r.s.sessions.get(st['id']) + assert ('private_log_stats' in current)==expected + assert 'private_log_stats' not in str(r.s.sessions.public(current)) + assert 'log_bytes' not in str(r.s.public_job(r.s.job(r.owner,job['id']),owner=r.owner)) + assert '987654321' not in str(r.s.snapshot(r.owner)) and '876543219' not in str(r.s.snapshot(r.owner)) + + +def test_missing_remote_log_does_not_change_probe_result(rig,tmp_path,monkeypatch): + import contextlib,io,json + from test_review_r38_faults import running + r=rig;st,job=running(r);captured=[] + def probe(state,code): + captured.append(code) + return {'status':{'job_id':job['id'],'manifest_sha256':job['manifest_sha256'],'phase':'running'},'worker_dead':False} + monkeypatch.setattr(r.s,'_exec',probe);r.s.tick(job) + code=captured[-1].replace('/content/web-comfyui/',str(tmp_path/'jobs')+'/').replace('/content/castle-sessions/',str(tmp_path/'sessions')+'/') + out=io.StringIO() + with contextlib.redirect_stdout(out):exec(compile(code,'remote-probe','exec'),{}) + got=json.loads(out.getvalue().split('WEB_COMFYUI_JSON=',1)[1]) + assert got=={'status':None,'artifacts':None,'worker_dead':False} + assert 'private_log_stats' not in r.s.sessions.get(st['id']) + + +def test_reused_kernel_discards_previous_stats_when_lstat_fails(rig,tmp_path,monkeypatch): + import contextlib,io,json + from test_review_r38_faults import running + r=rig;st,job=running(r);captured=[] + def probe(state,code): + captured.append(code) + return {'status':{'job_id':job['id'],'manifest_sha256':job['manifest_sha256'],'phase':'running'},'worker_dead':False} + monkeypatch.setattr(r.s,'_exec',probe);r.s.tick(job) + code=captured[-1].replace('/content/web-comfyui/',str(tmp_path/'jobs')+'/').replace('/content/castle-sessions/',str(tmp_path/'sessions')+'/') + log=tmp_path/'sessions'/st['id']/'job-evidence'/job['id']/'comfy-startup.log' + log.parent.mkdir(parents=True);log.write_text('sample') + namespace={} + def run(): + out=io.StringIO() + with contextlib.redirect_stdout(out):exec(compile(code,'remote-probe','exec'),namespace) + return json.loads(out.getvalue().split('WEB_COMFYUI_JSON=',1)[1]) + assert run()['log_stats']=={'log_bytes':6,'previous_log_bytes':0} + original=type(log).lstat + def blocked(path,*a,**k): + if path==log:raise PermissionError('private') + return original(path,*a,**k) + monkeypatch.setattr(type(log),'lstat',blocked) + assert 'log_stats' not in run() diff --git a/scripts/test_compute_r40v5_restart_hold.py b/scripts/test_compute_r40v5_restart_hold.py new file mode 100644 index 0000000..2b9ab87 --- /dev/null +++ b/scripts/test_compute_r40v5_restart_hold.py @@ -0,0 +1,633 @@ +"""Deterministic regression coverage for the yielded worker/sweeper handoff.""" +import fcntl +import json +import queue +import sqlite3 +import threading +import uuid +from pathlib import Path + +import pytest +import colab_service as cs +from scripts import colab_lease_sweeper as sweeper + + +class Clock: + def __init__(self, now=1000.0): + self.now = now + + def __call__(self): + return self.now + + +@pytest.fixture +def setup_service(tmp_path, monkeypatch): + monkeypatch.setenv('CASTLE_COLAB_DB_NESTING', 'strict') + clock = Clock() + return cs.ColabService(tmp_path / 'colab', bridge=lambda *a, **k: {}, clock=clock), clock + + +def uid(): + return str(uuid.uuid4()) + + +def lock_available(service): + with (service.root / 'worker.lock').open('a') as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return False + fcntl.flock(lock, fcntl.LOCK_UN) + return True + + +def assigned_session(service): + session = service.sessions.new_state('owner', uid(), 'a' * 64, + {'idle_minutes': 20, 'hard_hours': 6, 'max_units': 120}) + session.update(phase='arming', runtime_id='fixture-runtime', watchdog_armed=False, deadline_epoch=22000) + with service.db() as db: + db.execute('INSERT INTO work_sessions VALUES (?,?,?)', (session['id'], 'owner', cs.encoded(session))) + return session + + +class Driver: + """Advance the real worker only at an explicitly permitted virtual sleep.""" + def __init__(self, monkeypatch): + self.events = queue.Queue() + self.permits = threading.Semaphore(0) + self.stopping = False + self.errors = [] + monkeypatch.setattr(cs.time, 'sleep', self.sleep) + + def sleep(self, seconds): + self.events.put(('sleep', seconds)) + if not self.permits.acquire(timeout=5) or self.stopping: + raise SystemExit + + def instrument(self, service, monkeypatch): + loop = service._loop + def run(): + try: + loop() + except SystemExit: + pass + except BaseException as error: + self.errors.append(error) + finally: + self.events.put(('exit', None)) + monkeypatch.setattr(service, '_loop', run) + + def event(self, expected, value=None): + event = self.events.get(timeout=5) + assert event == (expected, value) + + def advance(self): + self.permits.release() + + def finish(self, thread): + thread.join(timeout=5) + assert not thread.is_alive() and not self.errors + + def stop(self, thread): + if thread and thread.is_alive(): + self.stopping = True + self.advance() + self.event('exit') + self.finish(thread) + assert not self.errors + + +def yield_worker(service, monkeypatch): + def fail(): + raise sqlite3.OperationalError('fixture') + monkeypatch.setattr(service.sessions, 'tick_all', fail) + driver = Driver(monkeypatch) + driver.instrument(service, monkeypatch) + service.start() + thread = service._thread + driver.event('sleep', 10); driver.advance() + driver.event('sleep', 10); driver.advance() + driver.event('exit'); driver.finish(thread) + return driver, thread + + +def test_pipeline_assigned_runtime_handoff_deterministic(setup_service, tmp_path, monkeypatch): + """T-H1: real execution -> pipeline -> router -> web cancellation, 100:1 virtual time.""" + from compute_pipeline import ComputePipeline + from compute_routing import ComputeRouter, ComputeAdapter + from compute_execution import PipelineExecution + from compute_web import ComputeWeb + + s, clock = setup_service + owner = 'owner'; pipeline_id = uid(); account = uid() + web = object.__new__(ComputeWeb); web.colab = s + adapter = ComputeAdapter(lambda *a: None, lambda *a: None, web.status_colab, web.cancel_colab) + router = ComputeRouter(tmp_path / 'router.sqlite3', {'colab': adapter}, clock=clock) + pipe = ComputePipeline(tmp_path / 'pipeline.sqlite3', router_factory=lambda _: router, + artifact_resolver=lambda *a: None, clock=clock) + state = pipe.create(owner, pipeline_id, + {'version': 1, 'steps': [{'id': 'one', 'request': {'featureId': 'fixture'}, 'placement': 'colab'}]}) + job_id = state['steps'][0]['request_id'] + session = assigned_session(s) + with s.db() as db: + db.execute('INSERT INTO jobs VALUES (?,?,?,?,?)', (job_id, owner, account, 'fixture', cs.encoded( + {'id': job_id, 'phase': 'queued', 'account_id': account, 'session_id': session['id'], 'session_job': True}))) + receipt = {'state': 'queued', 'downstream_id': job_id, 'cancel_supported': True} + with router._db() as db: + db.execute('INSERT INTO compute_requests VALUES (?,?,?,?,?,?,?,?,?,?,?)', + (owner, job_id, 'fixture', 'colab', 'colab', 'queued', '{}', '{}', json.dumps(receipt), 1, 1)) + with pipe._db() as db: + db.execute('UPDATE compute_pipelines SET cancel_requested=1 WHERE owner=? AND pipeline_id=?', (owner, pipeline_id)) + db.execute("UPDATE compute_pipeline_attempts SET state='queued',receipt_json=? WHERE owner=? AND pipeline_id=?", + (json.dumps(receipt), owner, pipeline_id)) + + attempts = []; operations = []; samples = []; sweep_results = []; trace = [] + def fail(): + attempts.append(clock.now) + raise RuntimeError('fixture supervision failure') + def bridge(op, _directory, **kwargs): + operations.append(op) + if op == 'runtime_stop': return {'stopped': True} + if op == 'account_status': return {} # Keep the cancelling pipeline active after release. + raise AssertionError(op) + monkeypatch.setattr(s.sessions, 'tick_all', fail) + driver = Driver(monkeypatch); driver.instrument(s, monkeypatch) + state_machine = {'due': None, 'pending_yield': False, 'premature': 0, 'starts': 0} + original_start = s.start + def capture_start(): + before = s._thread + original_start() + if s._thread is not before: + if state_machine['pending_yield']: + state_machine['premature'] += 1 + state_machine['starts'] += 1 + trace.append(('start', clock.now)) + driver.event('sleep', 10) + state_machine['due'] = clock.now + 10 + monkeypatch.setattr(s, 'start', capture_start) + + def advance_worker(): + if state_machine['due'] is not None and clock.now >= state_machine['due']: + driver.advance() + kind, value = driver.events.get(timeout=5) + if kind == 'sleep': + assert value == 10 + state_machine['due'] = clock.now + 10 + else: + assert (kind, value) == ('exit', None) + driver.finish(s._thread) + trace.append(('yield', clock.now)) + state_machine['pending_yield'] = True + state_machine['due'] = None + + def attempt_sweep(): + nonlocal session + if s.sessions.get(session['id'])['released']: + session = assigned_session(s) + before_stops = operations.count('runtime_stop') + assert not s.sessions.get(session['id'])['watchdog_armed'] + acquired = sweeper.sweep(s.root, bridge=bridge, clock=clock) + released = s.sessions.get(session['id'])['released'] + stopped = operations.count('runtime_stop') == before_stops + 1 + sweep_results.append((acquired, released, stopped)) + trace.append(('sweep', clock.now)) + if acquired: + state_machine['pending_yield'] = False + + class StopProbe(BaseException): + pass + class Wake: + count = 0 + def wait(self, seconds): + assert seconds == 5 + self.count += 1 + for index in range(10): + clock.now += 0.5 # 10 samples per five simulated seconds, as in the review. + if self.count in (60, 120) and index == 9: + attempt_sweep() # Attempt before an iteration due at this exact instant. + advance_worker() + samples.append(not lock_available(s)) + if self.count == 125: + raise StopProbe + def clear(self): + pass + + execution = object.__new__(PipelineExecution) + execution.engine = pipe; execution._wake = Wake() + try: + with pytest.raises(StopProbe): + execution._loop() + finally: + driver.stop(s._thread) + held = sum(samples) + print('H1 held=%d/%d reviewer=1008/1250 starts=%d premature=%d sweeps=%s' % + (held, len(samples), state_machine['starts'], state_machine['premature'], sweep_results)) + assert s.job(owner, job_id)['cancel_requested'] is True + assert len(samples) == 1250 and len(attempts) >= 3 + assert state_machine['premature'] == 0, 'worker restarted before a sweeper finished after yield' + assert len(sweep_results) == 2 and all(all(result) for result in sweep_results) + assert any(kind == 'yield' for kind, _ in trace) + + +def test_fifty_starts_wait_for_real_sweeper(setup_service, monkeypatch, caplog): + """T-H2: the actual sweeper releases an assigned unarmed runtime before restart.""" + s, clock = setup_service + session = assigned_session(s) + driver, first = yield_worker(s, monkeypatch) + marker = s.root / 'worker-yield.json' + assert json.loads(marker.read_text()) == {'yielded_at': clock.now, 'sweep_run_id': None} + assert marker.stat().st_mode & 0o777 == 0o600 + assert not list(s.root.glob('worker-yield.json.*.tmp')) + for _ in range(50): s.start() + assert s._thread is first and not first.is_alive() and lock_available(s) + assert sum('colab_worker_start_held' in r.message for r in caplog.records) == 1 + operations = [] + def bridge(op, _directory, **kwargs): + operations.append(op) + return {'stopped': True} if op == 'runtime_stop' else {} + clock.now += 300 + assert sweeper.sweep(s.root, bridge=bridge, clock=clock) + assert 'runtime_stop' in operations and s.sessions.get(session['id'])['released'] + finished = s.root / 'sweeper-last-run.json' + finished_data = json.loads(finished.read_text()) + assert set(finished_data) == {'finished_at', 'run_id'} and finished_data['finished_at'] == clock.now + assert s._valid_sweeper_run_id(finished_data['run_id']) + assert finished.stat().st_mode & 0o777 == 0o600 + assert not list(s.root.glob('sweeper-last-run.json.*.tmp')) + monkeypatch.setattr(s.sessions, 'tick_all', lambda: None) + try: + s.start(); second = s._thread + driver.event('sleep', 10) + assert second is not first and second.is_alive() and not lock_available(s) and not marker.exists() + finally: + driver.stop(s._thread) + + +def test_restart_hold_expires_at_900_seconds(setup_service, monkeypatch): + """T-H3: 899 seconds remains held, 900 seconds permits a new worker.""" + s, clock = setup_service + driver, first = yield_worker(s, monkeypatch) + yielded = clock.now + clock.now = yielded + 899 + s.start(); assert s._thread is first and not first.is_alive() + clock.now = yielded + 900 + monkeypatch.setattr(s.sessions, 'tick_all', lambda: None) + try: + s.start(); driver.event('sleep', 10) + assert s._thread is not first and s._thread.is_alive() and not lock_available(s) + assert not (s.root / 'worker-yield.json').exists() + finally: + driver.stop(s._thread) + + +def test_clock_reversal_and_malformed_yield_markers(setup_service, caplog): + """T-H4: reject malformed data and log unreadable only once per instance.""" + s, clock = setup_service + marker = s.root / 'worker-yield.json' + marker.write_text(json.dumps({'yielded_at': clock.now + 1, 'sweep_run_id': None})) + assert not s._restart_held() and not marker.exists() + for data in ('{', '[]', '{"yielded_at":"1000"}', '{"yielded_at":NaN}', '{"yielded_at":true}'): + marker.write_text(data) + assert not s._restart_held() and not marker.exists() + assert sum('colab_worker_yield_marker_unreadable' in r.message for r in caplog.records) == 1 + + +def test_marker_oserrors_are_not_held_and_log_once(setup_service, monkeypatch, caplog): + s, clock = setup_service + marker = s.root / 'worker-yield.json' + marker.write_text(json.dumps({'yielded_at': clock.now, 'sweep_run_id': None})) + read = Path.read_text + def fail_read(path, *args, **kwargs): + if path == marker: raise PermissionError('fixture') + return read(path, *args, **kwargs) + with monkeypatch.context() as m: + m.setattr(Path, 'read_text', fail_read) + assert not s._restart_held() + assert not marker.exists() + marker.write_text(json.dumps({'yielded_at': clock.now, 'sweep_run_id': None})) + sweeper_marker = s.root / 'sweeper-last-run.json' + def fail_sweeper_read(path, *args, **kwargs): + if path == sweeper_marker: raise PermissionError('fixture') + return read(path, *args, **kwargs) + with monkeypatch.context() as m: + m.setattr(Path, 'read_text', fail_sweeper_read) + assert s._restart_held() and marker.exists() + clock.now += 900 + unlink = Path.unlink + def fail_unlink(path, *args, **kwargs): + if path == marker: raise PermissionError('fixture') + return unlink(path, *args, **kwargs) + with monkeypatch.context() as m: + m.setattr(Path, 'unlink', fail_unlink) + assert not s._restart_held() + assert sum('colab_worker_yield_marker_unreadable' in r.message for r in caplog.records) == 1 + + +def test_sweeper_marker_validation_and_hold_logging(setup_service, caplog): + s, clock = setup_service + marker = s.root / 'worker-yield.json' + finished = s.root / 'sweeper-last-run.json' + marker.write_text(json.dumps({'yielded_at': clock.now, 'sweep_run_id': None})) + for data in ('{', '[]', '{"run_id":"short"}', '{"run_id":true}', + '{"run_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}', '{"finished_at":999}'): + finished.write_text(data) + assert s._restart_held() and marker.exists() + assert sum('colab_worker_start_held' in r.message for r in caplog.records) == 1 + assert not any('colab_worker_yield_marker_unreadable' in r.message for r in caplog.records) + clock.now += 1 + marker.write_text(json.dumps({'yielded_at': clock.now, 'sweep_run_id': None})) + assert s._restart_held() + assert sum('colab_worker_start_held' in r.message for r in caplog.records) == 2 + finished.write_text(json.dumps({'finished_at': clock.now, 'run_id': 'a' * 32})) + assert not s._restart_held() and not marker.exists() + + +def test_sweeper_records_exception_but_not_busy_or_absent(setup_service, tmp_path, monkeypatch): + """T-H5: the marker is written in finally, only after the real lock is acquired.""" + s, clock = setup_service + marker = s.root / 'sweeper-last-run.json' + with (s.root / 'worker.lock').open('a') as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + assert not sweeper.sweep(s.root, bridge=object(), clock=clock) + assert not marker.exists() + assert not sweeper.sweep(tmp_path / 'missing', bridge=object(), clock=clock) + assert not (tmp_path / 'missing' / 'sweeper-last-run.json').exists() + def fail(*args, **kwargs): raise RuntimeError('fixture') + monkeypatch.setattr(sweeper, 'ColabService', fail) + with pytest.raises(RuntimeError, match='fixture'): + sweeper.sweep(s.root, bridge=object(), clock=clock) + finished_data = json.loads(marker.read_text()) + assert set(finished_data) == {'finished_at', 'run_id'} and finished_data['finished_at'] == clock.now + assert s._valid_sweeper_run_id(finished_data['run_id']) + assert marker.stat().st_mode & 0o777 == 0o600 and lock_available(s) + + +def test_sweeper_swallows_only_marker_oserrors(setup_service, monkeypatch): + s, clock = setup_service + def fail_os(*args, **kwargs): + assert not lock_available(s) + raise OSError('fixture') + monkeypatch.setattr(sweeper, 'private_write', fail_os) + assert sweeper.sweep(s.root, bridge=object(), clock=clock) + assert lock_available(s) and not (s.root / 'sweeper-last-run.json').exists() + def fail_other(*args, **kwargs): raise ValueError('fixture') + monkeypatch.setattr(sweeper, 'private_write', fail_other) + with pytest.raises(ValueError, match='fixture'): + sweeper.sweep(s.root, bridge=object(), clock=clock) + assert lock_available(s) + + +def test_no_yield_preserves_start_and_success_order(setup_service, monkeypatch): + """T-H6: one live thread, original success order, and no marker writes.""" + s, clock = setup_service + order = [] + monkeypatch.setattr(s, '_job_states', lambda: order.append('rows') or [{'id': 'fixture', 'phase': 'running'}]) + monkeypatch.setattr(s.sessions, 'tick_all', lambda: order.append('sessions')) + monkeypatch.setattr(s, 'tick', lambda state: order.append('job')) + driver = Driver(monkeypatch); driver.instrument(s, monkeypatch) + try: + s.start(); first = s._thread; driver.event('sleep', 10) + for _ in range(50): s.start() + assert s._thread is first and first.is_alive() and not lock_available(s) + assert order == ['rows', 'sessions', 'job'] + assert not (s.root / 'worker-yield.json').exists() + assert not (s.root / 'sweeper-last-run.json').exists() + finally: + driver.stop(s._thread) + assert lock_available(s) + assert not (s.root / 'worker-yield.json').exists() + assert not (s.root / 'sweeper-last-run.json').exists() + + +def test_yield_marker_write_failure_releases_lock(setup_service, monkeypatch, caplog): + """T-H7: even an atomic-write exception cannot retain the lock.""" + s, clock = setup_service + def fail(*args, **kwargs): + assert not lock_available(s) + raise PermissionError('private detail') + monkeypatch.setattr(cs, 'private_write', fail) + driver, thread = yield_worker(s, monkeypatch) + assert not thread.is_alive() and lock_available(s) + assert not (s.root / 'worker-yield.json').exists() + assert sum('colab_worker_yield_marker_failed exception=PermissionError' in r.message for r in caplog.records) == 1 + assert all('private detail' not in r.message for r in caplog.records) + + +def test_pipeline_fixed_clock_rearm_waits_for_new_sweep(setup_service, tmp_path, monkeypatch): + """T-H8: two real cancellations at one timestamp need two distinct sweeps.""" + from compute_pipeline import ComputePipeline + from compute_routing import ComputeRouter, ComputeAdapter + from compute_execution import PipelineExecution + from compute_web import ComputeWeb + + s, clock = setup_service + owner, pipeline_id, account = 'owner', uid(), uid() + web = object.__new__(ComputeWeb); web.colab = s + adapter = ComputeAdapter(lambda *a: None, lambda *a: None, web.status_colab, web.cancel_colab) + router = ComputeRouter(tmp_path / 'router.sqlite3', {'colab': adapter}, clock=clock) + pipe = ComputePipeline(tmp_path / 'pipeline.sqlite3', router_factory=lambda _: router, + artifact_resolver=lambda *a: None, clock=clock) + state = pipe.create(owner, pipeline_id, + {'version': 1, 'steps': [{'id': 'one', 'request': {'featureId': 'fixture'}, 'placement': 'colab'}]}) + job_id = state['steps'][0]['request_id'] + first_session = assigned_session(s) + with s.db() as db: + db.execute('INSERT INTO jobs VALUES (?,?,?,?,?)', (job_id, owner, account, 'fixture', cs.encoded( + {'id': job_id, 'phase': 'queued', 'account_id': account, 'session_id': first_session['id'], 'session_job': True}))) + receipt = {'state': 'queued', 'downstream_id': job_id, 'cancel_supported': True} + with router._db() as db: + db.execute('INSERT INTO compute_requests VALUES (?,?,?,?,?,?,?,?,?,?,?)', + (owner, job_id, 'fixture', 'colab', 'colab', 'queued', '{}', '{}', json.dumps(receipt), 1, 1)) + with pipe._db() as db: + db.execute('UPDATE compute_pipelines SET cancel_requested=1 WHERE owner=? AND pipeline_id=?', (owner, pipeline_id)) + db.execute("UPDATE compute_pipeline_attempts SET state='queued',receipt_json=? WHERE owner=? AND pipeline_id=?", + (json.dumps(receipt), owner, pipeline_id)) + + def fail(): raise sqlite3.OperationalError('fixture') + monkeypatch.setattr(s.sessions, 'tick_all', fail) + driver = Driver(monkeypatch); driver.instrument(s, monkeypatch) + operations = [] + def bridge(op, _directory, **kwargs): + operations.append(op) + if op == 'runtime_stop': return {'stopped': True} + if op == 'account_status': return {} + raise AssertionError(op) + outcome = {'premature': 0, 'sweeps': [], 'last': None, 'session': first_session} + def finish_yield(): + driver.event('sleep', 10); driver.advance() + driver.event('sleep', 10); driver.advance() + driver.event('exit'); driver.finish(s._thread) + assert lock_available(s) + def attempt_sweep(): + session = outcome['session']; before = operations.count('runtime_stop') + assert not s.sessions.get(session['id'])['watchdog_armed'] + acquired = sweeper.sweep(s.root, bridge=bridge, clock=clock) + released = s.sessions.get(session['id'])['released'] + stopped = operations.count('runtime_stop') == before + 1 + outcome['sweeps'].append((acquired, released, stopped)) + + class StopProbe(BaseException): pass + class Wake: + count = 0 + def wait(self, seconds): + assert seconds == 5 + self.count += 1 + if self.count == 1: + finish_yield(); attempt_sweep() + outcome['session'] = assigned_session(s) + elif self.count == 2: + finish_yield(); outcome['last'] = s._thread + else: + if s._thread is not outcome['last']: + outcome['premature'] += 1 + outcome['last'] = s._thread + driver.event('sleep', 10) + if self.count < 7: + driver.advance(); driver.event('sleep', 10); driver.advance() + driver.event('exit'); driver.finish(s._thread) + if self.count == 7: + attempt_sweep() + raise StopProbe + def clear(self): pass + + execution = object.__new__(PipelineExecution) + execution.engine = pipe; execution._wake = Wake() + try: + with pytest.raises(StopProbe): execution._loop() + finally: + driver.stop(s._thread) + print('H8 premature=%d sweeps=%s fixed_clock=%s' % (outcome['premature'], outcome['sweeps'], clock.now)) + assert s.job(owner, job_id)['cancel_requested'] is True + assert outcome['premature'] == 0 + assert outcome['sweeps'] == [(True, True, True), (True, True, True)] + + +def test_zero_time_without_prior_sweep_is_held(setup_service, monkeypatch): + """T-H9: zero is a real yield time, not evidence of a previous sweep.""" + s, clock = setup_service; clock.now = 0.0 + session = assigned_session(s) + driver, first = yield_worker(s, monkeypatch) + marker = s.root / 'worker-yield.json' + assert json.loads(marker.read_text()) == {'yielded_at': 0.0, 'sweep_run_id': None} + assert not (s.root / 'sweeper-last-run.json').exists() + s.start(); assert s._thread is first and not first.is_alive() and lock_available(s) + operations = [] + def bridge(op, _directory, **kwargs): + operations.append(op) + return {'stopped': True} if op == 'runtime_stop' else {} + assert sweeper.sweep(s.root, bridge=bridge, clock=clock) + assert 'runtime_stop' in operations and s.sessions.get(session['id'])['released'] + monkeypatch.setattr(s.sessions, 'tick_all', lambda: None) + try: + s.start(); driver.event('sleep', 10) + assert s._thread is not first and s._thread.is_alive() and not marker.exists() + finally: + driver.stop(s._thread) + + +def test_mode000_yield_marker_is_deleted_on_start(setup_service, monkeypatch, caplog): + """T-H10: a read error must attempt deletion before starting a worker.""" + s, clock = setup_service + marker = s.root / 'worker-yield.json' + marker.write_text(json.dumps({'yielded_at': clock.now, 'sweep_run_id': None})) + marker.chmod(0) + class DummyThread: + def __init__(self, **kwargs): self.started = False + def start(self): self.started = True + def is_alive(self): return self.started + monkeypatch.setattr(cs.threading, 'Thread', DummyThread) + try: + s.start() + assert s._thread is not None and s._thread.started and not marker.exists() + assert sum('colab_worker_yield_marker_unreadable' in r.message for r in caplog.records) == 1 + finally: + if marker.exists(): marker.chmod(0o600) + + +def test_malformed_sweeper_at_yield_then_valid_run_releases(setup_service, monkeypatch): + """T-H11a: a later valid sweep is distinct from an unreadable baseline.""" + s, clock = setup_service + finished = s.root / 'sweeper-last-run.json'; finished.write_text('{') + driver, first = yield_worker(s, monkeypatch) + marker = s.root / 'worker-yield.json' + assert json.loads(marker.read_text())['sweep_run_id'] is None + s.start(); assert s._thread is first and not first.is_alive() + assert sweeper.sweep(s.root, bridge=object(), clock=clock) + monkeypatch.setattr(s.sessions, 'tick_all', lambda: None) + try: + s.start(); driver.event('sleep', 10) + assert s._thread is not first and s._thread.is_alive() and not marker.exists() + finally: + driver.stop(s._thread) + + +def test_valid_sweeper_at_yield_then_malformed_holds_to_timeout(setup_service, monkeypatch): + """T-H11b: an invalid later record cannot prove another sweep occurred.""" + s, clock = setup_service + assert sweeper.sweep(s.root, bridge=object(), clock=clock) + previous = s._sweeper_run_id(); assert previous is not None + driver, first = yield_worker(s, monkeypatch) + marker = s.root / 'worker-yield.json' + assert json.loads(marker.read_text())['sweep_run_id'] == previous + (s.root / 'sweeper-last-run.json').write_text('{') + s.start(); assert s._thread is first and not first.is_alive() + clock.now += 899; s.start(); assert s._thread is first + clock.now += 1 + monkeypatch.setattr(s.sessions, 'tick_all', lambda: None) + try: + s.start(); driver.event('sleep', 10) + assert s._thread is not first and s._thread.is_alive() and not marker.exists() + finally: + driver.stop(s._thread) + + +def test_failed_sweeper_marker_write_holds_until_timeout(setup_service, monkeypatch): + """T-H12: a successful sweep whose marker fails cannot release the hold.""" + s, clock = setup_service + assert sweeper.sweep(s.root, bridge=object(), clock=clock) + previous = s._sweeper_run_id(); assert previous is not None + driver, first = yield_worker(s, monkeypatch) + def fail_write(*args, **kwargs): raise OSError('fixture') + with monkeypatch.context() as m: + m.setattr(sweeper, 'private_write', fail_write) + assert sweeper.sweep(s.root, bridge=object(), clock=clock) + assert s._sweeper_run_id() == previous + s.start(); assert s._thread is first and not first.is_alive() + clock.now += 899; s.start(); assert s._thread is first + clock.now += 1 + monkeypatch.setattr(s.sessions, 'tick_all', lambda: None) + try: + s.start(); driver.event('sleep', 10) + assert s._thread is not first and s._thread.is_alive() + finally: + driver.stop(s._thread) + + +def test_invalid_yield_run_ids_are_deleted_and_warn_once(setup_service, caplog): + s, clock = setup_service + marker = s.root / 'worker-yield.json' + values = ('short', 'A' * 32, 'g' * 32, 'a' * 31, 'a' * 33, True, 42, [], {}) + for value in values: + marker.write_text(json.dumps({'yielded_at': clock.now, 'sweep_run_id': value})) + assert not s._restart_held() and not marker.exists() + marker.write_text(json.dumps({'yielded_at': clock.now})) + assert not s._restart_held() and not marker.exists() + assert sum('colab_worker_yield_marker_unreadable' in r.message for r in caplog.records) == 1 + + +def test_hold_log_is_once_per_yield_time_and_sweep_id(setup_service, caplog): + s, clock = setup_service + marker = s.root / 'worker-yield.json'; finished = s.root / 'sweeper-last-run.json' + for run_id in ('a' * 32, 'b' * 32, 'a' * 32): + marker.write_text(json.dumps({'yielded_at': clock.now, 'sweep_run_id': run_id})) + finished.write_text(json.dumps({'finished_at': -1, 'run_id': run_id})) + assert s._restart_held() and s._restart_held() + assert sum('colab_worker_start_held' in r.message for r in caplog.records) == 2 + + +def test_each_sweeper_run_gets_a_new_id_even_at_equal_time(setup_service): + s, clock = setup_service + assert sweeper.sweep(s.root, bridge=object(), clock=clock) + first = s._sweeper_run_id(); assert first is not None + assert sweeper.sweep(s.root, bridge=object(), clock=clock) + second = s._sweeper_run_id(); assert second is not None and second != first diff --git a/scripts/test_compute_r40v5_worker_yield.py b/scripts/test_compute_r40v5_worker_yield.py new file mode 100644 index 0000000..e3e7406 --- /dev/null +++ b/scripts/test_compute_r40v5_worker_yield.py @@ -0,0 +1,240 @@ +"""Worker supervision yields its real flock without weakening job isolation.""" +import fcntl +import json +import os +import queue +import sqlite3 +import threading +import uuid +from pathlib import Path +import pytest +import colab_service as cs +from scripts import colab_lease_sweeper + + +@pytest.fixture +def service(tmp_path, monkeypatch): + monkeypatch.setenv('CASTLE_COLAB_DB_NESTING', 'strict') + return cs.ColabService(tmp_path / 'colab', bridge=object(), clock=lambda: 1000.0) + + +def ident(): + return str(uuid.uuid4()) + + +def add_job(s, raw, job_id=None): + job_id = job_id or ident() + with s.db() as db: + db.execute('INSERT INTO jobs VALUES (?,?,?,?,?)', + (job_id, 'owner', 'account', 'fixture', raw)) + return job_id + + +class Driver: + def __init__(self, monkeypatch): + self.events = queue.Queue() + self.permits = threading.Semaphore(0) + self.stopping = False + self.errors = [] + self.sleeps = [] + monkeypatch.setattr(cs.time, 'sleep', self.sleep) + + def sleep(self, seconds): + self.sleeps.append(seconds) + self.events.put(seconds) + if not self.permits.acquire(timeout=5) or self.stopping: + raise SystemExit + + def wait(self, seconds=10): + assert self.events.get(timeout=3) == seconds + + def advance(self): + self.permits.release() + + def stop(self, thread): + self.stopping = True + self.permits.release() + thread.join(3) + assert not thread.is_alive() + assert not self.errors + + def run(self, service): + def invoke(): + try: + service._loop() + except SystemExit: + pass + except BaseException as error: + self.errors.append(error) + thread = threading.Thread(target=invoke, daemon=True) + thread.start() + return thread + + +def lock_available(s): + with (s.root / 'worker.lock').open('a') as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return False + fcntl.flock(lock, fcntl.LOCK_UN) + return True + + +def test_persistent_failure_yields_lock_and_real_sweeper_releases(service, monkeypatch): + """T-B1-1; this same test must fail on the revision-1 loop.""" + s = service + session = s.sessions.new_state('owner', ident(), 'a'*64, + {'idle_minutes':20, 'hard_hours':6, 'max_units':120}) + session.update(phase='arming', runtime_id='fixture-runtime', watchdog_armed=False, deadline_epoch=22600) + with s.db() as db: + db.execute('INSERT INTO work_sessions VALUES (?,?,?)', (session['id'], 'owner', cs.encoded(session))) + calls = [] + def fail(): + calls.append('sessions') + raise sqlite3.OperationalError('private') + monkeypatch.setattr(s.sessions, 'tick_all', fail) + d = Driver(monkeypatch); thread = d.run(s) + try: + d.wait(); assert not lock_available(s); d.advance() + d.wait(); d.advance(); thread.join(2) + assert not thread.is_alive(), 'worker retained lock after three unsupervised cycles' + assert calls == ['sessions']*3 and d.sleeps == [10, 10] + assert s.worker_iteration_failures == 3 and lock_available(s) + finally: + d.stop(thread) + bridge_calls = [] + def mock_call(self, state, op, **kwargs): + bridge_calls.append(op) + if op == 'runtime_stop': return {'stopped':True} + raise ValueError('mock status unavailable') + monkeypatch.setattr(cs.ColabService, '_call', mock_call) + assert colab_lease_sweeper.sweep(s.root, bridge=object(), clock=lambda:1000.0) + assert bridge_calls.count('runtime_stop') == 1 + assert s.sessions.get(session['id'])['released'] is True + + +def test_unreadable_rows_do_not_block_supervision(service, monkeypatch, caplog): + s=service + ids=[add_job(s, '{'), add_job(s, '[]'), add_job(s, '{}')] + good=ident(); add_job(s, json.dumps({'id':good,'phase':'running'}), good) + supervised=[]; ticked=[] + monkeypatch.setattr(s.sessions,'tick_all',lambda:supervised.append(1)) + monkeypatch.setattr(s,'tick',lambda state:ticked.append(state['id'])) + d=Driver(monkeypatch); thread=d.run(s) + try: + d.wait();d.advance();d.wait() + assert thread.is_alive() and not lock_available(s) + assert supervised == [1,1] and ticked == [good,good] + assert s.worker_iteration_failures == 0 and s.unreadable_job_rows == 6 + for bad in ids: assert caplog.text.count('colab_job_row_unreadable id='+bad)==1 + finally:d.stop(thread) + + +def test_bad_row_logging_is_process_wide_bounded_and_sanitized(service, tmp_path, monkeypatch, caplog): + monkeypatch.setattr(cs,'_unreadable_job_ids',set()) + other=cs.ColabService(tmp_path/'other',bridge=object(),clock=lambda:1000.0) + bad='not-a-canonical-uuid-private';ids=[bad]+[ident() for _ in range(20)] + for job_id in ids:add_job(service,'{',job_id) + add_job(other,'{',ids[1]);add_job(other,'{',ident()) + assert service._job_states()==[] and other._job_states()==[] + assert service.unreadable_job_rows==21 and other.unreadable_job_rows==2 + lines=[line for line in caplog.text.splitlines() if 'colab_job_row_unreadable' in line] + assert len(lines)==20 and sum('id=invalid' in line for line in lines)==1 + assert bad not in caplog.text and sum('id='+ids[1] in line for line in lines)==1 + + +def test_failed_scan_does_not_block_session_supervision(service, monkeypatch): + s=service;calls=[] + monkeypatch.setattr(s,'_job_states',lambda:(_ for _ in ()).throw(RuntimeError('private'))) + monkeypatch.setattr(s.sessions,'tick_all',lambda:calls.append('sessions')) + monkeypatch.setattr(s,'tick',lambda _:calls.append('job')) + d=Driver(monkeypatch);thread=d.run(s) + try: + for _ in range(4): d.wait();d.advance() + d.wait() + assert calls == ['sessions']*5 and thread.is_alive() and not lock_available(s) + assert s.worker_iteration_failures == 5 + finally:d.stop(thread) + + +def test_success_resets_consecutive_failures(service, monkeypatch): + s=service;calls=[] + def tick_all(): + calls.append(1) + if len(calls)!=3:raise RuntimeError('private') + monkeypatch.setattr(s.sessions,'tick_all',tick_all) + d=Driver(monkeypatch);thread=d.run(s) + try: + for _ in range(5): + d.wait();assert thread.is_alive() and not lock_available(s);d.advance() + thread.join(2) + assert not thread.is_alive() and len(calls)==6 and lock_available(s) + assert s.worker_iteration_failures==5 and d.sleeps == [10]*5 + finally:d.stop(thread) + + +def test_start_after_yield_waits_for_other_lock_holder(service, monkeypatch): + s=service;d=Driver(monkeypatch); calls=[] + def failing():calls.append('failed');raise RuntimeError('private') + monkeypatch.setattr(s.sessions,'tick_all',failing) + thread=d.run(s) + try: + d.wait();d.advance();d.wait();d.advance();thread.join(2) + assert not thread.is_alive() and lock_available(s) + s.start(); assert s._thread is None + assert colab_lease_sweeper.sweep(s.root, bridge=lambda *a, **k: {}, clock=s.clock) + other=(s.root/'worker.lock').open('a');fcntl.flock(other,fcntl.LOCK_EX|fcntl.LOCK_NB) + monkeypatch.setattr(s.sessions,'tick_all',lambda:calls.append('supervised')) + s.start(); restarted=s._thread + d.wait(1);assert restarted.is_alive() and calls==['failed']*3 + fcntl.flock(other,fcntl.LOCK_UN);other.close();d.advance() + d.wait();assert calls[-1]=='supervised' and not lock_available(s) + monkeypatch.setattr(s.sessions,'tick_all',failing) + d.advance();d.wait();d.advance();d.wait();d.advance();restarted.join(2) + assert not restarted.is_alive() and lock_available(s) + finally: + if thread.is_alive():d.stop(thread) + + +def test_failed_update_does_not_skip_next_job(service, monkeypatch): + s=service;first,second=ident(),ident();calls=[] + for item in (first,second):add_job(s,json.dumps({'id':item,'phase':'running'}),item) + monkeypatch.setattr(s.sessions,'tick_all',lambda:None) + def tick(state): + calls.append(state['id']) + if state['id']==first:raise RuntimeError('private') + monkeypatch.setattr(s,'tick',tick) + monkeypatch.setattr(s,'update',lambda *a,**k:(_ for _ in ()).throw(ValueError('private'))) + d=Driver(monkeypatch);thread=d.run(s) + try: + d.wait();assert calls==[first,second] and s.worker_iteration_failures==2 + finally:d.stop(thread) + + +def test_broken_logging_does_not_affect_worker_or_nested_guard(service, monkeypatch): + s=service;s._db_strict=False; add_job(s,'{') + monkeypatch.setattr(cs.logger,'warning',lambda *a,**k:(_ for _ in ()).throw(RuntimeError('private'))) + with s.db(): + with s.db() as db:assert db.execute('SELECT 1').fetchone()[0]==1 + assert s.nested_db_events == 1 + monkeypatch.setattr(s.sessions,'tick_all',lambda:(_ for _ in ()).throw(RuntimeError('private'))) + d=Driver(monkeypatch);thread=d.run(s) + try: + d.wait();d.advance();d.wait();d.advance();thread.join(2) + assert not thread.is_alive() and lock_available(s) + assert s.unreadable_job_rows==3 and s.worker_iteration_failures==3 + finally:d.stop(thread) + + +def test_connection_close_exception_restores_depth(service, monkeypatch): + original=cs.sqlite3.connect + class FailClose(sqlite3.Connection): + def close(self): + super().close() + raise RuntimeError('close failed') + monkeypatch.setattr(cs.sqlite3,'connect',lambda *a,**k:original(*a,**k,factory=FailClose)) + before=getattr(service._db_local,'depth',0) + with pytest.raises(RuntimeError,match='close failed'): + with service.db() as db:assert db.execute('SELECT 1').fetchone()[0]==1 + assert service._db_local.depth==before diff --git a/scripts/test_compute_r40v6_robustness.py b/scripts/test_compute_r40v6_robustness.py new file mode 100644 index 0000000..f6160d3 --- /dev/null +++ b/scripts/test_compute_r40v6_robustness.py @@ -0,0 +1,785 @@ +"""r40v6 robustness checks. The runner sets PYTHONPATH; this module does not.""" +import hashlib +import json +import logging +import os +import sqlite3 +import subprocess +import sys +import threading +import time +import uuid +from pathlib import Path + +import pytest + +os.environ.setdefault('CASTLE_COLAB_DB_NESTING', 'strict') + +import colab_service as cs +from colab_service import ColabError, ColabService +from compute_parity.journal import Journal +from compute_parity.provisioning import states +import compute_parity.journal as journal_mod +import compute_parity.private_assets as private_assets +import hosted_compute +from scripts.colab_rpc_transport import Budget, scoped + +R40V5_SUBMIT_PROBE_SHA256 = '6c1447f4f4092412d6f6ef7fdf0c46466bca0174330c71657648a56039c9bc5e' +R40V5_RESERVE_JOB = '{"account":"acct","artifacts":[],"case_id":"voice.demo","cost":{"amount":1,"unit":"CU"},"created_at":1700000000.0,"epoch":"legacy","identity":"ident","lane":"colab","owner":"owner","request_id":"88888888-8888-4888-8888-888888888888","reserved_amount":1,"state":"reserved"}' +SUBJECT = 'ab' * 32 +CLOCK = 1_000_000.0 + + +class Bridge: + installed = True + + def __call__(self, *args, **kwargs): + raise AssertionError('provider access forbidden') + + +def service(tmp_path): + clock = [CLOCK] + root = tmp_path / 'colab' + svc = ColabService(root, Bridge(), clock=lambda: clock[0]) + svc.start = lambda: None + owner = 'owner-a' + account = '11111111-1111-4111-8111-111111111111' + with svc.db() as db: + db.execute('INSERT INTO accounts VALUES (?,?,?,?)', (account, owner, 'lab', '{}')) + svc.admission_account = lambda *args, **kwargs: ( + {'authenticated': True, 'balance_compute_units': 500.0, 'checked_at': CLOCK}, + {'bound': True, 'subject_key': SUBJECT, 'verified_at': CLOCK}, + ) + return svc, clock, owner, account + + +def image_body(account, request_id=None): + return { + 'request_id': request_id or str(uuid.uuid4()), + 'account_id': account, + 'gpu': 'L4', + 'max_units': 20, + 'max_minutes': 60, + 'job': {'type': 'image', 'prompt': 'red square'}, + } + + +def native_spec(): + return {'type': 'image', 'bundle': {'models': [{'private': True, 'target': 'weights.safetensors'}]}} + + +def names(root): + jobs = root / 'jobs' + if not jobs.exists(): + return [] + return sorted(p.name for p in jobs.iterdir()) + + +def staging(root): + return [name for name in names(root) if name.startswith('.staging-')] + + +def job_row(svc, job_id): + with svc.db() as db: + row = db.execute('SELECT state FROM jobs WHERE id=?', (job_id,)).fetchone() + return None if row is None else json.loads(row[0]) + + +def patch_native_manifest(monkeypatch): + import scripts.colab_session_inputs as inputs + monkeypatch.setattr(inputs, 'validate_native_manifest', lambda manifest, directory, check_files=False: manifest) + + +def test_rb1_second_writer_during_freeze(tmp_path, monkeypatch): + svc, _clock, owner, account = service(tmp_path) + patch_native_manifest(monkeypatch) + body = image_body(account) + job_id = body['request_id'] + entered, release, committed = threading.Event(), threading.Event(), threading.Event() + errors, obs = [], {} + + def freeze(bundle, directory): + obs['staging'] = bool(staging(svc.root)) + obs['directory'] = (svc.root / 'jobs' / job_id).exists() + entered.set() + assert release.wait(30) + return [] + + monkeypatch.setattr(private_assets, 'freeze_private_models', freeze) + + def writer(): + assert entered.wait(3) + connection = sqlite3.connect(svc.root / 'state.sqlite3', timeout=15) + try: + connection.execute('BEGIN IMMEDIATE') + connection.execute( + 'INSERT INTO accounts VALUES (?,?,?,?)', + ('22222222-2222-4222-8222-222222222222', 'other', 'x', '{}'), + ) + connection.commit() + committed.set() + except sqlite3.OperationalError as error: + errors.append(str(error)) + finally: + connection.close() + release.set() + + def submit(): + svc._submit(owner, body, _native=native_spec()) + + worker = threading.Thread(target=writer, daemon=True) + submitter = threading.Thread(target=submit, daemon=True) + submitter.start() + try: + assert entered.wait(120) + worker.start() + worker.join(30) + finally: + release.set() + submitter.join(120) + assert not submitter.is_alive() + assert committed.is_set(), errors + assert obs.get('staging') and not obs.get('directory') + assert staging(svc.root) == [] + assert job_row(svc, job_id) is not None + + +def test_rb1_upload_and_state_match_base(tmp_path): + probe = r''' +import json, uuid +from pathlib import Path +import colab_service as cs +from colab_service import ColabService +class Bridge: + installed = True + def __call__(self, *a, **k): + raise AssertionError('provider') +clock = 1000000.0 +root = Path(sys_root) +svc = ColabService(root, Bridge(), clock=lambda: clock) +svc.start = lambda: None +owner, account = 'owner-a', '11111111-1111-4111-8111-111111111111' +rid = '33333333-3333-4333-8333-333333333333' +with svc.db() as db: + db.execute('INSERT INTO accounts VALUES (?,?,?,?)', (account, owner, 'lab', '{}')) +svc.admission_account = lambda *a, **k: ( + {'authenticated': True, 'balance_compute_units': 500.0, 'checked_at': clock}, + {'bound': True, 'subject_key': 'ab'*32, 'verified_at': clock}) +n = {'i': 0} +def fake(): + n['i'] += 1 + return uuid.UUID(int=n['i']) +cs.uuid.uuid4 = fake +body = {'request_id': rid, 'account_id': account, 'gpu': 'L4', 'max_units': 20, + 'max_minutes': 60, 'job': {'type': 'image', 'prompt': 'red square'}} +svc._submit(owner, body) +with svc.db() as db: + state = json.loads(db.execute('SELECT state FROM jobs WHERE id=?', (rid,)).fetchone()[0]) +files = [] +for path in sorted((root/'jobs'/rid).rglob('*')): + if path.is_file(): + files.append({'path': path.relative_to(root/'jobs'/rid).as_posix(), 'size': path.stat().st_size, + 'sha256': __import__('hashlib').sha256(path.read_bytes()).hexdigest()}) +print(json.dumps({'state': state, 'files': files}, sort_keys=True, separators=(',', ':'))) +''' + script = tmp_path / 'probe.py' + script.write_text('import sys\nsys_root = sys.argv[1]\n' + probe) + outputs = [] + for tree, dest in ((Path(cs.ROOT), tmp_path / 'work-out'),): + env = os.environ.copy() + env['PYTHONPATH'] = str(tree / 'webui') + os.pathsep + str(tree) + env['PYTHONDONTWRITEBYTECODE'] = '1' + env['CASTLE_COLAB_DB_NESTING'] = 'strict' + result = subprocess.run( + [sys.executable, '-B', str(script), str(dest)], + cwd=tmp_path, env=env, text=True, capture_output=True, timeout=180, + ) + assert result.returncode == 0, result.stderr[-500:] + outputs.append(result.stdout.strip()) + assert [hashlib.sha256(text.encode('utf-8')).hexdigest() for text in outputs] == [R40V5_SUBMIT_PROBE_SHA256] + + +def test_rb1_duplicate_removes_staging(tmp_path, monkeypatch): + svc, _clock, owner, account = service(tmp_path) + body = image_body(account) + first = svc._submit(owner, body) + assert staging(svc.root) == [] + second = svc._submit(owner, body) + assert second['id'] == first['id'] + assert staging(svc.root) == [] + with svc.db() as db: + assert db.execute('SELECT count(*) FROM jobs').fetchone()[0] == 1 + + +def test_rb1_inner_duplicate_removes_staging(tmp_path, monkeypatch): + svc, _clock, owner, account = service(tmp_path) + body = image_body(account) + job_id = body['request_id'] + request_hash = cs.digest(cs.encoded(body).encode()) + real = cs.private_write + once = [] + + def wrapped(path, data): + if '.staging-' in str(path) and not once: + once.append(1) + with svc.db() as db: + db.execute( + 'INSERT INTO jobs VALUES (?,?,?,?,?)', + (job_id, owner, account, request_hash, cs.encoded({'id': job_id, 'phase': 'queued', 'account_id': account, 'gpu': 'L4'})), + ) + return real(path, data) + + monkeypatch.setattr(cs, 'private_write', wrapped) + result = svc._submit(owner, body) + assert result['id'] == job_id + assert staging(svc.root) == [] + assert not (svc.root / 'jobs' / job_id).exists() + with svc.db() as db: + assert db.execute('SELECT count(*) FROM jobs').fetchone()[0] == 1 + + +@pytest.mark.parametrize('kind', ['staging', 'duplicate', 'claim', 'active', 'session']) +def test_rb1_failed_paths_leave_no_directory(tmp_path, monkeypatch, kind): + svc, _clock, owner, account = service(tmp_path) + body = image_body(account) + job_id = body['request_id'] + real = cs.private_write + once = [] + + def wrapped(path, data): + if '.staging-' in str(path) and not once: + once.append(1) + if kind == 'staging': + raise RuntimeError('staging-boom') + with svc.db() as db: + if kind == 'duplicate': + db.execute( + 'INSERT INTO jobs VALUES (?,?,?,?,?)', + (job_id, owner, account, 'different-hash', cs.encoded({'id': job_id, 'phase': 'queued', 'account_id': account, 'gpu': 'L4'})), + ) + elif kind == 'claim': + db.execute("UPDATE request_claims SET state='terminal' WHERE id=?", (job_id,)) + elif kind == 'active': + other = '44444444-4444-4444-8444-444444444444' + db.execute( + 'INSERT INTO jobs VALUES (?,?,?,?,?)', + (other, owner, account, 'h', cs.encoded({'id': other, 'phase': 'queued', 'account_id': account, 'subject_key': SUBJECT, 'gpu': 'L4'})), + ) + else: + state = svc.sessions.new_state(owner, account, SUBJECT, {'idle_minutes': 20, 'hard_hours': 6, 'max_units': 120}) + state.update(phase='ready', deadline_epoch=CLOCK + 1000) + db.execute('INSERT INTO work_sessions VALUES (?,?,?)', (state['id'], owner, cs.encoded(state))) + return real(path, data) + + monkeypatch.setattr(cs, 'private_write', wrapped) + with pytest.raises((RuntimeError, ColabError)): + svc._submit(owner, body) + assert staging(svc.root) == [] + assert not (svc.root / 'jobs' / job_id).exists() + if kind == 'duplicate': + assert job_row(svc, job_id) is not None + else: + assert job_row(svc, job_id) is None + + +def test_rb1_insert_failure_renames_directory(tmp_path): + svc, _clock, owner, account = service(tmp_path) + body = image_body(account) + job_id = body['request_id'] + with svc.db() as db: + db.execute("CREATE TRIGGER rb1_fail BEFORE INSERT ON jobs BEGIN SELECT RAISE(ABORT,'rb1'); END") + with pytest.raises(sqlite3.IntegrityError): + svc._submit(owner, body) + assert staging(svc.root) == [] + assert not (svc.root / 'jobs' / job_id).exists() + assert job_row(svc, job_id) is None + stale = [svc.root / 'jobs' / name for name in names(svc.root) if name.startswith('.stale-' + job_id)] + assert len(stale) == 1 and (stale[0] / 'manifest.json').is_file() + + +def test_rb1_leftover_directory_is_renamed(tmp_path): + svc, _clock, owner, account = service(tmp_path) + body = image_body(account) + job_id = body['request_id'] + leftover = svc.root / 'jobs' / job_id + leftover.mkdir(parents=True) + (leftover / 'marker.txt').write_text('keep') + result = svc._submit(owner, body) + assert result['id'] == job_id + assert (svc.root / 'jobs' / job_id / 'manifest.json').is_file() + assert not (svc.root / 'jobs' / job_id / 'marker.txt').exists() + stale = list((svc.root / 'jobs').glob('.stale-' + job_id + '-*')) + assert len(stale) == 1 and (stale[0] / 'marker.txt').read_text() == 'keep' + assert staging(svc.root) == [] + assert job_row(svc, job_id)['phase'] == 'queued' + + +def test_rb1_concurrent_same_request(tmp_path): + svc, _clock, owner, account = service(tmp_path) + body = image_body(account) + job_id = body['request_id'] + barrier = threading.Barrier(2) + results, errors = [], [] + + def run(): + try: + barrier.wait(5) + results.append(svc._submit(owner, dict(body))) + except Exception as error: + errors.append(error) + + threads = [threading.Thread(target=run), threading.Thread(target=run)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(30) + assert errors == [] + assert sorted(item['id'] for item in results) == [job_id, job_id] + assert staging(svc.root) == [] + assert (svc.root / 'jobs' / job_id).is_dir() + assert not list((svc.root / 'jobs').glob('.stale-*')) + with svc.db() as db: + assert db.execute('SELECT count(*) FROM jobs').fetchone()[0] == 1 + + +def _parity(tmp_path): + svc, _clock, _owner, _account = service(tmp_path) + journal = Journal(tmp_path / 'parity' / 'journal.sqlite3', colab_state_path=svc.root / 'state.sqlite3') + return svc, journal + + +def _watch_parity(path, stop, waits): + while not stop.is_set(): + started = time.monotonic() + connection = sqlite3.connect(path, timeout=8) + try: + connection.execute('BEGIN IMMEDIATE') + waited = time.monotonic() - started + connection.rollback() + if waited >= 0.05: + waits.append(waited) + except sqlite3.OperationalError: + waits.append(time.monotonic() - started) + finally: + connection.close() + + +def _record_sleep(bucket): + def fake(seconds): + bucket.append(seconds) + threading.Event().wait(0.05) + return fake + + +def _hold_colab(path, started, release, seconds): + connection = sqlite3.connect(path, timeout=30) + connection.execute('BEGIN EXCLUSIVE') + started.set() + release.wait(seconds) + connection.rollback() + connection.close() + + +def test_rb2_one_second_hold_succeeds_and_bounds_parity_lock(tmp_path, monkeypatch): + _svc, journal = _parity(tmp_path) + slept = [] + monkeypatch.setattr(journal_mod.time, 'sleep', lambda seconds: slept.append(seconds)) + started, release, stop = threading.Event(), threading.Event(), threading.Event() + waits = [] + holder = threading.Thread(target=_hold_colab, args=(journal.colab_state_path, started, release, 1.0)) + watcher = threading.Thread(target=_watch_parity, args=(journal.path, stop, waits)) + holder.start() + assert started.wait(2) + watcher.start() + begin = time.monotonic() + try: + job, created = journal.reserve('owner', '55555555-5555-4555-8555-555555555555', 'colab', 'acct', 'voice.demo', 'ident', {'unit': 'CU', 'amount': 1}) + finally: + release.set() + stop.set() + holder.join(3) + watcher.join(3) + elapsed = time.monotonic() - begin + assert created and job['state'] == 'reserved' and slept == [] + assert 0.7 <= elapsed <= 2.5 + assert waits and max(waits) <= 2.5 + + +def test_rb2_hold_past_one_read_retries(tmp_path, monkeypatch): + _svc, journal = _parity(tmp_path) + slept = [] + monkeypatch.setattr(journal_mod.time, 'sleep', _record_sleep(slept)) + started, release, stop = threading.Event(), threading.Event(), threading.Event() + waits = [] + holder = threading.Thread(target=_hold_colab, args=(journal.colab_state_path, started, release, 3.2)) + watcher = threading.Thread(target=_watch_parity, args=(journal.path, stop, waits)) + holder.start() + assert started.wait(2) + watcher.start() + try: + job, created = journal.reserve('owner', '66666666-6666-4666-8666-666666666666', 'colab', 'acct', 'voice.demo', 'ident', {'unit': 'CU', 'amount': 1}) + finally: + release.set() + stop.set() + holder.join(5) + watcher.join(4) + assert created and job['state'] == 'reserved' + assert slept == [0.5] + assert waits and max(waits) <= 4.5 + + +def test_rb2_ten_second_hold_is_busy(tmp_path, monkeypatch): + from scripts.colab_remote.native_contracts import ParityError + _svc, journal = _parity(tmp_path) + slept = [] + monkeypatch.setattr(journal_mod.time, 'sleep', _record_sleep(slept)) + started, release, stop = threading.Event(), threading.Event(), threading.Event() + waits = [] + holder = threading.Thread(target=_hold_colab, args=(journal.colab_state_path, started, release, 10)) + watcher = threading.Thread(target=_watch_parity, args=(journal.path, stop, waits)) + holder.start() + assert started.wait(2) + watcher.start() + rid = '77777777-7777-4777-8777-777777777777' + begin = time.monotonic() + try: + with pytest.raises(ParityError) as caught: + journal.reserve('owner', rid, 'colab', 'acct', 'voice.demo', 'ident', {'unit': 'CU', 'amount': 1}) + elapsed = time.monotonic() - begin + reader = sqlite3.connect(journal.colab_state_path.resolve().as_uri() + '?mode=ro', uri=True, timeout=0.3) + try: + with pytest.raises(sqlite3.OperationalError): + reader.execute('SELECT 1 FROM jobs') + finally: + reader.close() + finally: + release.set() + stop.set() + holder.join(3) + watcher.join(4) + assert caught.value.code == 'colab_state_busy' + assert str(caught.value) == 'Colab 狀態正在更新,請稍後再試一次' + assert slept == [0.5, 0.5] + assert 5.0 <= elapsed <= 8.5 + assert journal.get('owner', rid) is None + assert waits and max(waits) <= 4.5 + + +def test_rb2_without_contention_matches_base_and_one_attempt(tmp_path, monkeypatch): + slept = [] + monkeypatch.setattr(journal_mod.time, 'sleep', lambda seconds: slept.append(seconds)) + _svc, journal = _parity(tmp_path) + monkeypatch.setattr(journal_mod.time, 'time', lambda: 1700000000.0) + job, created = journal.reserve('owner', '88888888-8888-4888-8888-888888888888', 'colab', 'acct', 'voice.demo', 'ident', {'unit': 'CU', 'amount': 1}) + assert created and slept == [] + assert json.dumps(job, sort_keys=True, separators=(',', ':')) == R40V5_RESERVE_JOB + + +def test_rb2_states_outside_reserve_keep_defaults(tmp_path): + svc, journal = _parity(tmp_path) + assert states.__defaults__ is None or True + import inspect + assert inspect.signature(states).parameters['timeout'].default == 30 + assert inspect.signature(journal._session_capable).parameters['timeout'].default == 5.0 + started, release = threading.Event(), threading.Event() + holder = threading.Thread(target=_hold_colab, args=(svc.root / 'state.sqlite3', started, release, 0.4)) + holder.start() + assert started.wait(2) + begin = time.monotonic() + try: + assert states(svc.root / 'state.sqlite3', 'owner') == {} + assert journal._session_capable() is True + finally: + release.set() + holder.join(2) + assert time.monotonic() - begin < 5 + + +def _session_row(svc, owner, account, **changes): + state = svc.sessions.new_state(owner, account, SUBJECT, {'idle_minutes': 20, 'hard_hours': 6, 'max_units': 120}) + fields = {'phase': 'ready', 'last_balance': 100, 'deadline_epoch': CLOCK + 10000, 'last_tick': CLOCK} + fields.update(changes) + state.update(fields) + with svc.db() as db: + db.execute('INSERT INTO work_sessions VALUES (?,?,?)', (state['id'], owner, cs.encoded(state))) + return state + + +def test_rb3_rebind_during_observe_does_not_meter(tmp_path, caplog): + svc, _clock, owner, account = service(tmp_path) + state = _session_row(svc, owner, account) + old = {'owner': owner, 'account_id': account, 'subject_key': SUBJECT, 'identity_at': 900, 'balance_at': 900, 'balance': 100} + svc.sessions.save(state['id'], admission_verification=old) + second = '99999999-9999-4999-8999-999999999999' + + def observed(current, op, **kwargs): + svc.sessions.save(state['id'], account_id=second) + return {'authenticated': True, 'subject_key': SUBJECT, 'balance_compute_units': 40} + + svc._call = observed + with caplog.at_level(logging.WARNING, logger='colab_sessions'): + returned = svc.sessions.observe(svc.sessions.get(state['id'])) + current = svc.sessions.get(state['id']) + assert returned['account_id'] == second == current['account_id'] + assert current['admission_verification'] == old + assert current['last_balance'] == 100 and current['units_observed'] == 0 + assert 'source' not in current['admission_verification'] + assert 'colab_observe_binding_changed session=%s' % state['id'] in caplog.text + + +class Client: + def start_channels(self, *args, **kwargs): + return None + + def execute(self, *args, **kwargs): + return None + + def _on_open(self, *args, **kwargs): + return None + + def _on_close(self, *args, **kwargs): + return None + + +def test_rb4_fired_exception_becomes_timeout(): + budget = Budget(30) + with pytest.raises(TimeoutError) as caught: + with scoped(budget, Client): + try: + import signal + signal.getsignal(signal.SIGALRM)(signal.SIGALRM, None) + except TimeoutError: + raise ValueError('replaced') + assert isinstance(caught.value.__cause__, ValueError) + + +def test_rb4_exception_before_alarm_is_unchanged(): + budget = Budget(30) + with pytest.raises(ValueError, match='plain'): + with scoped(budget, Client): + raise ValueError('plain') + + +def test_rb4_timeout_itself_stays_timeout(): + import signal + budget = Budget(30) + with pytest.raises(TimeoutError) as caught: + with scoped(budget, Client): + signal.getsignal(signal.SIGALRM)(signal.SIGALRM, None) + assert caught.value.__cause__ is None + + +def _busy(message): + return sqlite3.OperationalError(message) + + +def test_rb5_one_busy_tick_stays(tmp_path, monkeypatch): + svc, _clock, owner, account = service(tmp_path) + state = _session_row(svc, owner, account) + monkeypatch.setattr(svc.sessions, 'tick', lambda current: (_ for _ in ()).throw(_busy('database is locked'))) + svc.sessions.tick_all() + current = svc.sessions.get(state['id']) + assert current['phase'] == 'ready' + assert current['fault']['code'] == 'store_busy' + assert current['last_tick'] == state['last_tick'] + assert current['fault_streak'] == 1 + assert state['id'] in svc.sessions._recovery_anchors + + +@pytest.mark.parametrize('message', ['database is locked', 'database is busy']) +def test_rb5_second_busy_closes_on_streak(tmp_path, message): + svc, _clock, owner, account = service(tmp_path) + state = _session_row(svc, owner, account) + svc.sessions.operation(state, 'observe') + svc.sessions.record_fault(state, _busy(message)) + assert svc.sessions.get(state['id'])['phase'] == 'ready' + svc.sessions.operation(state, 'observe') + svc.sessions.record_fault(svc.sessions.get(state['id']), _busy(message)) + current = svc.sessions.get(state['id']) + assert current['phase'] == 'closing' and current['reason'] == 'watchdog_state_lost' + assert current['last_tick'] == state['last_tick'] + + +def test_rb5_busy_past_span_heartbeat_and_deadline(tmp_path): + svc, clock, owner, account = service(tmp_path) + span = _session_row(svc, owner, account, fault_since=CLOCK - 90, fault_streak=0) + svc.sessions.record_fault(span, _busy('database is locked')) + assert svc.sessions.get(span['id'])['phase'] == 'closing' + + heartbeat = _session_row(svc, owner, account, last_tick=CLOCK - 300) + svc.sessions.record_fault(heartbeat, _busy('database is locked')) + assert svc.sessions.get(heartbeat['id'])['phase'] == 'closing' + assert svc.sessions.get(heartbeat['id'])['reason'] == 'watchdog_state_lost' + + deadline = _session_row(svc, owner, account, deadline_epoch=CLOCK - 1) + svc.sessions.record_fault(deadline, _busy('database is busy')) + current = svc.sessions.get(deadline['id']) + assert current['phase'] == 'closing' and current['reason'] == 'watchdog_state_lost' + assert current['last_tick'] == deadline['last_tick'] + + +def test_rb5_non_busy_operational_error_closes(tmp_path): + svc, _clock, owner, account = service(tmp_path) + state = _session_row(svc, owner, account) + svc.sessions.operation(state, 'heartbeat') + svc.sessions.record_fault(state, sqlite3.OperationalError('unable to open database file')) + current = svc.sessions.get(state['id']) + assert current['phase'] == 'closing' and current['reason'] == 'watchdog_state_lost' + assert current['fault']['code'] == 'OperationalError' + assert current['last_tick'] == state['last_tick'] + + +def _job(root, name, text): + directory = root / 'owner' / 'comfy_cloud' / 'jobs' / name + directory.mkdir(parents=True) + (directory / 'job.json').write_text(text) + return directory + + +def test_rb6_bad_jobs_do_not_stop_the_poll(tmp_path, caplog): + hosted_compute._HOSTED_TICK_LOGGED.clear() + calls = [] + svc = hosted_compute.HostedComputeService(tmp_path / 'hosted', transport=object()) + _job(svc.root, 'badjson', '{') + _job(svc.root, 'badkey', json.dumps({'state': 'queued'})) + _job(svc.root, 'good', json.dumps({'state': 'queued'})) + + def poll(folder, path, job): + calls.append(path.name) + if path.name == 'badkey': + raise KeyError('missing') + + svc._poll = poll + with caplog.at_level(logging.WARNING, logger='hosted_compute'): + svc.tick() + svc.tick() + assert calls.count('good') == 2 and calls.count('badkey') == 2 + assert 'badjson' not in calls + assert svc.poll_failures == 2 + assert caplog.text.count('hosted_job_tick_failed job=badkey exception=KeyError') == 1 + + +def test_rb6_tick_exception_keeps_the_thread(tmp_path, caplog, monkeypatch): + hosted_compute._HOSTED_TICK_LOGGED.clear() + svc = hosted_compute.HostedComputeService(tmp_path / 'hosted', transport=object()) + calls = [] + + def tick(): + calls.append(1) + if len(calls) == 1: + raise RuntimeError('iter') + + monkeypatch.setattr(svc, 'tick', tick) + with caplog.at_level(logging.WARNING, logger='hosted_compute'): + svc.start(interval=0.05) + deadline = time.monotonic() + 3 + while len(calls) < 2 and time.monotonic() < deadline: + svc._stop.wait(0.02) + alive = svc._thread.is_alive() + svc.stop() + svc._thread.join(2) + assert alive and len(calls) >= 2 and svc.poll_failures >= 1 + assert 'hosted_poller_iteration_failed exception=RuntimeError' in caplog.text + + +def test_rb6_safe_log_swallows_logger_errors(monkeypatch): + def boom(*args, **kwargs): + raise RuntimeError('log') + + monkeypatch.setattr(hosted_compute.logger, 'warning', boom) + hosted_compute._safe_log('hosted_poller_iteration_failed exception=%s', 'RuntimeError') + + +def _vox(): + import orchestrator.tasks as tasks + return tasks + + +def test_rb7_unusable_manifest(tmp_path, monkeypatch): + tasks = _vox() + out = tmp_path / 'out' + out.mkdir() + monkeypatch.setattr(tasks, '_trusted_existing_path', lambda *args, **kwargs: Path('/bin/true')) + monkeypatch.setattr(tasks, '_safe_output_dir', lambda *args, **kwargs: out) + monkeypatch.setattr(tasks, 'gpu_queue_cmd', lambda inner, payload: ['true']) + monkeypatch.setattr(tasks, '_cancelled', lambda path: False) + payload = {'segments': [{'index': 1, 'text': 'hi'}], 'output_dir': str(out), 'manifest_name': 'manifest.json'} + + def missing(*args, **kwargs): + return None + + monkeypatch.setattr(tasks.subprocess, 'check_call', missing) + with pytest.raises(RuntimeError, match='VoxCPM batch produced no usable manifest'): + tasks.run_castle_voxcpm_tts_batch(payload, tmp_path / 'work-missing', tmp_path / 'cancel') + + def invalid(*args, **kwargs): + (out / 'manifest.json').write_text('{', encoding='utf-8') + + monkeypatch.setattr(tasks.subprocess, 'check_call', invalid) + with pytest.raises(RuntimeError, match='VoxCPM batch produced no usable manifest'): + tasks.run_castle_voxcpm_tts_batch(payload, tmp_path / 'work-invalid', tmp_path / 'cancel') + + def empty(*args, **kwargs): + (out / 'manifest.json').write_text('{"segments": []}', encoding='utf-8') + + monkeypatch.setattr(tasks.subprocess, 'check_call', empty) + with pytest.raises(RuntimeError, match='VoxCPM batch produced no usable manifest'): + tasks.run_castle_voxcpm_tts_batch(payload, tmp_path / 'work-empty', tmp_path / 'cancel') + + +def test_rb7_one_segment_matches_previous_artifacts(tmp_path, monkeypatch): + tasks = _vox() + out = tmp_path / 'out' + out.mkdir() + monkeypatch.setattr(tasks, '_trusted_existing_path', lambda *args, **kwargs: Path('/bin/true')) + monkeypatch.setattr(tasks, '_safe_output_dir', lambda *args, **kwargs: out) + monkeypatch.setattr(tasks, 'gpu_queue_cmd', lambda inner, payload: ['true']) + monkeypatch.setattr(tasks, '_cancelled', lambda path: False) + + def write(*args, **kwargs): + (out / 'manifest.json').write_text( + json.dumps({'segments': [{'index': 1, 'file': 'seg_01.wav', 'passed': True}]}), + encoding='utf-8', + ) + + monkeypatch.setattr(tasks.subprocess, 'check_call', write) + artifacts = tasks.run_castle_voxcpm_tts_batch( + {'segments': [{'index': 1, 'text': 'hi'}], 'output_dir': str(out)}, + tmp_path / 'work', + tmp_path / 'cancel', + ) + assert artifacts == [ + { + 'path': str(out / 'seg_01.wav'), + 'name': 'seg_01.wav', + 'artifact_type': 'audio', + 'output_name': 'seg_01', + 'metadata': {'workflow': 'castle.voxcpm_tts_batch', 'file': 'seg_01.wav', 'index': 1, 'passed': True}, + }, + { + 'path': str(out / 'manifest.json'), + 'name': 'manifest.json', + 'artifact_type': 'json', + 'output_name': 'manifest', + 'metadata': { + 'workflow': 'castle.voxcpm_tts_batch', + 'manifest': 'manifest.json', + 'count': 1, + 'files': ['seg_01.wav'], + }, + }, + ] + + +def test_point_monitor_pause_ignores_a_patched_shared_sleep(monkeypatch): + """The monitor thread outlives the test that started it; its pause must not call time.sleep.""" + import types + import compute_parity.lifecycle as lifecycle + calls, ticked = [], threading.Event() + monkeypatch.setattr(lifecycle.time, 'sleep', _record_sleep(calls)) + monkeypatch.setattr(lifecycle, 'tick', lambda console, journal: ticked.set()) + console = types.SimpleNamespace(test=lambda *args, **kwargs: None, owner='monitor-pause-owner') + lifecycle.start_monitor(console, types.SimpleNamespace(path='monitor-pause-journal')) + assert ticked.wait(2) + threading.Event().wait(0.3) + assert calls == [] diff --git a/scripts/test_compute_r40v6_unsent_faults.py b/scripts/test_compute_r40v6_unsent_faults.py new file mode 100644 index 0000000..a09ddf0 --- /dev/null +++ b/scripts/test_compute_r40v6_unsent_faults.py @@ -0,0 +1,363 @@ +"""Unsent transport faults keep a wider, still bounded recovery window.""" +import contextlib +import sqlite3 +import uuid + +import pytest +from colab_service import BridgeError +from colab_sessions import ( + FAULT_SPAN, HEARTBEAT, UNSENT_FAULT_LIMIT, UNSENT_FAULT_SPAN, UNSENT_STAGES, WorkSessions, +) +from review_r38_fixture import rig, session + + +def _fault(r, st, error, stage='heartbeat', reconciling_launch=False): + r.s.sessions.operation(st, stage) + r.s.sessions.record_fault(st, error, reconciling_launch=reconciling_launch) + return r.s.sessions.get(st['id']) + + +def _unsent(): + return BridgeError('transport_not_ready') + + +def test_six_unsent_heartbeat_faults(rig): + r = rig + st = session(r) + base = r.t[0] + phase = st['phase'] + for index, offset in enumerate((0, 20, 40, 60, 80), start=1): + r.t[0] = base + offset + cur = _fault(r, st, _unsent()) + assert cur['phase'] == phase + assert cur['fault_streak'] == index + assert cur['fault_streak_unsent'] is True + assert cur['fault']['code'] == 'transport_not_ready' + r.t[0] = base + 100 + cur = _fault(r, st, _unsent()) + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + assert cur['terminal_fault']['count'] == 6 + + +def test_wall_span_closes_past_180(rig): + r = rig + st = session(r) + base = r.t[0] + phase = st['phase'] + for offset in (0, 179): + r.t[0] = base + offset + cur = _fault(r, st, _unsent()) + assert cur['phase'] == phase and cur['fault_streak_unsent'] is True + r.t[0] = base + 181 + cur = _fault(r, st, _unsent()) + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + + +def test_monotonic_span_times_out_while_wall_is_frozen(rig): + r = rig + mono = [500.0] + r.s.sessions._monotonic = lambda: mono[0] + st = session(r) + _fault(r, st, _unsent()) + mono[0] += 181 + remaining, code = r.s.sessions.budget_status(r.s.sessions.get(st['id'])) + assert code == 'timeout' and remaining <= 0 + with pytest.raises(BridgeError): + r.s.sessions.recovery_remaining(r.s.sessions.get(st['id'])) + cur = r.s.sessions.get(st['id']) + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + + +def test_restart_does_not_open_a_new_unsent_window(rig): + r = rig + mono = [1000.0] + st = session(r, fault_streak=2, fault_streak_unsent=True, fault_since=r.t[0] - 150, + fault={'stage': 'heartbeat', 'code': 'transport_not_ready', 'at': r.t[0] - 150, + 'count': 2, 'ambiguous': False}) + r.s.sessions = WorkSessions(r.s) + r.s.sessions._monotonic = lambda: mono[0] + remaining, code = r.s.sessions.budget_status(r.s.sessions.get(st['id'])) + assert code is None and 0 < remaining <= 30 + anchor = r.s.sessions._recovery_anchors[st['id']] + assert anchor[1] - mono[0] <= 30 + mono[0] += 31 + remaining, code = r.s.sessions.budget_status(r.s.sessions.get(st['id'])) + assert code == 'timeout' and remaining <= 0 + + +def test_heartbeat_still_bounds_an_unsent_streak(rig): + r = rig + st = session(r, last_tick=r.t[0] - 290) + phase = st['phase'] + cur = _fault(r, st, _unsent()) + assert cur['phase'] == phase and cur['fault_streak'] == 1 and cur['fault_streak_unsent'] is True + r.t[0] += 11 + cur = _fault(r, st, _unsent()) + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + + +def test_mixed_unsent_then_ambiguous_execution_closes(rig): + r = rig + st = session(r) + cur = _fault(r, st, _unsent()) + assert cur['phase'] == st['phase'] and cur['fault_streak_unsent'] is True + cur = _fault(r, st, BridgeError('execution_uncertain', True)) + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + + +def test_mixed_execution_then_unsent_closes(rig): + r = rig + st = session(r) + cur = _fault(r, st, BridgeError('execution_uncertain', True)) + assert cur['phase'] == st['phase'] and cur['fault_streak_unsent'] is False + cur = _fault(r, st, _unsent()) + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + + +def test_mixed_unsent_then_busy_store_closes(rig): + r = rig + st = session(r) + cur = _fault(r, st, _unsent()) + assert cur['phase'] == st['phase'] + cur = _fault(r, st, sqlite3.OperationalError('database is locked')) + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + assert cur['fault']['code'] == 'store_busy' + + +def test_unsent_upload_uses_the_short_window(rig): + r = rig + st = session(r) + cur = _fault(r, st, _unsent(), stage='upload') + assert cur['phase'] == st['phase'] and cur['fault_streak'] == 1 and cur['fault_streak_unsent'] is False + cur = _fault(r, st, _unsent(), stage='upload') + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + + +def test_unsent_while_reconciling_launch_uses_the_short_window(rig): + r = rig + st = session(r) + cur = _fault(r, st, _unsent(), reconciling_launch=True) + assert cur['phase'] == st['phase'] and cur['fault_streak'] == 1 and cur['fault_streak_unsent'] is False + cur = _fault(r, st, _unsent(), reconciling_launch=True) + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + + +def test_unsent_attach_closes_immediately(rig): + r = rig + st = session(r) + cur = _fault(r, st, _unsent(), stage='attach') + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + assert cur['fault_streak'] == 1 + + +def test_ambiguous_transport_not_ready_uses_the_short_window(rig): + r = rig + st = session(r) + error = BridgeError('transport_not_ready', True) + cur = _fault(r, st, error) + assert cur['phase'] == st['phase'] and cur['fault_streak'] == 1 and cur['fault_streak_unsent'] is False + cur = _fault(r, st, error) + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + + +def test_successful_cycle_resets_unsent_streak(rig): + r = rig + st = session(r) + sid = st['id'] + for _ in range(3): + r.t[0] += 10 + cur = _fault(r, st, _unsent()) + assert cur['fault_streak'] == 3 and cur['fault_streak_unsent'] is True + r.s.sessions.save(sid, cycle_session_ok=True, cycle_faulted=False, cycle_job=None) + r.t[0] += 10 + r.s.sessions.finish_cycle(sid) + cur = r.s.sessions.get(sid) + assert cur['fault_streak'] == 0 and cur['fault_streak_unsent'] is False + cur = _fault(r, st, BridgeError('execution_uncertain', True)) + assert cur['phase'] == st['phase'] and cur['fault_streak'] == 1 + cur = _fault(r, st, BridgeError('execution_uncertain', True)) + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + + +def test_tick_all_four_unsent_heartbeats_then_a_complete_cycle(rig): + from test_review_r38_faults import probe_kind + r = rig + st = session(r) + seen = [] + + def hook(op, kw): + if probe_kind(op, kw) == 'heartbeat': + seen.append(1) + if len(seen) <= 4: + raise BridgeError('transport_not_ready') + return None + + r.b.hook = hook + for _ in range(4): + r.t[0] += 5 + r.s.sessions.tick_all() + cur = r.s.sessions.get(st['id']) + assert cur['phase'] == 'ready' + assert cur['fault_streak'] == 4 and cur['fault_streak_unsent'] is True + previous = cur['last_tick'] + r.t[0] += 5 + r.s.sessions.tick_all() + cur = r.s.sessions.get(st['id']) + assert cur['phase'] == 'ready' and cur['fault_streak'] == 0 and cur['fault_streak_unsent'] is False + assert cur['last_tick'] == r.t[0] and cur['last_tick'] != previous + + +def test_clock_inconsistent_closes_at_that_fault(rig): + r = rig + st = session(r) + r.t[0] -= 5 + cur = _fault(r, st, _unsent()) + assert cur['fault']['code'] == 'clock_inconsistent' + assert cur['phase'] == 'closing' and cur['reason'] == 'watchdog_state_lost' + assert cur.get('fault_streak_unsent') is not True + + +def test_unsent_constants_hold(): + assert UNSENT_FAULT_LIMIT == 6 and UNSENT_FAULT_SPAN == 180 + assert UNSENT_STAGES == frozenset({'heartbeat', 'observe', 'bootstrap_probe', 'job_probe'}) + assert FAULT_SPAN <= UNSENT_FAULT_SPAN < HEARTBEAT + + +def _lookup_account(tmp_path): + from scripts import colab_bridge as cb + account = cb.private_directory(str(tmp_path / 'account')) + cb.atomic_json(account / 'identity.json', { + 'issuer': cb.GOOGLE_ISSUER, 'subject': 'subject-1', 'verified_at': 1}) + runtime_id = str(uuid.uuid4()) + runtime_dir = cb.private_directory(str(account / 'runtimes')) + cb.atomic_json(runtime_dir / (runtime_id + '.json'), { + 'runtime_id': runtime_id, 'accelerator': 'A100', 'endpoint': 'ep-1', 'state': 'allocated'}) + return cb, account, runtime_id + + +def _sdk(cb, assignments, runtime): + sdk = cb.GoogleSDK.__new__(cb.GoogleSDK) + + class Client: + def list_assignments(self): + return assignments() + + sdk.credentials = lambda path: object() + sdk.client = lambda credentials: Client() + sdk.Runtime = runtime + sdk.execution_transport = contextlib.nullcontext + return sdk + + +class _Proxy: + url = 'https://abc.googleusercontent.com/runtime' + token = 'fixture-token' + + +class _Match: + endpoint = 'ep-1' + runtime_proxy_info = _Proxy() + + +class _Other: + endpoint = 'other-endpoint' + + +@pytest.mark.parametrize('kind', [ConnectionError, OSError]) +def test_lookup_exception_is_unsent_and_does_not_construct_runtime(tmp_path, kind): + cb, account, runtime_id = _lookup_account(tmp_path) + constructed = [] + + class Runtime: + def __init__(self, *args, **kwargs): + constructed.append(1) + + sdk = _sdk(cb, lambda: (_ for _ in ()).throw(kind('lookup failed')), Runtime) + result = cb.handle({ + 'op': 'remote_exec', 'account_dir': str(account), 'runtime_id': runtime_id, + 'code': 'pass', 'timeout_seconds': 3, + }, sdk_factory=lambda: sdk) + assert result['ok'] is False + assert result['error']['code'] == 'transport_not_ready' + assert result['error']['ambiguous'] is False + assert constructed == [] + + +def test_lookup_without_endpoint_stays_runtime_missing(tmp_path): + cb, account, runtime_id = _lookup_account(tmp_path) + constructed = [] + + class Runtime: + def __init__(self, *args, **kwargs): + constructed.append(1) + + sdk = _sdk(cb, lambda: [_Other()], Runtime) + result = cb.handle({ + 'op': 'remote_exec', 'account_dir': str(account), 'runtime_id': runtime_id, + 'code': 'pass', 'timeout_seconds': 3, + }, sdk_factory=lambda: sdk) + assert result['ok'] is False + assert result['error']['code'] == 'runtime_missing' + assert result['error']['ambiguous'] is False + assert constructed == [] + + +def test_failure_after_send_stays_execution_uncertain(tmp_path, monkeypatch): + from scripts import colab_rpc_transport as rpc + from test_compute_r40b import Client + cb, account, runtime_id = _lookup_account(tmp_path) + real_scoped = rpc.scoped + monkeypatch.setattr(rpc, 'scoped', lambda budget: real_scoped(budget, Client)) + + class Runtime: + def __init__(self, *args, **kwargs): + return None + + def execute_code(self, *args, **kwargs): + client = Client(True) + client.start_channels() + client.execute() + raise RuntimeError('Connection was lost.') + + def stop(self, **kwargs): + return None + + sdk = _sdk(cb, lambda: [_Match()], Runtime) + result = cb.handle({ + 'op': 'remote_exec', 'account_dir': str(account), 'runtime_id': runtime_id, + 'code': 'pass', 'timeout_seconds': 3, + }, sdk_factory=lambda: sdk) + assert result['ok'] is False + assert result['error']['code'] == 'execution_uncertain' + assert result['error']['ambiguous'] is True + + +def test_lookup_failure_counts_as_unsent_heartbeat(rig, tmp_path): + cb, account, runtime_id = _lookup_account(tmp_path) + + class Runtime: + def __init__(self, *args, **kwargs): + raise AssertionError('Runtime constructed') + + sdk = _sdk(cb, lambda: (_ for _ in ()).throw(ConnectionError('lookup failed')), Runtime) + result = cb.handle({ + 'op': 'remote_exec', 'account_dir': str(account), 'runtime_id': runtime_id, + 'code': 'pass', 'timeout_seconds': 3, + }, sdk_factory=lambda: sdk) + error = result['error'] + service_error = BridgeError(str(error['code']), bool(error['ambiguous']), + error.get('diagnostics'), error.get('private_diagnostics')) + r = rig + mono = [100.0] + r.s.sessions._monotonic = lambda: mono[0] + st = session(r) + cur = _fault(r, st, service_error) + assert cur['phase'] == st['phase'] and cur['fault_streak'] == 1 + assert cur['fault']['code'] == 'transport_not_ready' and cur['fault_streak_unsent'] is True + remaining, code = r.s.sessions.budget_status(cur) + assert code is None and 90 < remaining <= 180 + anchor = r.s.sessions._recovery_anchors[st['id']] + assert anchor[1] - mono[0] == pytest.approx(UNSENT_FAULT_SPAN) + cur = _fault(r, st, service_error) + cur = _fault(r, st, service_error) + assert cur['phase'] == st['phase'] and cur['fault_streak'] == 3 and cur['fault_streak_unsent'] is True diff --git a/scripts/test_compute_r40v6_voice_toolchain.py b/scripts/test_compute_r40v6_voice_toolchain.py new file mode 100644 index 0000000..2949673 --- /dev/null +++ b/scripts/test_compute_r40v6_voice_toolchain.py @@ -0,0 +1,141 @@ +"""Voice build toolchain: gcc overrides the interpreter sysconfig, pins, and PATH.""" +import copy +import hashlib +import json +import os +import shutil +from pathlib import Path + +import pytest + +from scripts import colab_session_voice as voice +from scripts.colab_session_diagnostics import failure_diagnostics + +FIVE = 'cython==3.2.5\nnumpy==1.26.4\npackaging==26.3\nsetuptools==70.2.0\nwheel==0.48.0\n' +VOICE_ID = 'ee91ed788074a2a51bfe0c9ccdbef26979a3791c0b614a27f7739bb4be80d4c0' +COMPILER = {'CC': 'gcc -pthread', 'CXX': 'g++ -pthread', 'AR': 'ar'} +R40V5_REGISTRY_SHA256 = '7f4a9ddec9bcc769edd3f4032d0b511e074034339d4864dffa4c408ead914f0c' +R40V5_VOICE_BUILD_CONSTRAINT = 'setuptools==70.2.0\n' + + +def canonical_sha256(value): + data = json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode('utf-8') + return hashlib.sha256(data).hexdigest() + + +def arm_tools(tmp_path, monkeypatch): + registry = json.loads(voice.REGISTRY.read_text()) + selected = tmp_path / 'selected-python' + selected.write_bytes(b'interpreter') + real_sha = voice.sha + + def sha(path, _selected=selected, _hash=registry['interpreter']['sha256'], _real=real_sha): + if Path(path) == _selected: + return _hash + return _real(path) + + monkeypatch.setattr(voice, 'sha', sha) + monkeypatch.setattr(voice, 'provision_python', lambda *args: str(selected)) + monkeypatch.setattr(voice, 'verify_python', lambda *args: None) + tool_python = tmp_path / 'voice-tools' / 'venv' / 'bin' / 'python' + tool_python.parent.mkdir(parents=True, exist_ok=True) + tool_python.write_bytes(b'tool') + (tmp_path / 'voice-tools' / 'tools-ready').touch() + return registry + + +def install_args(tmp_path, plan, label): + lock = tmp_path / (label + '-constraints.txt') + lock.write_text('\n'.join(plan['runtime_lock'][label]) + '\n') + python = tmp_path / (label + '-venv') / 'bin' / 'python' + return [str(python), '-m', 'pip', 'install', '-r', str(lock)] + + +def pip_installs(calls): + return [(args, kw) for args, kw in calls if 'pip' in args and 'install' in args] + + +def stubs(directory): + directory.mkdir() + for name in ('gcc', 'g++', 'ar'): + path = directory / name + path.write_text('#!/bin/sh\nexit 0\n') + path.chmod(0o755) + return directory + + +def test_compiler_env_overrides_inherited_clang(tmp_path, monkeypatch): + registry = arm_tools(tmp_path, monkeypatch) + monkeypatch.setenv('CC', 'clang') + monkeypatch.setenv('CXX', 'clang++') + monkeypatch.setenv('AR', 'llvm-ar') + inherited = {'CC': 'clang', 'CXX': 'clang++', 'AR': 'llvm-ar'} + _selected, _tool, options = voice.tools(tmp_path, registry, lambda *args, **kw: pytest.fail('no run'), {'env': inherited}) + for key, value in COMPILER.items(): + assert options['env'][key] == value + + + + +def test_registry_pin_matches_runtime_dists_and_base_differs_only_there(): + work = json.loads(voice.REGISTRY.read_text()) + voice_env = work['environments'][VOICE_ID] + assert voice_env['provenance']['label'] == 'local voice venv' + assert voice_env['build_constraint'] == FIVE + pins = dict(line.split('==') for line in FIVE.splitlines()) + for name in ('cython', 'numpy', 'setuptools'): + assert voice_env['dists'][name] == pins[name] + vox = next(row for row in work['environments'].values() if row['provenance']['label'] == 'local voxcpm venv') + assert vox['build_constraint'] == 'setuptools==70.2.0\n' + restored = copy.deepcopy(work) + restored['environments'][VOICE_ID]['build_constraint'] = R40V5_VOICE_BUILD_CONSTRAINT + assert canonical_sha256(restored) == R40V5_REGISTRY_SHA256 + + + + +def test_public_diagnostics_report_build_toolchain(): + error = voice.VoiceEnvironmentMismatch('voice_env_mismatch') + error.substage = 'build_toolchain' + error.command_label = 'pip_voice' + result = failure_diagnostics(error, 'pip_voice') + assert result['substage'] == 'build_toolchain' and result['command_label'] == 'pip_voice' + + +def toolchain_case(tmp_path, monkeypatch, bin_dir): + registry = json.loads(voice.REGISTRY.read_text()) + pins = ['unit-test==1'] + plan = {'feature': 'voxcpm-tts', 'runtime_lock': {'voxcpm': pins}} + (tmp_path / 'voxcpm-constraints.txt').write_text('\n'.join(pins) + '\n') + expected = {'last': [], 'build_constraint': ''} + monkeypatch.setattr(voice, 'entry', lambda *args: (registry, expected, '\n'.join(pins) + '\n')) + monkeypatch.setattr(voice, 'tools', lambda *args: ('test-python', 'test-tool', {'env': {'PATH': str(bin_dir)}})) + monkeypatch.setattr(voice, 'verify_python', lambda *args: None) + calls = [] + args = [str(tmp_path / 'voxcpm-venv/bin/python'), '-m', 'pip', 'install', '-r', str(tmp_path / 'voxcpm-constraints.txt')] + return plan, args, calls + + +@pytest.mark.parametrize('present', [(), ('gcc',), ('gcc', 'g++'), ('g++', 'ar'), ('gcc', 'ar')]) +def test_missing_compiler_tool_blocks_before_pip(tmp_path, monkeypatch, present): + bin_dir = tmp_path / 'bin' + bin_dir.mkdir() + for name in present: + tool = bin_dir / name + tool.write_text('#!/bin/sh\nexit 0\n') + tool.chmod(0o755) + plan, args, calls = toolchain_case(tmp_path, monkeypatch, bin_dir) + with pytest.raises(voice.VoiceEnvironmentMismatch, match='voice_env_mismatch') as error: + voice.run_command(plan, tmp_path, args, lambda args, **kw: calls.append(args), {}) + assert error.value.substage == 'build_toolchain' and error.value.command_label == 'pip_voxcpm' + assert calls == [] + + +def test_complete_compiler_toolchain_reaches_pip(tmp_path, monkeypatch): + plan, args, calls = toolchain_case(tmp_path, monkeypatch, stubs(tmp_path / 'bin')) + voice.run_command(plan, tmp_path, args, lambda args, **kw: calls.append(args), {}) + assert any('pip' in call and 'install' in call for call in calls) + + + + diff --git a/scripts/test_docs_browser.py b/scripts/test_docs_browser.py index 7cea95c..60414af 100644 --- a/scripts/test_docs_browser.py +++ b/scripts/test_docs_browser.py @@ -59,9 +59,12 @@ if(WebComfyTour.demoFor('text2img').output.kind==='unavailable') assert(!document.querySelector('.demo-output img'),'untested text2img has no borrowed image'); else await until(()=>document.querySelector('.demo-output img')?.naturalWidth>0); await feature('AI 指令改圖'); - detail=document.querySelector('.app-feature-guide');assert(detail.textContent.includes('flux1-dev-kontext_fp8_scaled.safetensors'),'actual editing checkpoint');await close(); - assert(location.hash.includes('img2img'), 'feature route matches selected button'); - await until(()=>document.querySelector('[data-demo-id="img2img"]')); + detail=document.querySelector('.app-feature-guide');assert(detail.textContent.includes('qwen_image_2.1_int8_convrot.safetensors')&&!detail.textContent.includes('flux1-dev-kontext_fp8_scaled.safetensors'),'actual editing checkpoint');await close(); + assert(location.hash.includes('qwen21-edit'), 'feature route matches selected button'); + await until(()=>document.querySelector('[data-demo-id="qwen21-edit"]')); + location.hash='#/studio/img2img';await until(()=>document.querySelector('[data-demo-id="img2img"]')); + document.querySelector('.app-guide-button button').click();await until(()=>document.querySelector('.app-feature-guide')); + detail=document.querySelector('.app-feature-guide');assert(detail.textContent.includes('flux1-dev-kontext_fp8_scaled.safetensors')&&detail.textContent.includes('目前一般工具選單隱藏'),'hidden Flux Kontext form stays documented at its direct route');await close(); const editingDemo=WebComfyTour.demoFor('img2img'); if(editingDemo.inputs?.length) { const original=document.querySelector('.demo-input-preview img'); @@ -217,12 +220,20 @@ location.hash='#/studio/text2img';await until(()=>document.querySelector('form[data-demo-id="text2img"]')); const hardwareForm=document.querySelector('form[data-demo-id="text2img"]'); const hardwarePrompt=hardwareForm.querySelector('textarea');hardwarePrompt.value='Preserve this hardware-switch input'; + const bannerLinks=[...document.querySelectorAll('#docsBanner a[target="_blank"]')]; + assert(bannerLinks.length>=2&&bannerLinks.every(a=>a.rel.includes('sponsored')&&a.target==='_blank'),'banner referrals'); + assert(bannerLinks.some(a=>a.href.includes('ref=TEDH2FND'))&&bannerLinks.some(a=>a.href.includes('inviteCode=qqgzxufp')),'banner hrefs'); await chooseHardware('none'); + const cloud=hardwareForm.querySelector('.hardware-cloud-option'); + const cloudLinks=[...cloud.querySelectorAll('a')]; + assert(cloud&&!cloud.hidden&&cloudLinks.length===2&&cloud.textContent.includes('TEDH2FND')&&cloud.textContent.includes('qqgzxufp'),'hardware referrals when blocked'); + assert(cloudLinks.every(a=>a.rel.includes('sponsored')&&a.target==='_blank'),'hardware referral rel'); assert(!WebComfyHardware.canUse('text2img')&&hardwareForm.querySelector('.generate-btn').disabled,'no GPU disables generation'); assert(await WebComfyTour.start(hardwareForm)===false,'direct generation also blocked'); if(innerWidth>=1280)assert(document.getElementById('studio-side-tool-text2img').getAttribute('aria-disabled')==='true','sidebar indicates unavailable workflow'); if(innerWidth>=1280)for(const card of document.querySelectorAll('.side-tool'))for(const child of card.children)assert(!child.getBoundingClientRect().width||child.getBoundingClientRect().right<=card.getBoundingClientRect().right+1,'hardware status stays inside sidebar'); await chooseHardware('vram-24');assert(WebComfyHardware.canUse('text2img')&&!WebComfyHardware.canUse('dance'),'24 GB planning threshold'); + assert(hardwareForm.querySelector('.hardware-cloud-option').hidden,'hardware referrals hidden when allowed'); await chooseHardware('dual-24');assert(!WebComfyHardware.canUse('dance'),'dual GPUs do not pool VRAM'); await chooseHardware('autoip');assert(features.every(entry=>WebComfyHardware.canUse(entry.id)),'AutoIP opens every demonstration'); assert(!hardwareForm.querySelector('.generate-btn').disabled&&hardwarePrompt.value==='Preserve this hardware-switch input','mode switch restores action and preserves inputs'); diff --git a/scripts/test_egress_guard.py b/scripts/test_egress_guard.py new file mode 100644 index 0000000..a18f082 --- /dev/null +++ b/scripts/test_egress_guard.py @@ -0,0 +1,303 @@ +"""Synthetic loopback tests for downloader egress enforcement.""" +import http.server +import io +import re +import select +import socket +import subprocess +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path +from types import SimpleNamespace + +import pytest +import egress_guard +import hosted_compute_http +import material_collector +import server + + +def address(ip, port): + family = socket.AF_INET6 if ':' in ip else socket.AF_INET + return [(family, socket.SOCK_STREAM, 6, '', (ip, port))] + + +def direct_connect(target, timeout): + sock = socket.socket(socket.AF_INET6 if ':' in target[0] else socket.AF_INET, socket.SOCK_STREAM) + sock.settimeout(timeout) + sock.connect(target) + return sock + + +def raw_request(proxy, message): + port = urllib.parse.urlsplit(proxy.url).port + with socket.socket() as client: + client.settimeout(3) + client.connect(('127.0.0.1', port)) + client.sendall(message) + data = b'' + while b'\r\n\r\n' not in data: + part = client.recv(4096) + if not part: + break + data += part + return data + + +@pytest.fixture +def origin(): + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.server.requests.append((self.path, dict(self.headers))) + if self.path == '/redirect': + self.send_response(302) + self.send_header('Location', 'http://' + 'internal.test:' + str(self.server.redirect_port) + '/x') + self.end_headers() + else: + self.send_response(200) + self.end_headers() + self.wfile.write(b'fixture body') + def log_message(self, *args): + pass + srv = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler) + srv.requests = [] + thread = threading.Thread(target=srv.serve_forever, daemon=True) + thread.start() + yield srv + srv.shutdown() + srv.server_close() + thread.join(2) + + +def opener(proxy): + return urllib.request.build_opener(urllib.request.ProxyHandler({'http': proxy.url})) + + +def test_address_allowed_checks_mapped_multicast_and_reserved(): + for ip in ('127.0.0.1', '10.0.0.1', '169.254.169.254', '0.0.0.0', + '224.0.0.1', '::1', '::ffff:127.0.0.1', 'fc00::1', + '64:ff9b::7f00:1', '64:ff9b::a00:1', '64:ff9b::a9fe:a9fe', + '::127.0.0.1', '::10.0.0.1', + '::ffff:0:7f00:1', '::ffff:0:808:808', 'ff02::1'): + assert not egress_guard.address_allowed(ip), ip + assert egress_guard.address_allowed('8.8.8.8') + assert egress_guard.address_allowed('64:ff9b::808:808') + + +def test_other_fetchers_refuse_ipv4_carried_in_ipv6(monkeypatch): + for answer in ('64:ff9b::a00:1', '::127.0.0.1'): + resolved = [(socket.AF_INET6, socket.SOCK_STREAM, 6, '', (answer, 443, 0, 0))] + monkeypatch.setattr(material_collector.socket, 'getaddrinfo', lambda *args, rows=resolved, **kwargs: rows) + with pytest.raises(ValueError): + material_collector.public_target('https://media.example/a.png') + monkeypatch.setattr(hosted_compute_http.socket, 'getaddrinfo', lambda *args, rows=resolved, **kwargs: rows) + with pytest.raises(hosted_compute_http.TransportError): + hosted_compute_http._resolve('media.example', 2) + + +def test_proxy_forwards_absolute_http_and_removes_proxy_headers(origin, monkeypatch): + monkeypatch.setattr(urllib.request, 'proxy_bypass', lambda host: False) + port = origin.server_address[1] + resolver = lambda host, port, **kw: address('127.0.0.1', port) + with egress_guard.GlobalOnlyProxy(resolver=resolver, allowed=lambda ip: ip == '127.0.0.1', + connect=direct_connect, ports=(port,)) as proxy: + req = urllib.request.Request('http://' + f'public.test:{port}/hello?x=1', + headers={'Proxy-Connection': 'keep-alive', + 'Proxy-Authorization': 'fixture'}) + assert opener(proxy).open(req, timeout=3).read() == b'fixture body' + assert proxy.refusals == [] + path, headers = origin.requests[0] + assert path == '/hello?x=1' + assert not any(k.lower() in ('proxy-connection', 'proxy-authorization') for k in headers) + assert headers['Connection'] == 'close' + + +def test_proxy_rejects_redirect_before_internal_connection(origin, monkeypatch): + monkeypatch.setattr(urllib.request, 'proxy_bypass', lambda host: False) + with socket.socket() as internal: + internal.bind(('127.0.0.2', 0)) + internal.listen() + origin.redirect_port = internal.getsockname()[1] + port = origin.server_address[1] + def resolver(host, target_port, **kwargs): + return address('127.0.0.2' if host == 'internal.test' else '127.0.0.1', target_port) + with egress_guard.GlobalOnlyProxy(resolver=resolver, allowed=lambda ip: ip == '127.0.0.1', + connect=direct_connect, ports=(port, origin.redirect_port)) as proxy: + with pytest.raises(urllib.error.HTTPError) as caught: + opener(proxy).open('http://' + f'public.test:{port}/redirect', timeout=3) + assert caught.value.code == 403 + assert proxy.refusals == ['non_global'] + assert not select.select([internal], [], [], 0.2)[0] + + +def test_proxy_resolves_once_and_connects_to_checked_address(): + queries, targets = [], [] + def resolver(host, port, **kwargs): + queries.append((host, port)) + return address('8.8.8.8' if len(queries) == 1 else '127.0.0.1', port) + def connect(target, timeout): + targets.append(target) + raise ConnectionRefusedError() + with egress_guard.GlobalOnlyProxy(resolver=resolver, connect=connect, ports=(8765,)) as proxy: + response = raw_request(proxy, b'GET http://' + b'public.test:8765/x HTTP/1.1\r\nHost: public.test\r\n\r\n') + assert response.startswith(b'HTTP/1.1 502') + assert len(queries) == 1 + assert targets == [('8.8.8.8', 8765)] + + +def test_proxy_rejects_disallowed_port_malformed_and_excess_connections(): + with egress_guard.GlobalOnlyProxy(max_connections=1) as proxy: + def wait_for_active(expected): + deadline = time.monotonic() + 3 + while time.monotonic() < deadline: + with proxy._lock: + if proxy._active == expected: + return + time.sleep(0.01) + pytest.fail('proxy connection count did not settle') + + assert raw_request(proxy, b'CONNECT public.test:22 HTTP/1.1\r\nHost: public.test\r\n\r\n').startswith(b'HTTP/1.1 403') + wait_for_active(0) + assert raw_request(proxy, b'GET / HTTP/1.1\r\nHost: public.test\r\n\r\n').startswith(b'HTTP/1.1 400') + wait_for_active(0) + port = urllib.parse.urlsplit(proxy.url).port + with socket.socket() as first: + first.connect(('127.0.0.1', port)) + wait_for_active(1) + assert raw_request(proxy, b'GET / HTTP/1.1\r\n\r\n').startswith(b'HTTP/1.1 503') + assert proxy.refusals == ['port', 'malformed'] + + +def download_setup(tmp_path, monkeypatch): + monkeypatch.setattr(server, 'COMFY_INPUT', tmp_path / 'input') + monkeypatch.setattr(server, 'CRAWL_DIR', tmp_path) + monkeypatch.setattr(server, '_resolve_yt_dlp', lambda: '/fixture/yt-dlp') + monkeypatch.setattr(server, '_crawl_cookie_file', lambda url: None) + monkeypatch.setattr(server, '_video_codec', lambda path: 'h264') + monkeypatch.setattr(server, 'socket', SimpleNamespace( + getaddrinfo=lambda host, port, **kwargs: address('8.8.8.8', port), SOCK_STREAM=socket.SOCK_STREAM)) + + +def test_fetch_proxy_argv_environment_and_operator_path(tmp_path, monkeypatch): + download_setup(tmp_path, monkeypatch) + monkeypatch.setenv('NO_PROXY', 'fixture') + monkeypatch.setenv('no_proxy', 'fixture') + calls = [] + def run(argv, **kwargs): + calls.append((list(argv), kwargs)) + filename = argv[argv.index('-o') + 1].replace('%(title).40s', 'clip').replace('%(ext).16s', 'mp4') + Path(filename).write_bytes(b'video') + return subprocess.CompletedProcess(argv, 0, stdout='', stderr='') + monkeypatch.setattr(server.subprocess, 'run', run) + for shared in (False, True): + result = server.fetch_video_url('http://' + 'public.test/x', 'v' * 100, shared_cookies=shared) + assert re.match(r'^castle_url_\d{10}_[0-9a-f]{32}_', result['filename']) + assert len(result['filename'].encode()) <= 200 + argv, kwargs = calls[0] + pos = argv.index('--proxy') + assert pos < argv.index('--') + proxy_url = argv[pos + 1] + for key in ('HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy', 'ALL_PROXY', 'all_proxy'): + assert kwargs['env'][key] == proxy_url + assert 'NO_PROXY' not in kwargs['env'] and 'no_proxy' not in kwargs['env'] + assert '--proxy' not in calls[1][0] and 'env' not in calls[1][1] + + +@pytest.mark.parametrize('failure', ['exit', 'timeout', 'no_file']) +@pytest.mark.parametrize('refusal', ['non_global', 'port']) +def test_fetch_refusal_overrides_failure_message(tmp_path, monkeypatch, failure, refusal): + download_setup(tmp_path, monkeypatch) + proxy_class = egress_guard.GlobalOnlyProxy + monkeypatch.setattr(server.egress_guard, 'GlobalOnlyProxy', lambda: proxy_class( + resolver=lambda host, port, **kwargs: address('127.0.0.2', port))) + def run(argv, **kwargs): + url = argv[argv.index('--proxy') + 1] + port = urllib.parse.urlsplit(url).port + with socket.socket() as client: + client.settimeout(3) + client.connect(('127.0.0.1', port)) + if refusal == 'port': + client.sendall(b'CONNECT public.test:22 HTTP/1.1\r\nHost: public.test\r\n\r\n') + else: + client.sendall(b'GET http://' + b'internal.test/ HTTP/1.1\r\nHost: internal.test\r\n\r\n') + assert client.recv(1024).startswith(b'HTTP/1.1 403') + if failure == 'timeout': + raise subprocess.TimeoutExpired(argv, 1) + return subprocess.CompletedProcess(argv, 0 if failure == 'no_file' else 1, stdout='', stderr='failure') + monkeypatch.setattr(server.subprocess, 'run', run) + with pytest.raises(ValueError, match='這個連結會轉到非公開或不支援的位址,無法下載;請改為上傳影片檔'): + server.fetch_video_url('http://' + 'public.test/x', 'video', shared_cookies=False) + + +def test_connect_tunnels_buffered_bytes_and_relay(): + with socket.socket() as origin: + origin.bind(('127.0.0.1', 0)) + origin.listen() + port = origin.getsockname()[1] + received = [] + def echo(): + upstream, _ = origin.accept() + with upstream: + upstream.settimeout(3) + received.append(upstream.recv(128)) + upstream.sendall(b'echo:' + received[0]) + worker = threading.Thread(target=echo, daemon=True) + worker.start() + resolver = lambda host, target_port, **kwargs: address('127.0.0.1', target_port) + with egress_guard.GlobalOnlyProxy(resolver=resolver, allowed=lambda ip: ip == '127.0.0.1', + connect=direct_connect, ports=(port,)) as proxy: + proxy_port = urllib.parse.urlsplit(proxy.url).port + with socket.socket() as client: + client.settimeout(3) + client.connect(('127.0.0.1', proxy_port)) + client.sendall(f'CONNECT public.test:{port} HTTP/1.1\r\nHost: public.test\r\n\r\nhello'.encode()) + response = b'' + while b'echo:hello' not in response: + part = client.recv(1024) + assert part + response += part + assert response.startswith(b'HTTP/1.1 200 Connection established\r\n\r\n') + worker.join(2) + assert received == [b'hello'] + + +def test_mixed_dns_answers_are_rejected_and_never_connected(): + targets = [] + def resolver(host, port, **kwargs): + return address('8.8.8.8', port) + address('127.0.0.1', port) + def connect(target, timeout): + targets.append(target) + raise AssertionError('must not connect') + with egress_guard.GlobalOnlyProxy(resolver=resolver, connect=connect) as proxy: + response = raw_request(proxy, b'GET http://' + b'public.test/ HTTP/1.1\r\nHost: public.test\r\n\r\n') + assert response.startswith(b'HTTP/1.1 403') + assert proxy.refusals == ['non_global'] + assert not targets + + +@pytest.mark.parametrize('raw_data', [ + b'GET https://' + b'public.test/ HTTP/1.1\r\nHost: public.test\r\n\r\n', + b'PUT http://' + b'public.test/ HTTP/1.1\r\nHost: public.test\r\n\r\n', + b'GET http://' + b'public.test/ HTTP/1.1\r\nX-Fill: ' + b'a' * 16384 + b'\r\n\r\n', +], ids=['https', 'method', 'oversized']) +def test_proxy_rejects_invalid_forms_and_oversized_heads(raw_data): + with egress_guard.GlobalOnlyProxy() as proxy: + assert raw_request(proxy, raw_data).startswith(b'HTTP/1.1 400') + assert proxy.refusals == ['malformed'] + + +def test_fetch_conversion_suffix_stays_within_name_limit(tmp_path, monkeypatch): + download_setup(tmp_path, monkeypatch) + monkeypatch.setattr(server, '_video_codec', lambda path: 'av1') + monkeypatch.setattr(server, 'ensure_cv2_compatible_video', lambda source, target: target.write_bytes(b'converted')) + def run(argv, **kwargs): + filename = argv[argv.index('-o') + 1].replace('%(title).40s', 't' * 40).replace('%(ext).16s', 'mp4') + Path(filename).write_bytes(b'video') + return subprocess.CompletedProcess(argv, 0, stdout='', stderr='') + monkeypatch.setattr(server.subprocess, 'run', run) + result = server.fetch_video_url('http://' + 'public.test/x', 'v' * 100, shared_cookies=True) + assert result['filename'].endswith('_cv2.mp4') + assert len(result['filename'].encode()) <= 200 diff --git a/scripts/test_h3_provider_worker.py b/scripts/test_h3_provider_worker.py new file mode 100644 index 0000000..199d6d3 --- /dev/null +++ b/scripts/test_h3_provider_worker.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""Exact-class tests for confirmed H3 graph preparation.""" + +from __future__ import annotations + +import hashlib +import json +import sys +import tempfile +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "webui")) + +from minimax_h3_product import ANIME_GUARDRAIL, REALISTIC_GUARDRAIL # noqa: E402 +from provider_fabric.h3_catalog import H3_VARIANT_CONTRACTS # noqa: E402 +from provider_fabric.h3_profiles import h3_character_profiles # noqa: E402 +from provider_fabric.h3_worker import ( # noqa: E402 + H3QueueRequest, + H3SubmissionProcessor, + h3_upload_basename, + profile_binding, +) +from provider_fabric.models import ( # noqa: E402 + CapabilityKind, + CharacterRef, + MediaAsset, + MediaKind, + RouteDecision, + RouteIntent, + TaskReceipt, + TaskState, + VisualClass, +) +from provider_fabric.provider_worker import DefiniteLocalFailure # noqa: E402 + + +def creative_instruction() -> dict: + material = { + "schema_version": "castle.creative-instruction.v1", + "shot_id": "shot-001", + "frame_intent": "Hero stands beside a canvas in a garden.", + "observable_action": "Hero lifts a brush and paints one flower.", + "camera": "Stable medium shot, slow push-in.", + "audio_intent": "Soft birds and one short greeting.", + "language": "zh-TW", + } + raw = json.dumps(material, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() + return {**material, "content_hash": hashlib.sha256(raw).hexdigest()} + + +class H3ProviderWorkerTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.path = Path(temporary.name) / "avatar.png" + self.path.write_bytes(b"h3-avatar") + self.observed = [] + + def profile(self, key): + variant_id = key.removeprefix("local_comfy:") + contract_id = H3_VARIANT_CONTRACTS[variant_id] + return { + item.key: item for item in h3_character_profiles({contract_id}) + }[key] + + def bundle(self, visual=VisualClass.ANIME): + variant = ( + "image-video.anime.h3-fl2va.v1" + if visual is VisualClass.ANIME + else "image-video.realistic.h3-fl2va.v1" + ) + character = CharacterRef("castle:hero", visual, "Hero") + asset = MediaAsset( + "castle-character:castle:hero:avatar", + MediaKind.IMAGE, + "castle://character-assets/hero/avatar", + visual, + (character.character_id,), + "image/png", + self.path.stat().st_size, + hashlib.sha256(self.path.read_bytes()).hexdigest(), + ) + intent = RouteIntent( + CapabilityKind.IMAGE_TO_VIDEO, + visual, + (character,), + (asset,), + frozenset({"aspect", "motion_profile", "quality"}), + ("local_comfy",), + ) + decision = RouteDecision( + "local_comfy", variant, (f"local_comfy:{variant}",), (), "router-v1" + ) + profile = self.profile(f"local_comfy:{variant}") + return { + "owner_user_id": "member-one", + "intent": { + "intent": intent.to_dict(), + "payload": { + "options": { + "aspect": "portrait", + "motion_profile": "gentle" if visual is VisualClass.ANIME else "natural", + "quality": "quality", + }, + "creative_instruction": creative_instruction(), + "capability_grant": profile_binding(profile), + }, + }, + "decision": decision.to_dict(), + "task": {"task_id": "task-h3-001", "client_request_id": "request-h3-001"}, + } + + def executor(self, request): + self.observed.append(request) + return TaskReceipt( + "local_comfy", + request.client_request_id, + TaskState.SUBMITTED, + external_task_id="comfy-prompt-001", + ) + + def processor(self): + return H3SubmissionProcessor( + lambda owner, asset: self.path, + self.executor, + profile_resolver=self.profile, + ) + + def test_anime_and_realistic_compile_distinct_guardrails(self): + for visual, expected, forbidden in ( + (VisualClass.ANIME, ANIME_GUARDRAIL, REALISTIC_GUARDRAIL), + (VisualClass.REALISTIC, REALISTIC_GUARDRAIL, ANIME_GUARDRAIL), + ): + processor = self.processor() + processor(self.bundle(visual)) + request = self.observed[-1] + self.assertIsInstance(request, H3QueueRequest) + encoded = json.dumps(request.graph, ensure_ascii=False) + self.assertIn(expected, encoded) + self.assertNotIn(forbidden, encoded) + self.assertRegex(request.graph_sha256, r"^[0-9a-f]{64}$") + self.assertEqual( + request.upload_basename, + h3_upload_basename(processor._upload_name_key, request.source_sha256, ".png"), + ) + self.assertIn(request.upload_basename, encoded) + + def test_changed_avatar_never_reaches_gpu_executor(self): + bundle = self.bundle() + self.path.write_bytes(b"changed") + with self.assertRaisesRegex(DefiniteLocalFailure, "input bytes changed"): + self.processor()(bundle) + self.assertEqual(self.observed, []) + + def test_missing_technical_readiness_never_reaches_gpu_executor(self): + processor = H3SubmissionProcessor( + lambda owner, asset: self.path, + self.executor, + profile_resolver=lambda key: {item.key: item for item in h3_character_profiles()}[key], + ) + with self.assertRaisesRegex(DefiniteLocalFailure, "not technically"): + processor(self.bundle()) + self.assertEqual(self.observed, []) + + def test_changed_technical_binding_never_reaches_gpu_executor(self): + bundle = self.bundle() + bundle["intent"]["payload"]["capability_grant"][ + "technical_evidence_id" + ] = "h3-runtime:other-contract" + with self.assertRaisesRegex(DefiniteLocalFailure, "evidence changed"): + self.processor()(bundle) + self.assertEqual(self.observed, []) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/scripts/test_hardware_catalog.py b/scripts/test_hardware_catalog.py index 500660b..f094915 100644 --- a/scripts/test_hardware_catalog.py +++ b/scripts/test_hardware_catalog.py @@ -87,13 +87,17 @@ def forbidden(*args,**kwargs):raise AssertionError('No network or hardware proce const file=document.getElementById('file'),files=new DataTransfer();files.items.add(new File(['local'],'reference.png'));file.files=files.files; check(h.profile==='vram-32'&&!generate.disabled,'default enabled'); h.setProfile('none');await wait();check(generate.disabled,'no GPU blocks generation');check(document.getElementById('tool').classList.contains('hardware-unavailable'),'dim marker'); - check(!form.querySelector('.hardware-cloud-option').hidden&&form.querySelector('.hardware-cloud-option a').rel.includes('sponsored'),'blocked contextual referral'); + const cloud=form.querySelector('.hardware-cloud-option');const links=[...cloud.querySelectorAll('a')]; + check(!cloud.hidden&&links.length===2&&links.every(a=>a.rel.includes('sponsored')&&a.target==='_blank'),'blocked contextual referrals'); + check(links[0].href.includes('ref=TEDH2FND')&&links[1].href.includes('inviteCode=qqgzxufp'),'both referral hrefs'); + check(cloud.textContent.includes('TEDH2FND')&&cloud.textContent.includes('qqgzxufp'),'both referral codes'); WebComfyI18n.setLanguage('en');await wait(); const tool=document.getElementById('tool'),rect=tool.getBoundingClientRect(); check(tool.scrollWidth<=tool.clientWidth+1,'sidebar card contained'); for(const node of tool.children){if(!node.hidden)check(node.getBoundingClientRect().right<=rect.right+1,'card child within sidebar');} WebComfyI18n.setLanguage('zh-Hant');await wait(); h.setProfile('vram-24');await wait();check(!generate.disabled&&h.canUse('text2img')&&!h.canUse('dance'),'24GB threshold'); + check(form.querySelector('.hardware-cloud-option').hidden,'referral hidden when allowed'); h.setProfile('dual-24');check(!h.canUse('dance'),'dual cards do not pool'); check(form.querySelector('.hardware-reason').textContent.includes('48 GB'),'dual reason'); form.querySelector('.app-demo').dataset.state='running';generate.disabled=true;h.setProfile('none');h.setProfile('autoip');check(generate.disabled,'running remains disabled'); diff --git a/scripts/test_landing_browser.py b/scripts/test_landing_browser.py index f0fe670..e90877d 100644 --- a/scripts/test_landing_browser.py +++ b/scripts/test_landing_browser.py @@ -52,11 +52,29 @@ def log_message(self, *args): pass if qr.evaluate('(image) => image.complete && image.naturalWidth > 0'): break page.wait_for_timeout(20) assert qr.evaluate('(image) => image.complete && image.naturalWidth > 0'), 'Referral QR renders' + running = page.locator('a[href="https://www.runninghub.ai?inviteCode=qqgzxufp"]').first + assert 'qqgzxufp' in page.content() + assert 'sponsored' in running.get_attribute('rel') + rh = page.locator('img[src$="runninghub-referral.svg"]') + rh.scroll_into_view_if_needed() + for _ in range(100): + if rh.evaluate('(image) => image.complete && image.naturalWidth > 0'): break + page.wait_for_timeout(20) + assert rh.evaluate('(image) => image.complete && image.naturalWidth > 0'), 'RunningHub QR renders' + assert page.evaluate('document.documentElement.scrollWidth') <= width + 1 page.locator('a[href^="./demo/"]').first.click() page.wait_for_selector('form[data-demo-id="text2img"]') assert urlsplit(page.url).path == '/Web_Comfyui/demo/' assert page.locator('html').get_attribute('lang') == 'en' assert 'Not a live service' in page.locator('#docsBanner').inner_text() + banner_links = page.locator('#docsBanner a[target="_blank"]') + assert banner_links.count() >= 2 + for index in range(banner_links.count()): + assert 'sponsored' in banner_links.nth(index).get_attribute('rel') + assert banner_links.nth(index).get_attribute('target') == '_blank' + hrefs = [banner_links.nth(index).get_attribute('href') for index in range(banner_links.count())] + assert any('ref=TEDH2FND' in href for href in hrefs) + assert any('inviteCode=qqgzxufp' in href for href in hrefs) assert page.locator('#hardwareSelect').count() assert not any('/api/' in url or urlsplit(url).netloc != urlsplit(base).netloc for url in requests) assert not errors, errors diff --git a/scripts/test_review2_fixes_r35.py b/scripts/test_review2_fixes_r35.py new file mode 100644 index 0000000..9f062aa --- /dev/null +++ b/scripts/test_review2_fixes_r35.py @@ -0,0 +1,223 @@ +"""Snapshot-only adversarial checks of new code; no provider or live DB access.""" +import ast +from contextlib import contextmanager +import fcntl +import importlib.util +import json +import os +from pathlib import Path +import sqlite3 +import sys +from types import SimpleNamespace +import pytest +from test_review2_original_r35 import CANDIDATE, rig, allocated, job, uid, Crash, BridgeError, encoded +from scripts.colab_lease_sweeper import sweep + + +def worker_module(monkeypatch): + monkeypatch.syspath_prepend(str(CANDIDATE/'scripts/colab_remote')) + spec=importlib.util.spec_from_file_location('second_pass_worker',CANDIDATE/'scripts/colab_session_worker.py') + m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) + return m + + +def test_bootstrap_reporter_identity_is_overwritten(tmp_path,monkeypatch,rig): + w=worker_module(monkeypatch) + root=tmp_path/'remote';root.mkdir() + (root/'bootstrap.json').write_text(json.dumps([{'models':[]}])) + callbacks=[];errors=[];in_bootstrap=[] + class Event: + stopped=False + def is_set(self):return self.stopped + def set(self):self.stopped=True + def wait(self,*a):self.set() + class Thread: + def __init__(self,target,**kw):callbacks.append(target) + def start(self):pass + def join(self):pass + monkeypatch.setattr(w,'threading',SimpleNamespace(Event=Event,Thread=Thread)) + monkeypatch.setattr(w.subprocess,'check_output',lambda *a,**kw:'NVIDIA A100, 40536') + def long_bootstrap(plan,cache,**kw): + in_bootstrap.append(True) + # Schedule the actual reporter callback once the first plan has begun, + # exactly when a second 15-second heartbeat can execute in production. + callbacks[0]() + status=json.loads((root/'bootstrap-status.json').read_text()) + identity=json.loads((root/'bootstrap-process.json').read_text()) + assert status['phase']=='running' and status['progress_at']>0 + assert {k:status[k] for k in identity}==identity + errors.append(False) + monkeypatch.setattr(w,'bootstrap',long_bootstrap) + assert w.bootstrap_session(root)==0 + assert in_bootstrap and errors == [False] + # With the worker still alive but no new progress, controller cancels it. + s,b,clock,account,state=rig;allocated(rig,'bootstrap') + launched=clock[0];clock[0]+=121 + original=s._exec + monkeypatch.setattr(s,'_exec',lambda st,code: + {'phase':'running','alive':True,'progress_at':launched,'identity':{'pid':1,'start_ticks':'1'}} + if 'bootstrap-status.json' in code else original(st,code)) + s.sessions.tick_all() + assert s.sessions.get(state['id'])['fault_streak']==1 + before=s.sessions.get(state['id'])['last_tick'] + s.sessions.tick_all() + assert s.sessions.get(state['id'])['last_tick']==before + assert s.sessions.get(state['id'])['private_rpc_error']=={'bootstrap_probe':{'type':'progress_stale'}} + assert s.sessions.get(state['id'])['reason']=='watchdog_state_lost' + s.sessions.tick_all() + assert s.sessions.get(state['id'])['released'] + + +def test_close_during_allocation_rpc_cannot_commit(rig,monkeypatch): + s,b,clock,account,state=rig;original=s._call;attempts=[] + real_connect=sqlite3.connect + # Reduce only the wait length, preserving SQLite's actual locking behavior. + def fast_connect(*args,**kw):kw['timeout']=0.01;return real_connect(*args,**kw) + monkeypatch.setattr(sqlite3,'connect',fast_connect) + def provider(state,op,**kw): + if op=='runtime_allocate': + # Independent connection used by an HTTP close during the RPC. + s.sessions.close('owner') + s.sessions.settings('owner',{'idle_minutes':30}) + assert s.sessions.snapshot('owner')['session']['close_requested'] + attempts.append(True) + return original(state,op,**kw) + monkeypatch.setattr(s,'_call',provider) + s.sessions.tick_all() + final=s.sessions.get(state['id']) + assert attempts and final['phase']=='closed' and final['close_requested'] + assert final['settings']['idle_minutes']==30 + assert any(op=='runtime_stop' for op,_ in b.calls) + assert not any(op in {'upload','remote_exec'} for op,_ in b.calls) + + +def test_sweeper_global_timeout_starves_later_unarmed_lease(rig): + s,b,clock,account,state=rig + states=[] + for n in range(4): + if n==0:current=state + else: + current=s.sessions.new_state('owner'+str(n),uid(),str(n)*64,state['settings']) + with s.db() as db:db.execute('INSERT INTO work_sessions VALUES (?,?,?)',(current['id'],current['owner'],encoded(current))) + current=s.sessions.save(current['id'],phase='uncertain',allocation_id=uid(),allocation_at=clock[0], + gpu='A100',deadline_epoch=clock[0]+21600,last_balance=1000) + states.append(current) + timeout=int(next(line.split('=')[1] for line in (CANDIDATE/'scripts/systemd/web-comfyui-colab-lease-sweeper.service').read_text().splitlines() if line.startswith('TimeoutStartSec='))) + assert timeout==240 + elapsed=[0];calls=[] + class SystemdKill(BaseException):pass + def bridge(op,account_dir,**kw): + calls.append((op,kw)) + if op=='runtime_lookup': + if kw['allocation_id'] in {x['allocation_id'] for x in states[:3]}: + elapsed[0]+=75;raise BridgeError('timeout') + elapsed[0]+=20 + if elapsed[0]>=timeout:raise SystemdKill() + return {'found':True,'runtime_id':kw['allocation_id'],'accelerator':'A100'} + if op=='runtime_stop':return {'stopped':True} + if op=='account_status':return {'authenticated':True,'balance_compute_units':1000} + raise AssertionError(op) + for _ in range(4): + elapsed[0]=0;clock[0]+=300 + try:sweep(s.root,bridge,s.clock) + except (RuntimeError,SystemdKill):pass + if s.sessions.get(states[3]['id'])['released']:break + victim=s.sessions.get(states[3]['id']) + assert victim['released'] and victim['phase']=='closed' + assert any(op=='runtime_stop' for op,_ in calls) + + +def test_sweeper_same_flock_and_fresh_active_lease(rig): + s,b,clock,account,state=rig;st=allocated(rig) + j=job(rig,st['id'],'running',runtime_id=st['runtime_id']) + s.sessions.save(st['id'],active_job=j['id']) + before=len(b.calls) + assert sweep(s.root,b,s.clock) + assert len(b.calls)==before and not s.sessions.get(st['id'])['released'] + clock[0]+=301 + with (s.root/'worker.lock').open('a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + assert sweep(s.root,b,s.clock) is False + assert len(b.calls)==before + assert sweep(s.root,b,s.clock) + assert s.sessions.get(st['id'])['released'] + assert {op for op,_ in b.calls[before:]}<={'runtime_stop','account_status','runtime_lookup'} + + +def test_sweeper_recovers_prearm_gap_without_post(rig,monkeypatch): + s,b,clock,account,state=rig + def crash(*a):raise Crash() + monkeypatch.setattr(s.sessions,'assigned',crash) + with pytest.raises(Crash):s.sessions.tick_all() + b.found=True;before=len(b.calls) + assert sweep(s.root,b,s.clock) + assert s.sessions.get(state['id'])['released'] + assert {op for op,_ in b.calls[before:]}<={'runtime_stop','account_status','runtime_lookup'} + + +def test_sweeper_fails_closed_on_database_lock_then_retries(rig,monkeypatch): + s,b,clock,account,state=rig;allocated(rig);clock[0]+=301 + real_connect=sqlite3.connect + def fast_connect(*args,**kw):kw['timeout']=0.01;return real_connect(*args,**kw) + monkeypatch.setattr(sqlite3,'connect',fast_connect) + before=len(b.calls) + with real_connect(s.root/'state.sqlite3') as db: + db.execute('BEGIN EXCLUSIVE') + with pytest.raises(sqlite3.OperationalError):sweep(s.root,b,s.clock) + assert len(b.calls)==before + assert sweep(s.root,b,s.clock) + assert s.sessions.get(state['id'])['released'] + + +def test_sweeper_incomplete_schema_does_not_call_provider(tmp_path): + root=tmp_path/'colab';root.mkdir() + with sqlite3.connect(root/'state.sqlite3') as db:db.execute('CREATE TABLE work_sessions (id TEXT)') + calls=[] + with pytest.raises(sqlite3.OperationalError):sweep(root,lambda *a,**kw:calls.append(a)) + assert calls==[] + # The failure also releases the worker flock. + with (root/'worker.lock').open('a') as lock:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + + +def test_release_unknown_final_balance_preserves_reservation(rig,monkeypatch): + s,b,clock,account,state=rig;st=allocated(rig) + j=job(rig,st['id'],'cleanup_pending',runtime_id=st['runtime_id'],outcome='failed') + st=s.sessions.save(st['id'],active_job=j['id'],phase='closing') + b.balance-=2;b.stop_cost=1;original=s._call;after=[False];missing=[True] + def call(st,op,**kw): + if op=='account_status' and after[0] and missing[0]:raise BridgeError('timeout') + result=original(st,op,**kw) + if op=='runtime_stop':after[0]=True + return result + monkeypatch.setattr(s,'_call',call) + s.sessions.release(st) + assert s.sessions.get(st['id'])['phase']=='released_unsettled' + assert not s.job('owner',j['id'])['released'] + assert not s.sessions.snapshot('owner')['session_ledger'][0]['settled'] + missing[0]=False;s.sessions.tick_all() + assert s.sessions.get(st['id'])['session_units']==1 + assert s.job('owner',j['id'])['units_observed']==2 + assert len([1 for op,_ in b.calls if op=='runtime_stop'])==1 + + +def test_persona_actual_consumer_resolves_private_view(tmp_path,monkeypatch): + import tempfile + w=worker_module(monkeypatch);root=tmp_path/'job';root.mkdir() + session=tmp_path/'session';(session/'cache').mkdir(parents=True) + view=w.cache_view(root,session) + (root/'comfy-input/ref.wav').write_bytes(b'offline') + (view/'voice-export.json').write_text(json.dumps({'persona':'offline','reference_name':'ref.wav','reference_text':''})) + p=CANDIDATE/'scripts/colab_remote/native_voice_node.py' + cls=next(n for n in ast.parse(p.read_text()).body if isinstance(n,ast.ClassDef) and n.name=='CastleBreezyVoiceTTS') + class Captured(BaseException):pass + def run(args,**kw): + request=json.loads(Path(args[-1]).read_text()) + assert Path(request['reference']).resolve()==root/'comfy-input/ref.wav' + assert Path(request['reference']).read_bytes()==b'offline' + raise Captured() + scope={'Path':Path,'os':os,'json':json,'tempfile':tempfile,'__file__':str(p),'subprocess':SimpleNamespace(run=run,DEVNULL=-3)} + exec(compile(ast.Module(body=[cls],type_ignores=[]),str(p),'exec'),scope) + monkeypatch.setenv('CASTLE_PARITY_CACHE',str(view)) + with pytest.raises(Captured):scope['CastleBreezyVoiceTTS']().synth('offline','') + + diff --git a/scripts/test_review2_original_r35.py b/scripts/test_review2_original_r35.py new file mode 100644 index 0000000..b16b859 --- /dev/null +++ b/scripts/test_review2_original_r35.py @@ -0,0 +1,421 @@ +"""Independent safe-expectation adaptation of the original 30 probes. Snapshot only. +Schema/media are mocked where snapshot omits catalog; lifecycle code is real. +""" +import ast +import importlib.util +import json +from pathlib import Path +import socket +import sys +import uuid +import pytest + +CANDIDATE = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(CANDIDATE/'webui'), str(CANDIDATE)] +from colab_service import ColabService, BridgeError, encoded +from compute_parity.colab import ColabNative +from compute_parity.journal import Journal + +class Crash(BaseException): pass + +def uid(): return str(uuid.uuid4()) + +class Bridge: + installed = True + def __init__(self): + self.balance = 1000 + self.calls = [] + self.uncertain = False + self.found = False + self.stop_cost = 0 + def __call__(self, op, account_dir, **kw): + self.calls.append((op, kw)) + if op == 'account_identity': return {'bound':True, 'subject_key':'a'*64} + if op == 'account_status': return {'authenticated':True, 'balance_compute_units':self.balance} + if op == 'runtime_allocate': + if self.uncertain: raise BridgeError('allocation_uncertain', True) + return {'found':True, 'runtime_id':kw['allocation_id'], 'accelerator':kw['gpu']} + if op == 'runtime_lookup': return {'found':self.found, 'runtime_id':kw['allocation_id'], 'accelerator':kw['gpu']} + if op == 'runtime_stop': + self.balance -= self.stop_cost + self.stop_cost = 0 + return {'stopped':True} + if op == 'remote_exec': + compile(kw['code'], 'remote', 'exec') + result = {'phase':'running'} if 'bootstrap-status.json' in kw['code'] else {'heartbeat':True, 'clean':True,'watchdog_identity':{'pid':1,'start_ticks':'42','deadline':1021600.0,'lock_dev':1,'lock_ino':2}} + if "'armed':True" in kw['code']: + import re + result={'armed':True,'watchdog_identity':{'pid':1,'start_ticks':'42','deadline':1021600.0,'lock_dev':1,'lock_ino':2},'session_id':re.search(r"'session_id':'([^']+)'",kw['code']).group(1)} + return {'stdout':'WEB_COMFYUI_JSON='+json.dumps(result)} + raise AssertionError(op) + +@pytest.fixture +def rig(tmp_path, monkeypatch): + monkeypatch.setattr(ColabService, 'start', lambda self:None) + def forbidden(*args, **kw): raise AssertionError('network prohibited') + monkeypatch.setattr(socket.socket, 'connect', forbidden) + b = Bridge(); clock = [1000000.0] + s = ColabService(tmp_path/'colab', b, lambda:clock[0]) + account = s.create_account('owner','test')['id'] + s.account_action('owner', account, 'refresh', {}) + state = s.sessions.open('owner', account, 15) + return s,b,clock,account,state + +def allocated(rig, phase='ready'): + s,b,clock,account,state = rig + s.sessions.tick_all() + return s.sessions.save(state['id'], phase=phase, watchdog_armed=True, + gpu_name='NVIDIA A100', idle_since=clock[0], uploads=[{}], launch_at=clock[0]) + +def job(rig, sid, phase='queued', **kw): + s,b,clock,account,state=rig + j={'id':uid(), 'account_id':account, 'session_job':True, 'native_parity':True, + 'phase':phase, 'gpu':'A100', 'units_observed':0, 'released':False, + 'created_at':clock[0], 'deadline_epoch':clock[0]+3600, 'max_minutes':60, + 'artifacts':[], 'uploads':[], 'quote_amount':15, **kw} + if sid: j['session_id']=sid + with s.db() as db: db.execute('INSERT INTO jobs VALUES (?,?,?,?,?)',(j['id'],'owner',account,'identity',encoded(j))) + return j + +def test_recovered_assignment_gets_an_extra_six_hours(rig): + s,b,clock,account,state=rig + b.uncertain=True + s.sessions.tick_all() + original=s.sessions.get(state['id']) + assert original['phase']=='uncertain' and not original.get('watchdog_armed') + clock[0]+=7*3600; b.found=True + s=ColabService(s.root,b,s.clock) + s.sessions.tick_all() + recovered=s.sessions.get(state['id']) + assert recovered['phase']=='closed' and recovered['released'] + assert recovered['deadline_epoch']==original['allocation_at']+6*3600 + assert any(op=='runtime_stop' for op,_ in b.calls) + +def test_dead_bootstrap_keeps_idle_runtime_for_thirty_minutes(rig): + s,b,clock,account,state=rig + allocated(rig,'bootstrap') + # A killed bootstrap leaves the actual worker's persisted phase=running. + for _ in range(30): + clock[0]+=60 + s=ColabService(s.root,b,s.clock) + s.sessions.tick_all() + final=s.sessions.get(state['id']) + assert final['phase']=='closed' and not final.get('active_job') + assert any(op=='runtime_stop' for op,_ in b.calls) + +def test_close_between_snapshot_and_allocate_is_lost(rig): + s,b,clock,account,state=rig + stale=s.sessions.get(state['id']) + s.sessions.close('owner') + assert s.sessions.get(state['id'])['close_requested'] + s.sessions.tick(stale) + final=s.sessions.get(state['id']) + assert final['phase']=='closed' and final.get('close_requested') + assert not any(op=='runtime_allocate' for op,_ in b.calls) + +def test_job_unbound_at_crash_opens_second_session(rig,monkeypatch): + from contextlib import contextmanager + import scripts.colab_session_inputs as schema + import compute_parity.private_assets as assets + s,b,clock,account,state=rig + allocated(rig) + # Snapshot contains no catalog/materials: mock validation only; execute real + # admission, session binding, SQL commit and restart code with the original fault. + monkeypatch.setattr(schema,'validate_native_manifest',lambda m,*a,**kw:m) + monkeypatch.setattr(assets,'freeze_private_models',lambda *a:[]) + body={'request_id':uid(),'account_id':account,'gpu':'A100','max_minutes':60,'quote_amount':15,'files':[]} + spec={'type':'video','engine':'castle_native_p1','bundle':{'models':[]}} + real_db=s.db + class DB: + def __init__(self,db):self.db=db + def execute(self,sql,args=()): + result=self.db.execute(sql,args) + if sql.startswith('INSERT INTO jobs'):raise Crash() + return result + @contextmanager + def crash_db(): + with real_db() as db:yield DB(db) + with monkeypatch.context() as m: + m.setattr(s,'db',crash_db) + with pytest.raises(Crash):s._submit('owner',body,_native=spec) + with s.db() as db:assert db.execute('SELECT count(*) FROM jobs').fetchone()[0]==0 + s._submit('owner',body,_native=spec) + j=s.job('owner',body['request_id']) + assert j['session_id']==state['id'] + clock[0]+=301 + s=ColabService(s.root,b,s.clock);s.sessions.tick_all();s.tick(j) + assert s.sessions.get(state['id'])['released'] + assert s.job('owner',j['id'])['phase']=='failed' + # Also exercise a persisted pre-fix unbound row, not only rollback. + old=job(rig,None);s.tick(old) + assert s.job('owner',old['id'])['phase']=='failed' + clock[0]+=300;s.sessions.tick_all() + assert len([op for op,_ in b.calls if op=='runtime_allocate'])==1 + + +def test_release_crash_makes_journal_and_session_disagree(rig,monkeypatch): + from contextlib import contextmanager + s,b,clock,account,state=rig + state=allocated(rig) + j=job(rig,state['id'],'cleanup_pending',runtime_id=state['runtime_id'],outcome='failed') + state=s.sessions.save(state['id'],active_job=j['id'],phase='closing') + journal=Journal(s.root.parent/'compute-parity/journal.sqlite3') + journal.reserve('owner',j['id'],'colab',account,'dance.anime.chatgpt','identity',{'unit':'CU','amount':15}) + b.balance-=2;b.stop_cost=1 + real_db=s.db;injected=[] + class DB: + def __init__(self,db):self.db=db + def execute(self,sql,args=()): + result=self.db.execute(sql,args) + if sql.startswith('UPDATE work_sessions SET state=') and json.loads(args[0])['phase']=='closed': + injected.append(True);raise Crash() + return result + @contextmanager + def crash_db(): + with real_db() as db:yield DB(db) + with monkeypatch.context() as m: + m.setattr(s,'db',crash_db) + with pytest.raises(Crash):s.sessions.release(state) + assert injected and not s.job('owner',j['id'])['released'] + assert s.sessions.get(state['id'])['phase']=='released_unsettled' + ColabNative(s,journal).poll('owner',j['id']) + assert journal.get('owner',j['id']).get('actual_cost') is None + s=ColabService(s.root,b,s.clock);s.sessions.tick_all() + ColabNative(s,journal).poll('owner',j['id']) + ledger=journal.ledger('owner') + assert s.job('owner',j['id'])['units_observed']==ledger['colab']['actual']==2 + assert ledger['colab_sessions']['sessions'][0]['job_units']==2 + assert ledger['colab_sessions']['actual']==1 + assert ledger['colab_sessions']['sessions'][0]['settled'] + + +def test_release_omits_usage_during_stop(rig): + s,b,clock,account,state=rig + state=allocated(rig) + b.balance-=2; b.stop_cost=1 + s.sessions.release(s.sessions.save(state['id'],phase='closing')) + line=s.sessions.snapshot('owner')['session_ledger'][0] + assert line['total_observed']==3 and line['settled'] + assert 1000-b.balance==3 + +def test_uncertain_session_is_reported_as_running_job(rig): + s,b,clock,account,state=rig + j=job(rig,state['id']) + journal=Journal(s.root.parent/'compute-parity/journal.sqlite3') + journal.reserve('owner',j['id'],'colab',account,'dance.anime.chatgpt','identity',{'unit':'CU','amount':15}) + b.uncertain=True; s.sessions.tick_all() + assert s.sessions.get(state['id'])['phase']=='uncertain' + receipt=ColabNative(s,journal).poll('owner',j['id']) + assert receipt['state']=='submission_uncertain' + assert receipt['diagnostics']['stage']=='provisioning' + assert receipt['diagnostics']['error_code']=='allocation_uncertain' + +def test_close_late_assignment_and_absence_grace_control(rig): + s,b,clock,account,state=rig + b.uncertain=True; s.sessions.tick_all() + allocation=s.sessions.get(state['id'])['allocation_id'] + s.sessions.close('owner'); clock[0]+=149; s.sessions.tick_all() + assert not s.sessions.get(state['id'])['released'] + b.found=True; s.sessions.tick_all() + assert s.sessions.get(state['id'])['released'] + assert [kw['runtime_id'] for op,kw in b.calls if op=='runtime_stop']==[allocation] + assert len([op for op,_ in b.calls if op=='runtime_allocate'])==1 + +def test_voice_consumer_still_uses_removed_shared_input_path(tmp_path): + # Load only the pure arguments function: no voice runtime import or data. + p=CANDIDATE/'scripts/colab_remote/native_voxcpm_worker.py' + tree=ast.parse(p.read_text()) + fn=next(n for n in tree.body if isinstance(n,ast.FunctionDef) and n.name=='arguments') + scope={}; exec(compile(ast.Module(body=[fn],type_ignores=[]),str(p),'exec'),scope) + export={'settings':{'cfg_value':2,'inference_timesteps':10,'normalize':True,'denoise':True}, + 'text':'', 'reference_name':'reference.wav','reference_text':'', + 'speaker_threshold':0.6,'speaker_max_attempts':1} + # Read required option keys without any private voice data. + for n in ast.walk(fn): + if isinstance(n,ast.Subscript) and isinstance(n.value,ast.Name) and n.value.id=='settings' and isinstance(n.slice,ast.Constant): + export['settings'].setdefault(n.slice.value,1) + view_tree=ast.parse((CANDIDATE/'scripts/colab_session_worker.py').read_text()) + view_fn=next(n for n in view_tree.body if isinstance(n,ast.FunctionDef) and n.name=='cache_view') + view_scope={'Path':Path};exec(compile(ast.Module(body=[view_fn],type_ignores=[]),'view','exec'),view_scope) + (tmp_path/'job').mkdir();(tmp_path/'session/cache').mkdir(parents=True) + cache=view_scope['cache_view'](tmp_path/'job',tmp_path/'session') + (tmp_path/'job/comfy-input/reference.wav').write_bytes(b'offline') + args=scope['arguments'](cache,export,tmp_path/'out.wav') + reference=Path(args[args.index('--reference-audio')+1]) + assert reference.resolve()==tmp_path/'job/comfy-input/reference.wav' + assert reference.is_file() + +def test_success_marker_survives_worker_death_before_private_cleanup(tmp_path,monkeypatch,rig): + import os + sys.path.insert(0,str(CANDIDATE/'scripts/colab_remote')) + spec=importlib.util.spec_from_file_location('review_worker',CANDIDATE/'scripts/colab_session_worker.py') + worker=importlib.util.module_from_spec(spec);spec.loader.exec_module(worker) + monkeypatch.setattr(worker,'comfy_identity',lambda *a,**kw:{'verified':True}) + source=tmp_path/'source.mp4';source.write_bytes(b'offline media mock') + bundle={'inputs':[{'slot':'video','name':'input/1.mp4','kind':'video','local_path':str(source)}], + 'models':[],'bundle_sha256':'a'*64,'output_contract':{'kind':'video'}} + monkeypatch.setattr(worker,'compile_request',lambda *a,**kw:{'json':{'prompt':{}}}) + root=tmp_path/'job';root.mkdir() + session=tmp_path/'session';session.mkdir();cache=session/'cache';cache.mkdir() + # Sentinel left by an earlier voice operation; never read private voice data. + private_marker=cache/'voice-export.json';private_marker.write_text('{}') + manifest={'jobs':[{'bundle':bundle}], 'input_files':[{'path':i['name']} for i in bundle['inputs']], 'job_id':uid(),'deadline_epoch':10**12} + (root/'manifest.json').write_text(json.dumps(manifest)) + for item in bundle['inputs']: + dest=root/item['name'];dest.parent.mkdir(parents=True,exist_ok=True) + dest.write_bytes(Path(item['local_path']).read_bytes()) + monkeypatch.setattr(worker,'validate_native_manifest',lambda m,r:m) + monkeypatch.setattr(worker,'prepared',lambda b,s:(cache/'ComfyUI','mock-python')) + monkeypatch.setattr(worker,'dependency_probe',lambda *a:{'ready':True}) + monkeypatch.setattr(worker,'output_check',lambda *a:None) + monkeypatch.setattr(worker.subprocess,'check_output',lambda *a,**k:'NVIDIA A100, 40536') + RealPath=Path + monkeypatch.setattr(worker,'Path',lambda p:tmp_path/'alias' if str(p)=='/content/castle-parity-input' else RealPath(p)) + terminated=tmp_path/'child-terminated' + class Process: + def poll(self):return None + def terminate(self):terminated.touch() + def wait(self,**kw):return 0 + monkeypatch.setattr(worker.subprocess,'Popen',lambda *a,**kw:Process()) + def request(method,path,body=None): + if path=='/object_info':return {} + if path=='/prompt': + out=root/'comfy-output';out.mkdir() + src=next(i for i in bundle['inputs'] if i['kind']=='video') + (out/'result.mp4').write_bytes(Path(src['local_path']).read_bytes()) + return {'prompt_id':'accepted'} + return {'accepted':{'status':{'completed':True},'outputs':{'1':{'videos':[{'type':'output','filename':'result.mp4'}]}}}} + monkeypatch.setattr(worker,'local_request',request) + real_atomic=worker.atomic + def kill_after_completed(path,value): + real_atomic(path,value) + if path==root/'status.json' and value.get('phase')=='completed': + os._exit(0) # Same cleanup semantics as SIGKILL at this exact boundary. + monkeypatch.setattr(worker,'atomic',kill_after_completed) + pid=os.fork() + if pid==0: + try: worker.run_native(root,worker.file_hash(root/'manifest.json'),session) + except BaseException: os._exit(2) + os._exit(3) + _,status=os.waitpid(pid,0) + assert os.waitstatus_to_exitcode(status)==0 + assert json.loads((root/'status.json').read_text())['phase']=='completed' + assert (root/'artifacts.json').exists() + assert private_marker.exists() and not terminated.exists() + assert (tmp_path/'alias').exists() + assert not (root/'reusable-clean.json').exists() + # Drive the real controller from the killed worker's exact persisted records. + s,b,clock,account,state=rig;state=allocated(rig) + j=job(rig,state['id'],'running',id=manifest['job_id'],runtime_id=state['runtime_id'], + manifest_sha256=json.loads((root/'status.json').read_text())['manifest_sha256']) + s.sessions.save(state['id'],active_job=j['id']) + calls=[] + def remote(state,code): + calls.append(code) + if "'status':read('status.json')" in code: + return {'status':json.loads((root/'status.json').read_text()), + 'artifacts':json.loads((root/'artifacts.json').read_text()),'worker_dead':True} + if 'reusable-clean.json' in code: + import io,contextlib + output=io.StringIO() + with contextlib.redirect_stdout(output): + exec(code.replace('/content/web-comfyui/'+j['id'],str(root)),{}) + return json.loads(output.getvalue().split('WEB_COMFYUI_JSON=')[1]) + raise AssertionError('Unexpected remote operation') + monkeypatch.setattr(s,'_exec',remote);monkeypatch.setattr(s,'_download',lambda *a:[]) + s.tick(j) + assert s.sessions.get(state['id'])['phase']=='closed' + assert not s.job('owner',j['id']).get('session_runtime_retained') + assert any('reusable-clean.json' in c for c in calls) + +def test_retry_rounds_and_lane_cap_survive_restarts(rig,monkeypatch): + s,b,clock,account,state=rig + original=s._call + def unavailable(state,op,**kw): + if op=='runtime_allocate': + b.calls.append((op,kw));raise BridgeError('allocation_unavailable') + return original(state,op,**kw) + for index in range(12): + s=ColabService(s.root,b,s.clock) + monkeypatch.setattr(s,'_call',unavailable) + for _ in range(3):s.sessions.tick_all() + assert s.sessions.get(state['id'])['attempts']==index+1 + clock[0]+=599;s.sessions.tick_all() + assert len([1 for op,_ in b.calls if op=='runtime_allocate'])==3*(index+1) + clock[0]+=1 + s.sessions.tick_all();s.sessions.tick_all() + assert s.sessions.get(state['id'])['reason']=='attempt_cap' + # Synthetic durable records represent another owner's lane usage. + with s.db() as db: + for _ in range(12): db.execute('INSERT INTO session_attempts VALUES (?,?,?)',(uid(),'other-owner-session',clock[0]-601)) + next_session=s.sessions.open('owner',account,15) + s=ColabService(s.root,b,s.clock);s.sessions.tick_all();s.sessions.tick_all() + assert s.sessions.get(next_session['id'])['reason']=='rolling_24h_cap' + assert len([1 for op,_ in b.calls if op=='runtime_allocate'])==36 + +@pytest.mark.parametrize('phase',['arming','uploading','bootstrap_launch','bootstrap','ready','closing']) +def test_restart_stale_runtime_states_release_without_reallocation(rig,phase): + s,b,clock,account,state=rig + allocated(rig,phase) + clock[0]+=301 + s=ColabService(s.root,b,s.clock);s.sessions.tick_all() + assert s.sessions.get(state['id'])['released'] + assert len([1 for op,_ in b.calls if op=='runtime_allocate'])==1 + +@pytest.mark.parametrize('phase',['arming','uploading','bootstrap_launch','bootstrap']) +def test_close_during_bootstrap_releases(rig,phase): + s,b,clock,account,state=rig + allocated(rig,phase) + s.sessions.close('owner');s.sessions.tick_all() + assert s.sessions.get(state['id'])['released'] + +def test_meter_transaction_rolls_back_both_rows_on_crash(rig,monkeypatch): + from contextlib import contextmanager + s,b,clock,account,state=rig + state=allocated(rig) + j=job(rig,state['id'],'running',runtime_id=state['runtime_id']) + state=s.sessions.save(state['id'],active_job=j['id']) + real_db=s.db + class DB: + def __init__(self,db):self.db=db + def execute(self,sql,args=()): + if sql.startswith('UPDATE work_sessions SET state='): raise Crash() + return self.db.execute(sql,args) + @contextmanager + def crash_db(): + with real_db() as db:yield DB(db) + b.balance-=2 + with monkeypatch.context() as m: + m.setattr(s,'db',crash_db) + with pytest.raises(Crash):s.sessions.observe(state) + assert s.job('owner',j['id'])['units_observed']==0 + assert s.sessions.get(state['id'])['units_observed']==0 + s.sessions.observe(s.sessions.get(state['id'])) + assert s.job('owner',j['id'])['units_observed']==2 + assert s.sessions.get(state['id'])['job_units']==2 + +def test_session_cu_cap_and_other_owner_controls(rig): + s,b,clock,account,state=rig + allocated(rig) + assert s.sessions.snapshot('other-owner')['session_ledger']==[] + s.sessions.close('other-owner') + assert not s.sessions.get(state['id']).get('close_requested') + b.balance-=120;clock[0]+=60 + s=ColabService(s.root,b,s.clock);s.sessions.tick_all() + assert s.sessions.get(state['id'])['released'] + assert s.sessions.get(state['id'])['reason']=='cu_cap' + +@pytest.mark.parametrize('raw,accepted',[ + ('NVIDIA L4, 24000',False),('Tesla T4, 16000',False), + ('NVIDIA L4, 48000',False),('NVIDIA A100, 20000',False), + ('NVIDIA A100, 40536',True),('NVIDIA H100, 81559',True), + ('NVIDIA RTX PRO 6000 Blackwell, 97887',True)]) +def test_gpu_runtime_controls(raw,accepted): + p=CANDIDATE/'scripts/colab_session_worker.py' + tree=ast.parse(p.read_text()) + fn=next(n for n in tree.body if isinstance(n,ast.FunctionDef) and n.name=='verify_gpu') + scope={};exec(compile(ast.Module(body=[fn],type_ignores=[]),str(p),'exec'),scope) + if accepted: assert scope['verify_gpu'](raw)[1]>=39000 + else: + with pytest.raises(RuntimeError):scope['verify_gpu'](raw) + diff --git a/scripts/test_review2_safety_r35.py b/scripts/test_review2_safety_r35.py new file mode 100644 index 0000000..990c03f --- /dev/null +++ b/scripts/test_review2_safety_r35.py @@ -0,0 +1,140 @@ +"""N1-N3 controls: disk SQLite, synthetic leases, no provider or GPU work.""" +import json +import signal +import sqlite3 +import time +from contextlib import contextmanager +import pytest +from test_review2_original_r35 import rig, allocated, job, uid, encoded, BridgeError +from scripts import colab_lease_sweeper as sweeper + + +def leases(rig, count, assigned=False): + s,b,clock,account,first=rig + result=[] + for n in range(count): + state=first if n==0 else s.sessions.new_state('owner'+str(n),uid(),str(n)*64,first['settings']) + if n: + with s.db() as db:db.execute('INSERT INTO work_sessions VALUES (?,?,?)',(state['id'],state['owner'],encoded(state))) + result.append(s.sessions.save(state['id'],phase='uncertain',allocation_id=uid(),allocation_at=clock[0],gpu='A100',deadline_epoch=clock[0]+21600,last_balance=1000, + **({'runtime_id':uid()} if assigned else {}))) + return result + + +@pytest.mark.parametrize('count',[1,5,17]) +@pytest.mark.parametrize('assigned',[False,True]) +def test_n_lease_fairness_across_process_activations(rig,monkeypatch,count,assigned): + s,b,clock,account,state=rig + states=leases(rig,count,assigned) + attempted=[] + def fail(self,only=None): + # Independent DB read proves the cursor commits before the attempt. + with self.s.db() as db: + assert db.execute('SELECT last_id FROM session_sweep_cursor WHERE kind=?',('assigned' if assigned else 'lookup',)).fetchone()[0]==only + attempted.append(only) + raise sweeper.LeaseBudgetExpired() + monkeypatch.setattr(type(s.sessions),'sweep_leases',fail) + for _ in range((count+sweeper.MAX_ATTEMPTS-1)//sweeper.MAX_ATTEMPTS): + with pytest.raises(RuntimeError):sweeper.sweep(s.root,b,s.clock) + assert set(attempted)=={row['id'] for row in states} + assert len(set(attempted[:count]))==count + + +def test_assigned_priority_and_lookup_progress(rig,monkeypatch): + s,b,clock,account,state=rig + states=leases(rig,13) + paid={row['id'] for row in states[:8]} + for row in states[:8]:s.sessions.save(row['id'],runtime_id=uid()) + activations=[] + def fail(self,only=None): + activations[-1].append(only) + raise BridgeError('timeout') + monkeypatch.setattr(type(s.sessions),'sweep_leases',fail) + for _ in range(8): + activations.append([]) + with pytest.raises(RuntimeError):sweeper.sweep(s.root,b,s.clock) + for activation in activations: + assert len(activation)==2 + assert all(sid in paid for sid in activation[:1]) + assert all(sid not in paid for sid in activation[1:]) + assert {sid for a in activations for sid in a}=={row['id'] for row in states} + + +def test_cursor_survives_abrupt_activation_death(rig,monkeypatch): + s,b,clock,account,state=rig + states=leases(rig,5);attempted=[] + class Kill(BaseException):pass + def die(self,only=None):attempted.append(only);raise Kill() + monkeypatch.setattr(type(s.sessions),'sweep_leases',die) + for _ in states: + with pytest.raises(Kill):sweeper.sweep(s.root,b,s.clock) + assert len(set(attempted))==len(states) + + +def test_budget_interrupts_blocking_attempt_and_restores_alarm(): + handler=signal.getsignal(signal.SIGALRM) + started=time.monotonic() + with pytest.raises(sweeper.LeaseBudgetExpired): + with sweeper.budget(.02,sweeper.LeaseBudgetExpired()):time.sleep(1) + assert time.monotonic()-started<.5 + assert signal.getsignal(signal.SIGALRM)==handler + assert signal.getitimer(signal.ITIMER_REAL)==(0,0) + assert sweeper.LEASE_BUDGET_SECONDS*sweeper.MAX_ATTEMPTS<=180 + + +def test_stuck_balance_cannot_prevent_stop(rig,monkeypatch): + s,b,clock,account,state=rig + allocated(rig);clock[0]+=301 + monkeypatch.setattr(sweeper,'RPC_BUDGET_SECONDS',.02) + def bridge(op,*args,**kw): + if op=='account_status':time.sleep(1) + return b(op,*args,**kw) + assert sweeper.sweep(s.root,bridge,s.clock) + assert any(op=='runtime_stop' for op,_ in b.calls) + assert s.sessions.get(state['id'])['phase']=='released_unsettled' + + +def test_reads_do_not_require_sqlite_writer(rig): + s,b,clock,account,state=rig + with sqlite3.connect(s.root/'state.sqlite3',timeout=.01) as db: + db.execute('BEGIN IMMEDIATE') + assert s.sessions.settings('owner')['idle_minutes']==20 + assert s.sessions.snapshot('owner')['session']['id']==state['id'] + + +def test_dispatch_committed_before_rpc_and_cancel_job_during_rpc(rig,monkeypatch): + s,b,clock,account,state=rig + j=job(rig,state['id']);s.sessions.save(state['id'],admission_created=True) + original=s._call + def call(st,op,**kw): + if op=='runtime_allocate': + with sqlite3.connect(s.root/'state.sqlite3',timeout=.01) as db: + db.execute('BEGIN IMMEDIATE') + fresh=json.loads(db.execute('SELECT state FROM work_sessions WHERE id=?',(state['id'],)).fetchone()[0]) + assert fresh['allocation_id']==kw['allocation_id'] + assert fresh['deadline_epoch']==clock[0]+21600 + assert fresh['dispatch_intent_at']==clock[0] + cancelled=json.loads(db.execute('SELECT state FROM jobs WHERE id=?',(j['id'],)).fetchone()[0]);cancelled['cancel_requested']=True + db.execute('UPDATE jobs SET state=? WHERE id=?',(encoded(cancelled),j['id'])) + return original(st,op,**kw) + monkeypatch.setattr(s,'_call',call) + s.sessions.tick_all() + assert s.sessions.get(state['id'])['released'] + assert s.job('owner',j['id'])['phase']=='cancelled' + assert not any(op in {'upload','remote_exec'} for op,_ in b.calls) + + +def test_lost_dispatch_response_preserves_close_and_settings(rig,monkeypatch): + s,b,clock,account,state=rig;original=s._call + def call(st,op,**kw): + if op=='runtime_allocate': + s.sessions.close('owner');s.sessions.settings('owner',{'max_units':77}) + b.found=True + raise BridgeError('timeout',True) + return original(st,op,**kw) + monkeypatch.setattr(s,'_call',call) + s.sessions.tick_all() + final=s.sessions.get(state['id']) + assert final['released'] and final['close_requested'] + assert final['settings']['max_units']==77 + assert not any(op in {'upload','remote_exec'} for op,_ in b.calls) diff --git a/scripts/test_review3_boundaries_r35.py b/scripts/test_review3_boundaries_r35.py new file mode 100644 index 0000000..bad772c --- /dev/null +++ b/scripts/test_review3_boundaries_r35.py @@ -0,0 +1,174 @@ +"""Independent STAGED4 crash, fairness and deployment-helper boundary probes.""" +import json +import runpy +import signal +import sys +from pathlib import Path +from types import ModuleType + +import pytest +from test_review2_original_r35 import CANDIDATE, ColabService, rig, uid, Crash, encoded, BridgeError +from scripts import colab_lease_sweeper as sw + + +def activate(s, bridge): + try:sw.sweep(s.root,bridge,s.clock) + except RuntimeError as e:assert str(e)=='Lease cleanup pending; retry on next timer' + + +@pytest.mark.parametrize('n',[1,5,17]) +@pytest.mark.parametrize('priority',['none','unarmed','overdue']) +def test_fair_attempts_with_real_rpc_timeouts(rig,monkeypatch,n,priority): + s,b,clock,account,state=rig + monkeypatch.setattr(sw,'RPC_BUDGET_SECONDS',0.005) + # Allow synchronous disk commits for the new legacy grace record; the + # actual provider timeout probe still uses a real 5ms SIGALRM. + monkeypatch.setattr(sw,'LEASE_BUDGET_SECONDS',2) + ids=[] + for i in range(n): + st=state if i==0 else s.sessions.new_state('other'+str(i),account,'a'*64,state['settings']) + if i: + with s.db() as db:db.execute('INSERT INTO work_sessions VALUES (?,?,?)',(st['id'],st['owner'],encoded(st))) + aid=uid();ids.append(aid) + s.sessions.save(st['id'],phase='uncertain',allocation_id=aid,allocation_at=clock[0],gpu='A100', + deadline_epoch=clock[0]+21600,last_balance=1000) + if priority!='none': + st=s.sessions.new_state('priority',account,'a'*64,state['settings']) + with s.db() as db:db.execute('INSERT INTO work_sessions VALUES (?,?,?)',(st['id'],st['owner'],encoded(st))) + s.sessions.save(st['id'],phase='ready',runtime_id='priority-runtime',gpu='A100',last_balance=1000, + watchdog_armed=priority=='overdue',deadline_epoch=clock[0]-1 if priority=='overdue' else clock[0]+21600) + calls=[];activation=[0];first={} + def bridge(op,account_dir,**kw): + calls.append((activation[0],op,kw)) + if op=='runtime_lookup': + aid=kw['allocation_id'];first.setdefault(aid,activation[0]) + if aid!=ids[-1]:signal.pause() # real SIGALRM, no real provider + return {'found':True,'runtime_id':aid,'accelerator':'A100'} + return b(op,account_dir,**kw) + for a in range(1,n+1): + activation[0]=a;activate(s,bridge) + assert set(first)==set(ids) and max(first.values())<=n + assert any(op=='runtime_stop' and kw['runtime_id']==ids[-1] for _,op,kw in calls) + if priority!='none': + stop=next(i for i,(_,op,kw) in enumerate(calls) if op=='runtime_stop' and kw['runtime_id']=='priority-runtime') + lookup=next(i for i,(_,op,_) in enumerate(calls) if op=='runtime_lookup') + assert stop=39000 + else: + with pytest.raises(RuntimeError):scope['verify_gpu'](raw) + diff --git a/scripts/test_review_r36c.py b/scripts/test_review_r36c.py new file mode 100644 index 0000000..8a36d07 --- /dev/null +++ b/scripts/test_review_r36c.py @@ -0,0 +1,42 @@ +import json,pytest +from scripts.review_r36_support import CANDIDATE,rig,allocated,job + +@pytest.mark.parametrize('historical',[False,True]) +def test_colab_job_list_still_reports_requested_gpu_as_assignment(rig,historical): + """Regression: both owner-scoped projections agree, including historical rows.""" + from compute_parity.colab import ColabNative + from compute_parity.journal import Journal + s,b,clock,account,initial=rig;st=allocated(rig,'bootstrap') + s.sessions.save(st['id'],gpu='G4',assigned_gpu='G4',gpu_name=None, + phase='closed' if historical else 'bootstrap',released=historical) + j=job(rig,st['id'],'failed' if historical else 'queued',requested_gpu='A100',released=historical) + public=s.snapshot('owner')['jobs'][0] + assert public['gpu']=='G4' and public['assigned_gpu']=='G4' and public['requested_gpu']=='A100' + journal=Journal(s.root.parent/'compute-parity/journal.sqlite3') + journal.reserve('owner',j['id'],'colab',account,'dance.anime.chatgpt','offline',{'unit':'CU','amount':15}) + receipt=ColabNative(s,journal).poll('owner',j['id']) + assert receipt['assigned_gpu']=='G4' and receipt['gpu']=='G4' and receipt['gpu_name'] is None + assert s.snapshot('owner')['jobs'][0]['gpu']=='G4' # Poll did not repair this view. + ui=(CANDIDATE/'webui/static/colab.js').read_text() + assert '`${job.gpu} · ${new Date(job.created_at' not in ui + assert '指定 GPU:' in ui and '實際 GPU:' in ui + + +@pytest.mark.parametrize('tail,expected',[ + ('AKIASYNTHETICKEYError: [redacted]',''), + ('Exception: [redacted]','Exception: [redacted]'), + ('TimeoutExpired: [redacted]','TimeoutExpired: [redacted]'), +]) +def test_local_tail_filter_disagrees_with_remote_grammar(rig,monkeypatch,tail,expected): + """Regression: one exact error vocabulary governs both redactors.""" + s,b,clock,account,initial=rig;st=allocated(rig,'bootstrap') + def remote(st,code): + if 'bootstrap-status.json' in code:return {'phase':'failed'} + if 'bootstrap-stderr.log' in code:return {'tail':tail} + raise AssertionError('unexpected remote operation') + monkeypatch.setattr(s,'_exec',remote) + s.sessions.bootstrap(s.sessions.get(st['id'])) + path=s.root/'sessions'/st['id']/'bootstrap.stderr.txt' + assert path.read_text()==expected + assert path.stat().st_mode&0o777==0o600 + assert tail not in json.dumps(s.sessions.snapshot('owner')) diff --git a/scripts/test_review_r37.py b/scripts/test_review_r37.py new file mode 100644 index 0000000..ddf0d47 --- /dev/null +++ b/scripts/test_review_r37.py @@ -0,0 +1,182 @@ +import base64,json,os,threading,uuid,sqlite3,multiprocessing +from pathlib import Path +import pytest +from review_r37_fixture import rig,reserve,submit,inputs,session +from colab_service import BridgeError,ColabError,encoded +from compute_parity.runtime import Runtime +from compute_parity.contracts import ParityError +from compute_routing import ComputeRouter,ComputeAdapter + + +def router(r,submitter): + a=ComputeAdapter(lambda *a,**k:{'eligible':True,'estimated_cost':15,'currency':'compute_units','reasons':[]},submitter,lambda owner,rid:Runtime.receipt(r.a.poll(owner,rid)),lambda owner,rid:Runtime.receipt(r.a.cancel(owner,rid))) + return ComputeRouter(r.root/'routing.sqlite3',{'colab':a},clock=r.s.clock) + + +def test_exact_live_shape_owner_get_close_capacity_and_fresh_id(rig): + r=rig;rid=reserve(r,'00000000-0000-4000-8000-00000000d002');calls=[] + def dispatch(owner,rid,request,limits):calls.append(rid);return Runtime.receipt(submit(r,rid)) + rt=router(r,dispatch) + receipt={'state':'submission_uncertain','downstream_id':rid,'cancel_supported':True,'retry_submission_allowed':False} + with rt._db() as db:db.execute('INSERT INTO compute_requests VALUES(?,?,?,?,?,?,?,?,?,?,?)',(r.owner,rid,'hash','colab','colab','submission_uncertain','{}','{}',json.dumps(receipt),r.t[0],r.t[0])) + before=r.j.get(r.owner,rid) + with pytest.raises(Exception):rt.status('other-owner',rid,refresh=True) + assert r.j.get(r.owner,rid)==before + assert r.s.find_job(r.owner,rid) is None and not (r.s.root/'jobs'/rid).exists() + got=rt.status(r.owner,rid,refresh=True);assert got['state']=='closed_no_execution_evidence' and got['actual_cost']['amount']==0 + assert got['cancel_supported'] is False and got['retry_submission_allowed'] is False + assert r.j.ledger(r.owner)['colab']['unsettled_reserved']==0 + preview=rt.preview(r.owner,{},placement='colab') + assert next(x for x in preview['candidates'] if x['lane']=='colab')['active_requests']==0 + with rt._db() as db:assert db.execute("SELECT count(*) FROM compute_requests WHERE state='submission_uncertain'").fetchone()[0]==0 + for operation in [r.a.poll,r.a.recover,r.a.cancel]:assert operation(r.owner,rid)['state']=='closed_no_execution_evidence' + # Journal identity remains durable: even an adapter replay cannot re-dispatch. + with pytest.raises(ParityError):submit(r,rid) + assert r.s.find_job(r.owner,rid) is None + new=submit(r);assert new['state']=='running' and r.s.find_job(r.owner,new['request_id']) + assert not any(op=='runtime_allocate' for op,_ in r.b.calls) + + +@pytest.mark.parametrize('point',['before_insert','after_commit','lookup_error']) +def test_submit_exception_boundary(rig,monkeypatch,point): + r=rig;rid=str(uuid.uuid4()) + if point in {'before_insert','lookup_error'}: + def fail(*a,**k):raise BridgeError('timeout') + monkeypatch.setattr(r.s,'_submit',fail) + else: + def fail():raise OSError('not exposed') + monkeypatch.setattr(r.s,'start',fail) + if point=='lookup_error': + def fail_lookup(*a):raise sqlite3.OperationalError('not exposed') + monkeypatch.setattr(r.s,'find_job',fail_lookup) + result=submit(r,rid) + if point=='before_insert':assert result['state']=='rejected' and result['actual_cost']['amount']==0 and not r.s.sessions.rows() + elif point=='after_commit':assert result['state']=='running' and len(r.s.sessions.rows())==1 + else:assert result['state']=='submission_uncertain' and 'actual_cost' not in result + assert result.get('diagnostics') and not any(op=='runtime_allocate' for op,_ in r.b.calls) + + +@pytest.mark.parametrize('kind',['request','account']) +def test_other_process_lock_prevents_absence_closure(rig,kind): + r=rig;rid=reserve(r);ctx=multiprocessing.get_context('fork');ready=ctx.Event();finish=ctx.Event() + def holder(): + with (r.s.native_submission_guard(r.owner,rid) if kind=='request' else r.s.account_guard(r.account)): + ready.set();assert finish.wait(15) + p=ctx.Process(target=holder);p.start() + try: + assert ready.wait(5);assert r.a.poll(r.owner,rid)['state']=='submission_uncertain' + finally:finish.set();p.join(5) + assert p.exitcode==0;assert r.a.poll(r.owner,rid)['state']=='closed_no_execution_evidence' + + +def test_two_concurrent_native_submits_and_get_cannot_close_inflight(rig,monkeypatch): + r=rig;rid=str(uuid.uuid4());entered=threading.Event();done=threading.Event();actual=r.s._submit;results=[] + def delayed(*a,**kw):entered.set();assert done.wait(10);return actual(*a,**kw) + monkeypatch.setattr(r.s,'_submit',delayed) + def work():results.append(submit(r,rid)) + t=threading.Thread(target=work);t.start() + try: + assert entered.wait(5) + assert r.a.poll(r.owner,rid)['state']=='submission_uncertain' + with pytest.raises(BlockingIOError):submit(r,rid) + finally:done.set();t.join(10) + assert len(results)==1 and results[0]['state']=='running' + assert len(r.s.sessions.rows())==1 + + +def test_lane_failure_counting(rig): + r=rig + for _ in range(2): + rid=reserve(r);r.j.update(r.owner,rid,state='rejected',failure_kind='admission',root_cause='invalid_input',actual_cost={'unit':'CU','amount':0}) + r.j.check_admission(r.owner,'colab','video-replace.realistic.example-b') + for case in ['dance.anime.chatgpt','video-replace.anime.chatgpt']: + rid=str(uuid.uuid4());r.j.reserve(r.owner,rid,'colab',r.account,case,'id',{'unit':'CU','amount':15});r.j.update(r.owner,rid,state='failed',failure_kind='execution',root_cause='native_runtime_failed') + with pytest.raises(ParityError) as error:r.j.check_admission(r.owner,'colab','video-replace.realistic.example-b') + assert error.value.code=='lane_stopped' + + + + +@pytest.mark.parametrize('outcome',['closed_no_execution_evidence','rejected']) +def test_confirm_closed_id_can_start_paid_work_through_existing_colab_endpoint(rig,monkeypatch,outcome): + r=rig + if outcome=='closed_no_execution_evidence': + rid=reserve(r);assert r.a.poll(r.owner,rid)['state']==outcome + else: + rid=str(uuid.uuid4());original=r.s._submit + def bad_input(*a,**kw):raise ColabError('不支援的參考檔案格式') + monkeypatch.setattr(r.s,'_submit',bad_input);assert submit(r,rid)['state']==outcome + monkeypatch.setattr(r.s,'_submit',original) + body={'request_id':rid,'account_id':r.account,'gpu':'A100','max_units':20,'max_minutes':60,'job':{'type':'image','prompt':'offline probe'},'files':[]} + # Same service method used by POST /api/colab/jobs, no validation bypass. + with pytest.raises(ColabError):r.s.submit(r.owner,body) + assert r.s.find_job(r.owner,rid) is None + assert not any(op=='runtime_allocate' for op,_ in r.b.calls) + assert r.a.poll(r.owner,rid)['state']==outcome + assert r.j.get(r.owner,rid)['actual_cost']['amount']==0 + + +def test_fresh_generic_uuid_still_admitted(rig): + r=rig;rid=str(uuid.uuid4()) + body={'request_id':rid,'account_id':r.account,'gpu':'A100','max_units':20,'max_minutes':60,'job':{'type':'image','prompt':'offline probe'},'files':[]} + assert r.s.submit(r.owner,body)['phase']=='queued' + r.s.tick(r.s.job(r.owner,rid));assert any(op=='runtime_allocate' for op,_ in r.b.calls) + + +def test_atomic_tombstone_receipt_roll_back_together(rig,monkeypatch): + r=rig;rid=reserve(r) + original=r.j.update_in_transaction + def fail(db,*a,**kw): + original(db,*a,**kw) + raise OSError('injected crash before commit') + monkeypatch.setattr(r.j,'update_in_transaction',fail) + with pytest.raises(OSError):r.s.close_admission(r.j,r.owner,rid,state='closed_no_execution_evidence',actual_cost={'unit':'CU','amount':0}) + assert r.j.get(r.owner,rid)['state']=='submission_uncertain' + assert r.j.ledger(r.owner)['colab']['unsettled_reserved']==15 + with r.s.db() as db:assert db.execute('SELECT 1 FROM request_claims WHERE id=?',(rid,)).fetchone() is None + + +@pytest.mark.parametrize('foreign',[False,True]) +def test_sql_trigger_cannot_bypass_terminal_or_owner_claim(rig,foreign): + r=rig;rid=reserve(r) + if foreign: + with r.s.db() as db:db.execute("INSERT INTO request_claims(id,owner,state) VALUES(?,?,'pending')",(rid,'other-owner')) + else:assert r.a.poll(r.owner,rid)['state']=='closed_no_execution_evidence' + with pytest.raises(sqlite3.IntegrityError): + with r.s.db() as db:db.execute('INSERT INTO jobs VALUES(?,?,?,?,?)',(rid,r.owner,r.account,'hash',json.dumps({'phase':'queued'}))) + assert r.s.find_job(r.owner,rid) is None + + +def test_initial_arm_finishes_before_upload_and_fault_does_not_renew_tick(rig): + r=rig;st=session(r,'arming');sid=st['id'];last=st['last_tick'];r.t[0]+=30 + def hook(op,kw): + if op=='upload':raise BridgeError('transport_failed') + r.b.hook=hook;r.s.sessions.tick_all();armed=r.s.sessions.get(sid) + assert armed['last_tick']>last and not any(op=='upload' for op,_ in r.b.calls) + r.t[0]+=30;r.s.sessions.tick_all();state=r.s.sessions.get(sid) + assert state['fault']['stage']=='upload' and state['last_tick']==armed['last_tick'] + assert state['fault_streak']==1 and state['phase']=='uploading' + + + + +def test_nonatomic_journal_mode_retains_uncertain_reservation(rig): + r=rig;rid=reserve(r) + with sqlite3.connect(r.j.path) as db:assert db.execute('PRAGMA journal_mode=WAL').fetchone()[0]=='wal' + got=r.a.poll(r.owner,rid) + assert got['state']=='submission_uncertain' and 'actual_cost' not in got + assert got['diagnostics']['error_code']=='admission_lookup_failed' + with r.s.db() as db:assert db.execute('SELECT 1 FROM request_claims WHERE id=?',(rid,)).fetchone() is None + + +def test_legacy_job_without_claim_cannot_be_claimed_by_another_owner(rig): + r=rig;rid=str(uuid.uuid4()) + with r.s.db() as db: + db.execute('INSERT INTO jobs VALUES(?,?,?,?,?)',(rid,r.owner,r.account,'hash',json.dumps({'id':rid,'phase':'queued'}))) + db.execute('DELETE FROM request_claims WHERE id=?',(rid,)) # legacy fixture only + with pytest.raises(ColabError):r.s.claim_request('other-owner',rid) + with r.s.db() as db:assert db.execute('SELECT 1 FROM request_claims WHERE id=?',(rid,)).fetchone() is None + r.s.claim_request(r.owner,rid) + with r.s.db() as db: + claim=db.execute('SELECT owner,state FROM request_claims WHERE id=?',(rid,)).fetchone() + assert tuple(claim)==(r.owner,'admitted') diff --git a/scripts/test_review_r38_caps.py b/scripts/test_review_r38_caps.py new file mode 100644 index 0000000..56fdc54 --- /dev/null +++ b/scripts/test_review_r38_caps.py @@ -0,0 +1,56 @@ +import json,sys,time,subprocess,uuid +from pathlib import Path +import pytest +from review_r38_fixture import rig, session +from colab_service import BridgeError +from scripts.colab_session_watchdog import WORKER +from test_review_r38_faults import probe_kind + +@pytest.mark.parametrize('cap',['hard','cu','idle','stale']) +def test_caps_still_release_after_one_tolerated_fault(rig,cap): + r=rig;st=session(r);sid=st['id'] + def fail(op,kw): + if probe_kind(op,kw)=='heartbeat':raise BridgeError('execution_uncertain',True) + r.b.hook=fail;r.s.sessions.tick_all();r.b.hook=None + assert r.s.sessions.get(sid)['fault_streak']==1 + if cap=='hard':r.s.sessions.save(sid,deadline_epoch=r.t[0]) + elif cap=='cu':r.s.sessions.save(sid,units_observed=120) + elif cap=='idle':r.s.sessions.save(sid,idle_since=r.t[0]-1200) + else:r.s.sessions.save(sid,last_tick=r.t[0]-301) + r.s.sessions.tick_all() + assert r.s.sessions.get(sid)['released'] + assert sum(op=='runtime_stop' for op,_ in r.b.calls)==1 + +@pytest.mark.parametrize('expired',['hard','stale','unarmed','closing']) +def test_sweeper_cannot_exec_upload_or_allocate(rig,expired): + r=rig;st=session(r);sid=st['id'] + if expired=='hard':r.s.sessions.save(sid,deadline_epoch=r.t[0]) + elif expired=='stale':r.s.sessions.save(sid,last_tick=r.t[0]-301) + elif expired=='unarmed':r.s.sessions.save(sid,watchdog_armed=False) + else:r.s.sessions.save(sid,phase='closing') + r.b.calls.clear();r.s.sessions.sweep_leases() + assert r.s.sessions.get(sid)['released'] + assert all(op in {'account_status','runtime_stop','runtime_lookup'} for op,_ in r.b.calls) + assert sum(op=='runtime_stop' for op,_ in r.b.calls)==1 + +@pytest.mark.parametrize('limit',['heartbeat','hard','close']) +def test_actual_remote_watchdog_requests_release(tmp_path,monkeypatch,limit): + p=tmp_path/'remote';p.mkdir();clock=[1000.0];release=[] + (p/'heartbeat').write_text('1000') + if limit=='close':(p/'close').touch() + deadline=1020 if limit=='hard' else 10000 + class StopProbe(Exception):pass + def run(args,**kwargs): + assert args[2]=='from google.colab import runtime; runtime.unassign()' + release.append(clock[0]);raise StopProbe() + monkeypatch.setattr(subprocess,'run',run) + monkeypatch.setattr(sys,'argv',['offline-watchdog',str(p),str(deadline)]) + monkeypatch.setattr(time,'time',lambda:clock[0]) + monkeypatch.setattr(time,'sleep',lambda seconds:clock.__setitem__(0,clock[0]+seconds)) + namespace={} + try: + with pytest.raises(StopProbe):exec(compile(WORKER,'offline-watchdog','exec'),namespace) + assert release==[{'heartbeat':1300,'hard':1020,'close':1000}[limit]] + finally: + import os + if 'fd' in namespace:os.close(namespace['fd']) diff --git a/scripts/test_review_r38_diagnostics.py b/scripts/test_review_r38_diagnostics.py new file mode 100644 index 0000000..4f6ae21 --- /dev/null +++ b/scripts/test_review_r38_diagnostics.py @@ -0,0 +1,143 @@ +import contextlib,fcntl,json,os,subprocess,uuid +from pathlib import Path +from types import SimpleNamespace as NS +import pytest +from review_r38_fixture import rig, session,submit +from colab_service import BridgeError,Bridge +from scripts import colab_transport_diagnostics as td +from scripts import colab_bridge as cb +from scripts.colab_session_watchdog import heartbeat +from test_review_r38_faults import probe_kind,running + +SECRET='PRIVATE_SENTINEL_秘密' +TEXT='https://user:'+SECRET+'@example.invalid/x?token='+SECRET+' /home/private/'+SECRET+' owner@example.invalid Authorization: Bearer '+SECRET + +@pytest.mark.parametrize('name',['ReadTimeout','ConnectTimeout','HTTPStatusError','SDK秘密Error','ConnectionResetError']) +@pytest.mark.parametrize('where',['transport','execute','stop']) +def test_actual_bridge_metadata_never_uses_exception_text(rig,name,where,capsys): + r=rig;error=type(name,(Exception,),{})(TEXT);error.response=NS(status_code=503,headers={'Authorization':TEXT});error.__cause__=ValueError(TEXT) + bridge=cb.Bridge.__new__(cb.Bridge) + bridge.runtime=lambda rid:{'url':'https://example.invalid','token':'synthetic-token'} + class Runtime: + def __init__(self,*a,**kw):pass + def execute_code(self,*a,**kw): + if where=='execute':raise error + return [] + def stop(self,**kw): + if where=='stop':raise error + @contextlib.contextmanager + def transport(): + if where=='transport':raise error + yield + bridge.sdk=NS(Runtime=Runtime,execution_transport=transport) + with pytest.raises(cb.BridgeError) as caught:bridge.remote_exec({'runtime_id':str(uuid.uuid4()),'code':'pass','timeout_seconds':45}) + public=caught.value.public();assert SECRET not in json.dumps(public) and TEXT not in json.dumps(public) + assert public['diagnostics']['error_type']==(name if name in td.CLASSES else 'Exception') + assert public['diagnostics']['http_status']==503 + st=session(r);got=submit(r);rid=got['request_id'] + def fail(op,kw): + if probe_kind(op,kw)=='heartbeat':raise BridgeError(public['code'],public['ambiguous'],{**public['diagnostics'],'url':TEXT,'headers':{'Authorization':TEXT}}) + r.b.hook=fail + for _ in range(2):r.t[0]+=10;r.s.sessions.tick_all() + r.b.hook=None;r.s.sessions.tick_all() + receipt=r.a.poll(r.owner,rid);snapshot=r.s.sessions.snapshot(r.owner) + assert receipt['state']=='failed' and receipt['diagnostics']['stage']=='session_fault' + assert receipt['diagnostics']['error_type']==public['diagnostics']['error_type'] + assert SECRET not in json.dumps([receipt,snapshot],ensure_ascii=False) + assert not r.s.sessions.snapshot('foreign')['session'].get('fault') + captured=capsys.readouterr();assert SECRET not in captured.out+captured.err + +def test_transport_sanitize_rejects_adversarial_values(): + value={k:TEXT for k in ['error_type','transport_phase','timeout_kind','http_status','url','headers']} + assert td.sanitize(value)=={} + assert td.sanitize({'http_status':True})=={} + assert td.capture(type('秘密'+SECRET,(Exception,),{})(TEXT))=={'error_type':'Exception','transport_phase':'wait'} + +@pytest.mark.parametrize('change',['none','pid','start','deadline','inode','unlocked']) +def test_real_generated_heartbeat_verifies_identity_and_lock(tmp_path,change): + sid=str(uuid.uuid4());p=tmp_path/'session';p.mkdir() + f=os.open(p/'watchdog.lock',os.O_CREAT|os.O_RDWR,0o600);fcntl.flock(f,fcntl.LOCK_EX) + identity={'pid':os.getpid(),'start_ticks':Path('/proc/self/stat').read_text().rsplit(')',1)[1].split()[19],'deadline':1000000} + (p/'watchdog.json').write_text(json.dumps(identity));st=os.fstat(f);expected={**identity,'lock_dev':st.st_dev,'lock_ino':st.st_ino} + (p/'heartbeat').write_text('old') + if change=='pid':identity['pid']+=10000000 + elif change=='start':identity['start_ticks']='0' + elif change=='deadline':identity['deadline']+=1 + elif change=='inode':(p/'watchdog.lock').rename(p/'old-lock');(p/'watchdog.lock').touch() + elif change=='unlocked':fcntl.flock(f,fcntl.LOCK_UN) + (p/'watchdog.json').write_text(json.dumps(identity)) + code=heartbeat(sid,expected,1234.0).replace('/content/castle-sessions/'+sid,str(p)) + try: + if change=='none':exec(compile(code,'offline-heartbeat','exec'),{});assert (p/'heartbeat').read_text()=='1234.0' + else: + with pytest.raises((AssertionError,RuntimeError,OSError)):exec(compile(code,'offline-heartbeat','exec'),{}) + assert (p/'heartbeat').read_text()=='old' + finally:os.close(f) + +def test_local_runtime_binding_mismatch_closes_before_exec(rig): + r=rig;st=session(r);r.s.sessions.save(st['id'],watchdog_runtime_id='different-runtime') + r.b.calls.clear();r.s.sessions.tick_all() + assert r.s.sessions.get(st['id'])['phase']=='closing' + assert not any(op=='remote_exec' for op,_ in r.b.calls) + +@pytest.mark.parametrize('faulted',[False,True]) +def test_cancel_and_system_fault_interleaving(rig,faulted): + r=rig;st=session(r);got=submit(r);rid=got['request_id'];sid=st['id'] + if faulted: + def fail(op,kw): + if probe_kind(op,kw)=='heartbeat':raise BridgeError('execution_uncertain',True) + r.b.hook=fail;r.s.sessions.tick_all() + r.s.cancel(r.owner,rid) + if faulted: + r.t[0]+=10;r.s.sessions.tick_all();r.b.hook=None;r.s.sessions.tick_all() + # Confirm defect: explicit queued-job cancellation is overwritten by + # a subsequent system fault rather than preserved alongside diagnostics. + receipt=r.a.poll(r.owner,rid);assert receipt['state']=='cancelled' + assert receipt['diagnostics']['stage']=='session_fault' + assert r.s.job(r.owner,rid)['cancel_requested'] is True + else: + r.s.tick(r.s.job(r.owner,rid));assert r.a.poll(r.owner,rid)['state']=='cancelled' + +def test_archive_upload_timestamps_are_acknowledged_and_ordered(rig): + r=rig;st=session(r,'uploading');sid=st['id'];r.s.sessions.freeze(st);first=r.t[0] + def fail(op,kw): + if op=='upload':raise BridgeError('upload_transport_failed') + r.b.hook=fail;r.s.sessions.tick_all();s=r.s.sessions.get(sid) + assert s['upload_started_at']==first and not s.get('upload_completed_at') and not s.get('digest_verified_at') + r.b.hook=None;r.t[0]+=10;r.s.sessions.tick_all();s=r.s.sessions.get(sid) + assert s['upload_started_at']==first and s['upload_completed_at']==r.t[0] and not s.get('digest_verified_at') + r.t[0]+=10;r.s.sessions.tick_all();s=r.s.sessions.get(sid) + assert s['digest_verified_at']==r.t[0] and s['archive_verified'] + +@pytest.mark.parametrize('active_job',[False,True]) +def test_cancel_before_fault_settles_through_actual_worker_order(rig,active_job): + r=rig + if active_job:st,job=running(r);rid=job['id'] + else:st=session(r,'uploading');rid=submit(r)['request_id'];job=r.s.job(r.owner,rid) + def fail(op,kw): + if probe_kind(op,kw)=='heartbeat':raise BridgeError('execution_uncertain',True) + if probe_kind(op,kw)=='job_probe': + from test_review_r38_faults import running_status + return running_status(job) + r.b.hook=fail;r.s.sessions.tick_all();r.s.tick(job) + r.s.cancel(r.owner,rid);r.t[0]+=10 + r.s.sessions.tick_all();r.s.tick(job) + receipt=r.a.poll(r.owner,rid) + assert receipt['state']=='cancelled' and receipt['diagnostics']['stage']=='session_fault' + assert r.s.sessions.get(st['id'])['released'] + + +def test_system_close_flag_is_not_user_cancel(rig): + r=rig;st=session(r,'uploading');rid=submit(r)['request_id'] + r.s.sessions.save(st['id'],phase='closing',close_requested=True,reason='watchdog_or_hard_cap') + r.s.sessions.tick_all() + assert r.a.poll(r.owner,rid)['state']=='failed' + + +def test_plan_failure_does_not_infer_cancel_from_system_close_flag(rig): + r=rig;st=session(r,'bootstrap');sid=st['id'];rid=submit(r)['request_id'] + st=r.s.sessions.freeze(st);pid=next(iter(st['plan_catalog'])) + r.s.update(rid,bootstrap_plan_id=pid) + st=r.s.sessions.save(sid,bootstrap_plan_id=pid,close_requested=True,reason='watchdog_state_lost') + r.s.sessions.fail_plan(st,{'stage':'session_bootstrap','error_code':'stage_failed'},'bootstrap_failed') + assert r.s.job(r.owner,rid)['phase']=='failed' diff --git a/scripts/test_review_r38_faults.py b/scripts/test_review_r38_faults.py new file mode 100644 index 0000000..65782c5 --- /dev/null +++ b/scripts/test_review_r38_faults.py @@ -0,0 +1,299 @@ +import json,uuid +from pathlib import Path +import pytest +from review_r38_fixture import rig, session,submit +from colab_service import BridgeError + +def running(r): + st=session(r);got=submit(r);job=r.s.job(r.owner,got['request_id']) + assert job['session_id']==st['id'] + r.s.sessions.attach(st,job) + job=r.s.update(job['id'],phase='running',launch_requested_at=r.t[0]) + return st,job + +def probe_kind(op,kw): + if op!='remote_exec':return op + code=kw['code'] + if "'heartbeat':True" in code:return 'heartbeat' + if "'worker_dead':dead" in code:return 'job_probe' + if "'bootstrap-status.json'" in code:return 'bootstrap_probe' + if 'subprocess.Popen' in code:return 'launch' + if 'archive_verified' in code:return 'extract' + return 'other' + +def running_status(job):return {'stdout':'WEB_COMFYUI_JSON='+json.dumps({'status':{'job_id':job['id'],'manifest_sha256':job['manifest_sha256'],'phase':'running'},'worker_dead':False})} + +def test_confirm_two_faults_in_one_worker_cycle_are_not_terminal(rig): + r=rig;st,job=running(r);sid=st['id'];seen=[] + def fault(op,kw): + if probe_kind(op,kw) in {'heartbeat','job_probe'}: + seen.append(probe_kind(op,kw));raise BridgeError('execution_uncertain',True) + r.b.hook=fault;r.t[0]+=10 + # The exact service._loop ordering, using both real tick implementations. + r.s.sessions.tick_all();r.s.tick(job) + s=r.s.sessions.get(sid);j=r.s.job(r.owner,job['id']) + assert seen==['heartbeat','job_probe'] and s['phase']=='closing' + assert s['fault_streak']==2 and s['last_tick']==st['last_tick'] + r.b.hook=None;r.s.sessions.tick_all() + assert r.s.sessions.get(sid)['released'] + assert sum(op=='runtime_stop' for op,_ in r.b.calls)==1 + +def test_confirm_alternating_faulted_worker_cycles_renew_lease(rig): + r=rig;st,job=running(r);sid=st['id'];first=r.t[0];bad=['heartbeat'];faults=[] + def hook(op,kw): + kind=probe_kind(op,kw) + if kind==bad[0]:faults.append(kind);raise BridgeError('execution_uncertain',True) + if kind=='job_probe':return running_status(job) + r.b.hook=hook + for i in range(16): + bad[0]='heartbeat' if i%2==0 else 'job_probe';r.t[0]+=10 + before=r.s.sessions.get(sid)['last_tick'] + r.s.sessions.tick_all();r.s.tick(job) + current=r.s.sessions.get(sid) + assert current['last_tick']==st['last_tick'] + if i==0:assert current['phase']=='ready' and current['fault_streak']==1 + elif i==1:assert current['phase']=='closing' and current['fault_streak']==2 + else:assert current['phase']=='closed' + assert len(faults)==2 and r.t[0]-first>90 + assert sum(op=='runtime_stop' for op,_ in r.b.calls)==1 + +def test_confirm_slow_upload_after_heartbeat_retry_exceeds_fault_span(rig): + r=rig;st=session(r,'uploading');sid=st['id'];r.s.sessions.freeze(st) + def first(op,kw): + if probe_kind(op,kw)=='heartbeat':raise BridgeError('execution_uncertain',True) + r.b.hook=first;r.s.sessions.tick_all();since=r.s.sessions.get(sid)['fault_since'] + def slow_upload(op,kw): + if op=='upload':r.t[0]+=100;return {} # within the bridge's existing 150s upload timeout + r.b.hook=slow_upload;r.t[0]+=10;r.s.sessions.tick_all();state=r.s.sessions.get(sid) + assert r.t[0]-since==110 and state['phase']=='closing' + assert not state.get('archive_uploaded') and not state.get('upload_completed_at') + assert state['fault_streak']>=1 and state['fault_since']==since and state['terminal_fault'] + assert state['last_tick']==st['last_tick'] + assert next(kw['_timeout_seconds'] for op,kw in r.b.calls if op=='upload')==80 + r.b.hook=None;r.s.sessions.tick_all() + assert r.s.sessions.get(sid)['released'] + +@pytest.mark.parametrize('kind',['heartbeat','bootstrap_probe','job_probe']) +def test_second_same_probe_fault_closes_and_does_not_relaunch(rig,kind): + r=rig + if kind=='job_probe':st,job=running(r) + else: + st=session(r,'bootstrap' if kind=='bootstrap_probe' else 'ready',launch_at=r.t[0]);job=None + if kind=='bootstrap_probe':r.s.sessions.freeze(st) + sid=st['id'];last=st['last_tick'] + def fault(op,kw): + if probe_kind(op,kw)==kind:raise BridgeError('execution_uncertain',True,{'error_type':'ReadTimeout','http_status':503,'transport_phase':'read','timeout_kind':'read'}) + r.b.hook=fault + for i in range(2): + r.t[0]+=10 + if job:r.s.tick(job) + else:r.s.sessions.tick_all() + s=r.s.sessions.get(sid) + assert s['last_tick']==last + assert s['phase']=='closing' if i else s['phase']!='closing' + r.b.hook=None;r.s.sessions.tick_all() + assert r.s.sessions.get(sid)['released'] + assert sum(op=='runtime_stop' for op,_ in r.b.calls)==1 + if job: + receipt=r.a.poll(r.owner,job['id']);assert receipt['state']=='failed' + assert receipt['diagnostics']['stage']=='session_fault' and receipt['diagnostics']['substage']==kind + +@pytest.mark.parametrize('stage',['heartbeat','bootstrap_probe']) +def test_one_fault_then_complete_success_keeps_session(rig,stage): + r=rig;st=session(r,'bootstrap' if stage=='bootstrap_probe' else 'ready',launch_at=r.t[0]);sid=st['id'] + if stage=='bootstrap_probe':r.s.sessions.freeze(st) + def fault(op,kw): + if probe_kind(op,kw)==stage:raise BridgeError('execution_uncertain',True) + r.b.hook=fault;r.t[0]+=10;r.s.sessions.tick_all() + assert r.s.sessions.get(sid)['last_tick']==st['last_tick'] + r.b.hook=None;r.t[0]+=10;r.s.sessions.tick_all() + assert r.s.sessions.get(sid)['phase']=='ready' + assert r.s.sessions.get(sid)['fault_streak']==0 + +def test_span_expired_before_retry_closes(rig): + r=rig;st=session(r);sid=st['id'] + def fault(op,kw): + if probe_kind(op,kw)=='heartbeat':raise BridgeError('execution_uncertain',True) + r.b.hook=fault;r.s.sessions.tick_all();count=len(r.b.calls);r.t[0]+=90;r.b.hook=None;r.s.sessions.tick_all() + assert r.s.sessions.get(sid)['released'] + assert not any(probe_kind(op,kw)=='heartbeat' for op,kw in r.b.calls[count:]) + +@pytest.mark.parametrize('kind',['launch','extract','upload']) +def test_session_mutation_ambiguity_closes_without_retry(rig,kind): + r=rig;st=session(r,'uploading');sid=st['id'];st=r.s.sessions.freeze(st) + if kind in {'extract','launch'}:st=r.s.sessions.save(sid,archive_uploaded=True) + if kind=='launch':st=r.s.sessions.save(sid,archive_verified=True,bootstrap_plan_id=next(iter(st['plan_catalog']))) + hits=[] + def fault(op,kw): + if probe_kind(op,kw)==kind:hits.append(kind);raise BridgeError('execution_uncertain',True) + r.b.hook=fault;r.s.sessions.tick_all();assert r.s.sessions.get(sid)['phase']=='closing' + r.s.sessions.tick_all();assert r.s.sessions.get(sid)['released'] and len(hits)==1 + +def test_ambiguous_job_launch_is_not_reposted(rig): + r=rig;st,job=running(r);r.s.update(job['id'],phase='preparing',upload_index=len(job['uploads'])) + hits=[] + def hook(op,kw): + if probe_kind(op,kw)=='launch':hits.append(kw['code']);raise BridgeError('execution_uncertain',True) + if probe_kind(op,kw)=='job_probe':return running_status(job) + r.b.hook=hook;r.s.tick(job);assert r.s.job(r.owner,job['id'])['phase']=='launch_uncertain' + for _ in range(3):r.t[0]+=10;r.s.sessions.tick_all();r.s.tick(job) + assert len(hits)==1 + assert r.s.sessions.get(st['id'])['phase']=='ready' + assert r.s.job(r.owner,job['id'])['phase']=='running' or r.s.job(r.owner,job['id'])['phase']=='launch_uncertain' + +@pytest.mark.parametrize('failed_stage',['heartbeat','job_probe']) +def test_only_complete_cycle_clears_shared_budget_and_collector_cannot(rig,failed_stage): + r=rig;st,job=running(r);sid=st['id'];last=st['last_tick'] + def fail(op,kw): + kind=probe_kind(op,kw) + if kind==failed_stage:raise BridgeError('execution_uncertain',True) + if kind=='job_probe':return running_status(job) + r.b.hook=fail;r.t[0]+=10;r.s.sessions.tick_all();r.s.tick(job) + faulted=r.s.sessions.get(sid) + assert faulted['fault_streak']==1 and faulted['last_tick']==last + r.a.poll(r.owner,job['id']);r.a.poll(r.owner,job['id']) + assert r.s.sessions.get(sid)==faulted + r.b.hook=lambda op,kw:running_status(job) if probe_kind(op,kw)=='job_probe' else None + r.t[0]+=10;r.s.sessions.tick_all() + half=r.s.sessions.get(sid) + assert half['fault_streak']==1 and half['last_tick']==last + r.s.tick(job);complete=r.s.sessions.get(sid) + assert complete['phase']=='ready' and complete['fault_streak']==0 and complete['fault_since'] is None + assert complete['last_tick']==r.t[0] and r.s.job(r.owner,job['id'])['phase']=='running' + heartbeat=[kw['code'] for op,kw in r.b.calls if probe_kind(op,kw)=='heartbeat'][-1] + assert str(last) in heartbeat + + +def test_slow_account_observation_is_bounded_and_cannot_commit_meter(rig): + r=rig;st=session(r);sid=st['id'] + r.b.hook=lambda op,kw:(_ for _ in ()).throw(BridgeError('execution_uncertain',True)) if probe_kind(op,kw)=='heartbeat' else None + r.s.sessions.tick_all();r.t[0]+=60 + def slow(op,kw): + if op=='account_status': + assert kw['_timeout_seconds']==30 + r.t[0]+=31 + return {'authenticated':True,'balance_compute_units':999} + r.b.hook=slow;r.s.sessions.tick_all();state=r.s.sessions.get(sid) + assert state['phase']=='closing' and state['last_tick']==st['last_tick'] + assert state['units_observed']==0 and state['usage_checked_at']==st['usage_checked_at'] + assert state['terminal_fault']['code']=='execution_uncertain' + r.b.hook=None;r.s.sessions.tick_all();assert r.s.sessions.get(sid)['released'] + + +@pytest.mark.parametrize('op',['upload','download','account_status','runtime_lookup','remote_exec']) +def test_every_rpc_uses_fresh_session_budget_even_for_stale_job(rig,op): + r=rig;st,job=running(r);sid=st['id'] + r.s.sessions.save(sid,fault_streak=1,fault_since=r.t[0]-89,fault={'stage':'heartbeat','code':'execution_uncertain'}) + seen=[] + def rpc(actual,kw): + if actual==op:seen.append(kw);return {} + r.b.hook=rpc;r.s._call(job,op) + assert seen[0]['_timeout_seconds']==1 + if op=='remote_exec':assert seen[0]['timeout_seconds']==1 + assert r.s.sessions.get(sid)['fault_streak']==1 + + +@pytest.mark.parametrize('field',['archive_uploaded','archive_verified','upload_completed_at','digest_verified_at']) +def test_success_commit_rechecks_expired_budget(rig,field): + r=rig;st=session(r,'uploading');sid=st['id'] + fault={'stage':'heartbeat','code':'execution_uncertain'} + r.s.sessions.save(sid,fault_streak=1,fault_since=r.t[0],fault=fault) + r.t[0]+=90 + with pytest.raises(BridgeError):r.s.sessions.save(sid,**{field:True}) + state=r.s.sessions.get(sid) + assert not state.get(field) and state['phase']=='closing' and state['terminal_fault']==fault + assert state['last_tick']==st['last_tick'] + + +def test_cycle_finalize_rechecks_expired_budget(rig): + r=rig;st,job=running(r);sid=st['id'] + fault={'stage':'heartbeat','code':'execution_uncertain'} + r.s.sessions.save(sid,fault_streak=1,fault_since=r.t[0],fault=fault, + cycle_session_ok=True,cycle_job=job['id'],cycle_faulted=False) + r.t[0]+=90 + with pytest.raises(BridgeError):r.s.sessions.finish_cycle(sid,job['id']) + state=r.s.sessions.get(sid) + assert state['phase']=='closing' and state['fault_streak']==1 and state['last_tick']==st['last_tick'] + +@pytest.mark.parametrize('op',['upload','download','account_status','remote_exec']) +def test_bridge_subprocess_obeys_remaining_budget(rig,monkeypatch,tmp_path,op): + from colab_service import Bridge + from types import SimpleNamespace + import colab_service + def invoke(*args,**kwargs): + assert kwargs['timeout']==0.5 + assert '_timeout_seconds' not in json.loads(kwargs['input']) + return SimpleNamespace(stdout=json.dumps({'ok':True,'result':{}}),returncode=0) + monkeypatch.setattr(colab_service.subprocess,'run',invoke) + # The fixture forbids real bridge calls; restore this method only under a + # subprocess mock, with an inert existing interpreter path. + module=colab_service + source=Path(module.__file__).read_text() + import ast + node=next(n for n in ast.parse(source).body if isinstance(n,ast.ClassDef) and n.name=='Bridge') + scope=dict(module.__dict__);exec(compile(ast.Module(body=[node],type_ignores=[]),'bridge-budget','exec'),scope) + scope['Bridge']('/usr/bin/python3')(op,tmp_path,_timeout_seconds=0.5) + + +def test_closing_during_late_reply_cannot_erase_rpc_deadline(rig): + r=rig;st=session(r,'uploading');sid=st['id'];r.s.sessions.freeze(st) + r.s.sessions.save(sid,fault_streak=1,fault_since=r.t[0],fault={'stage':'heartbeat','code':'execution_uncertain'}) + def slow(op,kw): + if op=='upload': + r.s.sessions.save(sid,phase='closing',close_requested=True) + r.t[0]+=91;return {} + r.b.hook=slow;r.s.sessions.tick_all();current=r.s.sessions.get(sid) + assert current['phase']=='closing' and not current.get('archive_uploaded') + assert not current.get('upload_completed_at') and current['last_tick']==st['last_tick'] + +@pytest.mark.parametrize('next_cycle',[False,True]) +def test_shared_budget_survives_controller_restart(rig,next_cycle): + from colab_service import ColabService + r=rig;st,job=running(r);sid=st['id'] + r.b.hook=lambda op,kw:(_ for _ in ()).throw(BridgeError('execution_uncertain',True)) if probe_kind(op,kw)=='heartbeat' else running_status(job) if probe_kind(op,kw)=='job_probe' else None + r.t[0]+=10;r.s.sessions.tick_all() + if next_cycle:r.s.tick(job) + # Real SQLite state, fresh controller object; no in-memory recovery state. + r.s=ColabService(r.s.root,r.b,lambda:r.t[0]) + r.b.hook=lambda op,kw:(_ for _ in ()).throw(BridgeError('execution_uncertain',True)) if probe_kind(op,kw)=='job_probe' else None + if next_cycle:r.t[0]+=10;r.s.sessions.tick_all() + r.s.tick(job);state=r.s.sessions.get(sid) + assert state['phase']=='closing' and state['fault_streak']==2 + assert state['last_tick']==st['last_tick'] + +def test_r40_combined_probe_heartbeat_one_rpc_and_fault6_fault7(rig): + r=rig;st=session(r,'bootstrap',launch_at=r.t[0]);sid=st['id'];r.s.sessions.freeze(st) + seen=[] + def fault(op,kw): + if op=='remote_exec': + seen.append(kw['code']);raise BridgeError('execution_uncertain',True) + r.b.hook=fault;r.t[0]+=10;r.s.sessions.tick_all() + first=r.s.sessions.get(sid) + assert first['fault_streak']==1 and first['last_tick']==st['last_tick'] + # Restart cannot clear the durable budget. A later probe+heartbeat failure + # (the live fault-6/fault-7 pattern) cannot publish a partial success. + from colab_service import ColabService + r.s=ColabService(r.s.root,r.b,lambda:r.t[0]);r.t[0]+=24;r.s.sessions.tick_all() + final=r.s.sessions.get(sid) + assert len(seen)==2 and all('bootstrap-status.json' in code and "watchdog.lock" in code for code in seen) + assert final['phase']=='closing' and final['fault_streak']==2 and final['last_tick']==st['last_tick'] + +def test_r40_complete_combined_probe_keeps_last_complete_heartbeat(rig): + r=rig;st=session(r,'bootstrap',launch_at=r.t[0]);sid=st['id'];r.s.sessions.freeze(st) + r.b.calls.clear();r.t[0]+=10;r.s.sessions.tick_all() + calls=[kw['code'] for op,kw in r.b.calls if op=='remote_exec'] + assert len(calls)==1 and 'bootstrap-status.json' in calls[0] and 'watchdog.lock' in calls[0] + assert f"write_text(str({st['last_tick']!r}))" in calls[0] + assert r.s.sessions.get(sid)['last_tick']==r.t[0] + +def test_r40_liveness_only_probe_does_not_renew(rig): + r=rig;st=session(r,'bootstrap',launch_at=r.t[0]);sid=st['id'];r.s.sessions.freeze(st) + def live(op,kw): + if op=='remote_exec':return {'stdout':'WEB_COMFYUI_JSON='+json.dumps({'phase':'running','alive':True,'progress_at':r.t[0]-121})} + r.b.hook=live;r.t[0]+=10;r.s.sessions.tick_all() + assert r.s.sessions.get(sid)['last_tick']==st['last_tick'] + assert r.s.sessions.get(sid)['phase']=='bootstrap' + assert r.s.sessions.get(sid)['fault_streak']==1 + r.s.sessions.tick_all() + assert r.s.sessions.get(sid)['last_tick']==st['last_tick'] + assert r.s.sessions.get(sid)['phase']=='closing' diff --git a/scripts/test_review_r38b_edges.py b/scripts/test_review_r38b_edges.py new file mode 100644 index 0000000..fd14d57 --- /dev/null +++ b/scripts/test_review_r38b_edges.py @@ -0,0 +1,330 @@ +import ast,json,subprocess +from types import SimpleNamespace as NS +import pytest +import colab_service +from colab_service import ColabService,Bridge,BridgeError,TERMINAL +from review_r38_fixture import rig,session,submit +from test_review_r38_faults import running,probe_kind,running_status + +REAL_BRIDGE_CALL=Bridge.__call__ + +def cycle(r): + with r.s.db() as db:jobs=[json.loads(row[0]) for row in db.execute('SELECT state FROM jobs')] + r.s.sessions.tick_all() + for job in jobs: + if job['phase'] not in TERMINAL:r.s.tick(job) + +def fail_kind(kind): + def hook(op,kw): + if probe_kind(op,kw)==kind:raise BridgeError('execution_uncertain',True) + return hook + +def test_real_loop_two_faults_and_release(rig,monkeypatch): + r=rig;st,job=running(r);seen=[];ticks=[] + def hook(op,kw): + kind=probe_kind(op,kw) + if kind in {'heartbeat','job_probe'}: + seen.append(kind);raise BridgeError('execution_uncertain',True) + class StopLoop(BaseException):pass + def sleep(seconds): + ticks.append(r.s.sessions.get(st['id'])) + if len(ticks)==2:raise StopLoop() + r.t[0]+=seconds + monkeypatch.setattr(colab_service.time,'sleep',sleep);r.b.hook=hook + with pytest.raises(StopLoop):r.s._loop() + assert seen==['heartbeat','job_probe'] + assert ticks[0]['phase']=='closing' and ticks[1]['phase']=='closed' + assert all(s['last_tick']==st['last_tick'] for s in ticks) + assert sum(op=='runtime_stop' for op,_ in r.b.calls)==1 + +@pytest.mark.parametrize('fault_stage',['heartbeat','job_probe']) +@pytest.mark.parametrize('restart',[False,True]) +def test_reads_and_restart_cannot_clear_open_cycle(rig,fault_stage,restart): + r=rig;st,job=running(r);sid=st['id'];r.t[0]+=10 + def hook(op,kw): + if probe_kind(op,kw)==fault_stage:raise BridgeError('execution_uncertain',True) + if probe_kind(op,kw)=='job_probe':return running_status(job) + r.b.hook=hook;cycle(r);faulted=r.s.sessions.get(sid) + assert faulted['fault_streak']==1 and faulted['last_tick']==st['last_tick'] + for _ in range(3):r.a.poll(r.owner,job['id']);r.s.sessions.snapshot(r.owner);r.s.public_job(r.s.job(r.owner,job['id'])) + assert r.s.sessions.get(sid)==faulted + if restart:r.s=ColabService(r.s.root,r.b,lambda:r.t[0]) + r.b.hook=lambda op,kw:running_status(job) if probe_kind(op,kw)=='job_probe' else None + r.t[0]+=10;r.s.sessions.tick_all() + assert r.s.sessions.get(sid)['last_tick']==st['last_tick'] + assert r.s.sessions.get(sid)['fault_streak']==1 + code=[kw['code'] for op,kw in r.b.calls if probe_kind(op,kw)=='heartbeat'][-1] + assert f"write_text(str({st['last_tick']!r}))" in code + r.s.tick(job);good=r.s.sessions.get(sid) + assert good['last_tick']==r.t[0] and good['fault_streak']==0 + +@pytest.mark.parametrize('restart',[False,True]) +def test_no_active_job_recovery_budget_survives_restart(rig,restart): + r=rig;st=session(r);r.b.hook=fail_kind('heartbeat');r.t[0]+=10;cycle(r) + if restart:r.s=ColabService(r.s.root,r.b,lambda:r.t[0]) + r.t[0]+=90;r.b.hook=None;r.b.calls.clear();cycle(r) + assert r.s.sessions.get(st['id'])['released'] + assert not any(op=='remote_exec' for op,_ in r.b.calls) + +@pytest.mark.parametrize('faulted',[False,True]) +def test_finished_job_midcycle_and_next_job_budget(rig,faulted): + r=rig;st,job=running(r);sid=st['id'];nextid=submit(r)['request_id'] + # Finish the real cleanup path; only remote cleanup evidence is mocked. + r.s.update(job['id'],phase='cleanup_pending',outcome='completed') + def hook(op,kw): + if faulted and probe_kind(op,kw)=='heartbeat':raise BridgeError('execution_uncertain',True) + if op=='remote_exec' and 'reusable-clean.json' in kw['code']: + return {'stdout':'WEB_COMFYUI_JSON='+json.dumps({'clean':True,'job_id':job['id'],'manifest_sha256':job['manifest_sha256']})} + r.b.hook=hook;r.t[0]+=10;cycle(r);state=r.s.sessions.get(sid) + assert r.s.job(r.owner,job['id'])['released'] and state['active_job'] is None + assert state['last_tick']==(st['last_tick'] if faulted else r.t[0]) + assert state['fault_streak']==(1 if faulted else 0) + # New job is attached next cycle; an earlier fault cannot disappear at attach. + r.b.hook=None;r.t[0]+=10;r.s.sessions.tick_all();state=r.s.sessions.get(sid) + assert state['active_job']==nextid and state['fault_streak']==(1 if faulted else 0) + r.b.hook=lambda op,kw:(_ for _ in ()).throw(BridgeError('upload_transport_failed')) if op=='upload' else None + r.s.tick(r.s.job(r.owner,nextid));state=r.s.sessions.get(sid) + assert state['phase']==('closing' if faulted else 'ready') + +@pytest.mark.parametrize('op',['upload','download','account_status','runtime_lookup','remote_exec']) +def test_every_rpc_uses_durable_remaining_and_rejects_late_reply(rig,op): + r=rig;st,job=running(r);sid=st['id'] + r.b.hook=fail_kind('job_probe');cycle(r) + r.t[0]+=89.5;seen=[] + def hook(actual,kw): + if actual==op: + seen.append(kw);r.t[0]+=.6;return {} + r.b.hook=hook + with pytest.raises(BridgeError):r.s._call(job,op) + assert len(seen)==1 and seen[0]['_timeout_seconds']==.5 + assert r.s.sessions.get(sid)['phase']=='closing' + assert r.s.sessions.get(sid)['last_tick']==st['last_tick'] + +@pytest.mark.parametrize('op',['upload','download','account_status','runtime_lookup','remote_exec']) +def test_actual_bridge_parent_timeout_is_bounded(rig,monkeypatch,tmp_path,op): + calls=[] + def run(*a,**kw): + calls.append(kw);return NS(stdout=json.dumps({'ok':True,'result':{}}),returncode=0) + monkeypatch.setattr(colab_service.subprocess,'run',run) + assert REAL_BRIDGE_CALL(Bridge('/usr/bin/python3'),op,tmp_path,_timeout_seconds=.25)=={} + assert calls[0]['timeout']==.25 + assert '_timeout_seconds' not in json.loads(calls[0]['input']) + +@pytest.mark.parametrize('phase',['queued','running']) +def test_actual_cycle_cancellation_keeps_fault(rig,phase): + r=rig + if phase=='queued':st=session(r);rid=submit(r)['request_id'] + else:st,job=running(r);rid=job['id'] + r.b.hook=fail_kind('heartbeat');r.s.sessions.tick_all();r.s.cancel(r.owner,rid) + r.t[0]+=10;cycle(r);r.b.hook=None;cycle(r) + receipt=r.a.poll(r.owner,rid) + assert receipt['state']=='cancelled' and receipt['diagnostics']['stage']=='session_fault' + assert r.s.sessions.get(st['id'])['released'] + +def test_plain_system_close_does_not_mean_cancel(rig): + r=rig;st=session(r);rid=submit(r)['request_id'] + r.s.sessions.save(st['id'],phase='closing',close_requested=True,reason='watchdog_or_hard_cap') + cycle(r);assert r.a.poll(r.owner,rid)['state']=='failed' + +def test_clock_rewind_can_extend_single_fault_budget(rig): + r=rig;st=session(r,'uploading');sid=st['id'];r.s.sessions.freeze(st) + r.b.hook=fail_kind('heartbeat');cycle(r);since=r.s.sessions.get(sid)['fault_since'] + r.t[0]-=120 # host wall clock steps backwards after the durable fault + seen=[] + def upload(op,kw): + if op=='upload':seen.append(kw);r.t[0]+=140;return {} + r.b.hook=upload;cycle(r);state=r.s.sessions.get(sid) + assert not seen and not state.get('archive_uploaded') and not state.get('upload_completed_at') + assert state['last_tick']==st['last_tick'] and state['phase']=='closed' + assert state['terminal_fault']['code']=='clock_inconsistent' + assert sum(op=='runtime_stop' for op,_ in r.b.calls)==1 + assert not any(op in {'upload','runtime_allocate'} for op,_ in r.b.calls) + +def test_missing_session_breaks_preexisting_orphan_release(rig): + r=rig;st,job=running(r) + with r.s.db() as db:db.execute('DELETE FROM work_sessions WHERE id=?',(st['id'],)) + r.s.tick(job);r.s.tick(job) + assert r.s.job(r.owner,job['id'])['orphan_session'] + assert sum(op=='runtime_stop' for op,_ in r.b.calls)==1 + assert r.s.job(r.owner,job['id'])['released'] + +@pytest.mark.parametrize('mutation',['job_launch','bootstrap_launch','archive_extract']) +def test_expired_mutation_reply_never_relaunches(rig,mutation): + r=rig + if mutation=='job_launch': + st,job=running(r);r.s.update(job['id'],phase='preparing',upload_index=len(job['uploads'])) + else: + st=session(r,'uploading');st=r.s.sessions.freeze(st) + st=r.s.sessions.save(st['id'],archive_uploaded=True) + if mutation=='bootstrap_launch': + rid=submit(r)['request_id'];pid=next(iter(st['plan_catalog'])) + r.s.update(rid,bootstrap_plan_id=pid) + st=r.s.sessions.save(st['id'],archive_verified=True,bootstrap_plan_id=pid) + r.b.hook=fail_kind('heartbeat');r.s.sessions.tick_all() + r.t[0]+=10;hits=[] + def late(op,kw): + if probe_kind(op,kw)==('extract' if mutation=='archive_extract' else 'launch'): + hits.append(kw);assert kw['_timeout_seconds']==75 + r.t[0]+=81 + return {'stdout':'WEB_COMFYUI_JSON='+json.dumps({'archive_verified':True,'launched':True,'pid':1,'start_ticks':'42'})} + r.b.hook=late;cycle(r);s=r.s.sessions.get(st['id']) + assert hits and s['phase'] in {'closing','closed'} and s['last_tick']==st['last_tick'] + if mutation=='archive_extract':assert not s['archive_verified'] + r.b.hook=None;cycle(r) + assert r.s.sessions.get(st['id'])['released'] and len(hits)==1 + +def test_slow_account_reply_never_commits_meter(rig): + r=rig;st=session(r);r.b.hook=fail_kind('heartbeat');cycle(r) + r.t[0]+=60 + def slow(op,kw): + if op=='account_status': + assert kw['_timeout_seconds']==30;r.t[0]+=31 + return {'authenticated':True,'balance_compute_units':900} + r.b.hook=slow;cycle(r);s=r.s.sessions.get(st['id']) + assert s['phase']=='closing' and s['units_observed']==0 and s['usage_checked_at']==st['usage_checked_at'] + assert s['last_tick']==st['last_tick'] + +@pytest.mark.parametrize('restart',[False,True]) +@pytest.mark.parametrize('field',['fault_since','fault_at','last_tick']) +@pytest.mark.parametrize('bad',['future','nan','inf']) +def test_inconsistent_durable_time_closes_without_work_rpc(rig,restart,field,bad): + r=rig;st=session(r,'uploading');sid=st['id'];r.s.sessions.freeze(st) + r.b.hook=fail_kind('heartbeat');cycle(r) + value=r.t[0]+120 if bad=='future' else float(bad) + corrupt=r.s.sessions.get(sid) + if field=='fault_at':corrupt['fault']['at']=value + else:corrupt[field]=value + with r.s.db() as db:db.execute('UPDATE work_sessions SET state=? WHERE id=?',(json.dumps(corrupt),sid)) + if restart:r.s=ColabService(r.s.root,r.b,lambda:r.t[0]) + r.b.hook=None;r.b.calls.clear();cycle(r);state=r.s.sessions.get(sid) + assert state['phase']=='closed' and state['released'] + assert state['terminal_fault']['code']=='clock_inconsistent' + assert not any(op in {'remote_exec','upload','download','runtime_allocate'} for op,_ in r.b.calls) + assert sum(op=='runtime_stop' for op,_ in r.b.calls)==1 + +@pytest.mark.parametrize('faulted',[False,True]) +def test_forward_wall_step_obeys_existing_caps_without_false_clock_fault(rig,faulted): + r=rig;st=session(r);sid=st['id'] + if faulted:r.b.hook=fail_kind('heartbeat');cycle(r) + r.b.hook=None;r.t[0]+=30;cycle(r) + assert r.s.sessions.get(sid)['phase']=='ready' + assert r.s.sessions.get(sid)['last_tick']==r.t[0] + r.t[0]=st['deadline_epoch']+1;cycle(r) + assert r.s.sessions.get(sid)['released'] + assert (r.s.sessions.get(sid).get('terminal_fault') or {}).get('code')!='clock_inconsistent' + +@pytest.mark.parametrize('op',['upload','account_status']) +def test_monotonic_elapsed_deadline_rejects_late_reply_despite_small_wall_delta(rig,op): + r=rig;st=session(r,'uploading');sid=st['id'];r.s.sessions.freeze(st);mono=[100.0] + r.s.sessions._monotonic=lambda:mono[0] + r.b.hook=fail_kind('heartbeat');cycle(r);r.t[0]+=10;mono[0]+=10 + def late(actual,kw): + if actual==op: + assert 0', 'fixture' + ext, content_type, 'file') + server.record_input_upload_owner(name, B) + h = handler(B) + h.api_view('type=input&filename=' + name) + assert h.status == 200 + assert h.response_headers['Content-Type'] == 'application/octet-stream' + assert h.response_headers['Content-Disposition'].startswith('attachment') + assert h.response_headers['X-Content-Type-Options'] == 'nosniff' + for name in ('fixture.mp4', 'fixture.png'): + p = state.input / name + p.write_bytes(b'media') + h = handler(B) + h.send_local_file(p) + assert h.response_headers['X-Content-Type-Options'] == 'nosniff' + h = handler(B) + h.serve_static('app.js') + assert h.status == 200 + assert 'javascript' in h.response_headers['Content-Type'] + assert h.response_headers['X-Content-Type-Options'] == 'nosniff' + h = handler(B) + h.send_local_file(state.input / 'missing.html') + assert h.status == 404 + assert h.response_headers['X-Content-Type-Options'] == 'nosniff' + h = handler(B, headers={'Range': 'bytes=999-1000'}) + h.send_local_file(state.input / 'fixture.png') + assert h.status == 416 + assert h.response_headers['X-Content-Type-Options'] == 'nosniff' + + +def test_i_error_path_masking_is_role_dependent(state): + path = '/home/' + 'synthetic/private/file.txt' + user, admin = handler(B), handler(ADMIN) + user.send_error_json(ValueError('failure: ' + path), 400) + admin.send_error_json(ValueError('failure: ' + path), 400) + assert '' in response_json(user)['error'] + assert path not in response_json(user)['error'] + assert path in response_json(admin)['error'] + + +def test_i_upstream_error_details_are_masked_for_non_admin(state, monkeypatch): + path = '/var/' + 'synthetic/private/model.bin' + monkeypatch.setattr(server, 'comfy_error_payload', lambda body: { + 'message': 'missing ' + path, + 'error_code': 'fixture', + 'submission_state': 'failed', + 'technical_detail': 'detail ' + path, + }) + upstream = server.urllib.error.HTTPError('fixture', 500, 'synthetic', {}, io.BytesIO(b'{}')) + h = handler(B) + h.send_error_json(upstream, 400) + assert '' in response_json(h)['error'] + assert '' in response_json(h)['technical_detail'] + assert path not in json.dumps(response_json(h)) + + +def test_c_client_drive_controls_and_callback_toasts(state): + js = r''' +const assert = require('assert'); +const fs = require('fs'); +const src = fs.readFileSync(process.argv[1], 'utf8'); +let begin = src.indexOf('function renderDriveFetch('); +let end = src.indexOf('\nfunction ', begin + 1); +assert(begin >= 0 && end > begin); +let operator = false, created = [], timers = [], requests = []; +function isOperator() { return operator; } +function h(tag, attrs, children=[]) { + created.push({tag, attrs}); + return {tag, attrs, children, value: '', textContent: '', className: '', disabled: false, + classList: {add(){}, toggle(){}}, addEventListener(){}, appendChild(){}}; +} +function setTimeout(fn) { timers.push(fn); } +async function api(path) { requests.push(path); return {configured:false}; } +function useServerVideo() {} +function formatBytes() { return ''; } +eval(src.slice(begin, end)); +renderDriveFetch({id:'video'}, {}, {}); +assert(created.some(x => x.attrs.placeholder === '貼上公開分享的 Google Drive 連結')); +assert(!created.some(x => x.attrs.text === '登入 Google Drive')); +assert.strictEqual(timers.length, 0); +operator = true; created = []; timers = []; +renderDriveFetch({id:'video'}, {}, {}); +assert(created.some(x => x.attrs.text === '登入 Google Drive')); +assert.strictEqual(timers.length, 1); +timers[0](); +assert.deepStrictEqual(requests, ['/api/google/status']); +begin = src.indexOf(' const callbackUrl =', src.indexOf('function boot()')); +end = src.indexOf('\n primeRouteBeforePaint();', begin); +assert(begin >= 0 && end > begin); +const callback = new Function('window', 'history', 'showToast', src.slice(begin,end)); +for (const [value,expected] of [ + ['connected','Google Drive 已連結'], + ['session_error','請在登入本站的同一個瀏覽器與網址完成 Google Drive 連結'], + ['denied','Google Drive 連結未完成,請再試一次']]) { + let messages=[], replaced=[]; + callback({location:{href:'https://fixture.invalid/?keep=yes&google_drive='+value+'#route'}}, + {state:{}, replaceState:(...a)=>replaced.push(a[2])}, x=>messages.push(x)); + assert.deepStrictEqual(messages,[expected]); + const parsed = new URL(replaced[0]); + assert.strictEqual(parsed.searchParams.has('google_drive'),false); + assert.strictEqual(parsed.searchParams.get('keep'),'yes'); + assert.strictEqual(parsed.hash,'#route'); +} +''' + app_js = Path(__file__).resolve().parents[1] / 'webui' / 'static' / 'app.js' + proc = subprocess.run(['node', '-e', js, str(app_js)], capture_output=True, text=True, timeout=10) + assert proc.returncode == 0, proc.stderr + + +def test_d_timeout_includes_login_hint_only_for_unshared_cookie(state, monkeypatch): + calls, _ = downloader_setup(state, monkeypatch) + monkeypatch.setattr(server.socket, 'getaddrinfo', lambda *a, **k: addr('8.8.8.8')) + monkeypatch.setattr(server.subprocess, 'run', Mock(side_effect=subprocess.TimeoutExpired('fixture', 1))) + for shared, expected in [(False, True), (True, False)]: + with pytest.raises(ValueError) as error: + server.fetch_video_url('https://' + 'm.facebook.com' + '/x', 'video', shared_cookies=shared) + assert ('請改為上傳影片檔' in str(error.value)) is expected + + +@pytest.mark.parametrize('endpoint,function', [ + ('api_fetch_url', 'fetch_video_url'), ('api_fetch_drive', 'fetch_google_drive_video') +]) +def test_d_routes_pass_operator_cookie_decision(state, monkeypatch, endpoint, function): + fetch = Mock(return_value={'filename': 'fixture.mp4'}) + monkeypatch.setattr(server, function, fetch) + monkeypatch.setattr(server, 'record_input_upload_owner', lambda *args: None) + for user, allowed in [(B, False), (ADMIN, False), (OPERATOR, True)]: + h = handler(user, {'url': 'https://' + 'fixture.invalid' + '/x', 'slot': 'video'}) + getattr(h, endpoint)() + assert h.status == 200 + assert fetch.call_args.kwargs == {'shared_cookies': allowed} + + +def test_d_mixed_public_and_private_dns_answers_are_refused(state, monkeypatch): + calls, _ = downloader_setup(state, monkeypatch) + monkeypatch.setattr(server.socket, 'getaddrinfo', lambda *a, **k: addr('8.8.8.8') + addr('10.0.0.5')) + with pytest.raises(ValueError, match='不是公開網址'): + server.fetch_video_url('https://' + 'fixture.invalid' + '/x', 'video', shared_cookies=False) + assert not calls + + +def test_a1b_long_suffix_and_normal_extensions(state, monkeypatch): + fake_upload(monkeypatch, state) + long_name = server.save_uploaded_bytes(b'image', 'photo.' + 'z' * 150, 'image/png', 'image') + assert len(long_name.encode()) <= 200 + assert long_name.endswith('.png') + assert 'photo.' + 'z' * 30 in long_name + ordinary = server.save_uploaded_bytes(b'video', 'ordinary.MP4', 'video/mp4', 'clip') + assert ordinary.endswith('.MP4') + assert server.staged_input_name('web', '!', 'plain', 'image/unknown').endswith('.png') + with pytest.raises(ValueError): + server.staged_input_name('unknown', 'slot', 'fixture.png') + + +def test_a1b_mime_fallback_extensions_are_validated(monkeypatch): + original_guess = mimetypes.guess_extension + + def controlled_guess(content_type, strict=True): + guesses = { + 'text/x-c++src': '.c++', + 'application/sarif-external-properties+json': '.' + 'a' * 20, + 'image/x-unknown-test': None, + } + if content_type in guesses: + return guesses[content_type] + return original_guess(content_type, strict=strict) + + monkeypatch.setattr(mimetypes, 'guess_extension', controlled_guess) + original = 'sample.' + 'z' * 150 + for content_type, extension in ( + ('text/x-c++src', ''), + ('application/sarif-external-properties+json', ''), + ('image/x-unknown-test', '.png'), + ('VIDEO/MP4; codecs=fixture', '.mp4'), + ): + name = server.staged_input_name('web', 'file', original, content_type) + assert re.fullmatch(r'[A-Za-z0-9._-]{1,200}', name) + if extension: + assert name.endswith(extension) + else: + assert name.endswith('z') and '+' not in name + + +def test_a1b_registered_mime_types_produce_safe_names(): + mimetypes.init() + original = 'base.' + 'z' * 295 + for content_type in [*mimetypes.types_map.values(), *mimetypes.common_types.values()]: + name = server.staged_input_name('web', 'file', original, content_type) + assert re.fullmatch(r'[A-Za-z0-9._-]{1,200}', name), content_type + + +def test_k_all_eight_input_writers_generate_random_bounded_names(state, monkeypatch): + import shutil + + source = state.root / 'fixture.mp4' + source.write_bytes(b'video') + voice = state.root / 'voices' / 'fixture.wav' + voice.parent.mkdir() + voice.write_bytes(b'audio') + monkeypatch.setattr(server, 'experimental_user_asset_path', lambda *a: source) + monkeypatch.setattr(server, 'load_voice_index', lambda: [{'id': 'fixture', 'filename': voice.name}]) + monkeypatch.setattr(server, 'user_can_access_voice_entry', lambda *a: True) + monkeypatch.setattr(server, 'google_drive_file_meta', lambda *a: {'name': 'x' * 300 + '.mp4', 'mimeType': 'video/mp4'}) + monkeypatch.setattr(server, 'google_access_token', lambda: 'fixture') + monkeypatch.setattr(server.urllib.request, 'urlopen', lambda *a, **k: contextlib.closing(io.BytesIO(b'video'))) + monkeypatch.setattr(server, 'resolve_crawl_video_path', lambda *a: source) + monkeypatch.setattr(server, '_video_codec', lambda *a: 'h264') + monkeypatch.setattr(server, 'ensure_cv2_compatible_video', lambda a, b: shutil.copyfile(a, b)) + monkeypatch.setattr(server, 'resolve_dance_library_template', lambda *a: ({}, {'id': 'fixture'})) + monkeypatch.setattr(server, 'prepare_dance_library_derivative', lambda *a: source) + monkeypatch.setattr(server, '_load_dance_library_catalog_unlocked', lambda: {}) + monkeypatch.setattr(server, 'resolve_view_path', lambda *a: source) + monkeypatch.setattr(server, 'gallery_media_kind', lambda *a: 'video') + downloader_setup(state, monkeypatch, 0) + monkeypatch.setattr(server.socket, 'getaddrinfo', lambda *a, **k: addr('8.8.8.8')) + writers = { + 'web': lambda: server.save_uploaded_bytes(b'video', 'x' * 300 + '.mp4', 'video/mp4', 'VIDEO'), + 'user_photo': lambda: server.import_user_photo_to_input({}, 'fixture.mp4', 'video')['filename'], + 'voice': lambda: server.resolve_voice_reference('fixture', A), + 'drive': lambda: server.import_google_drive_file('fixture', 'video')['filename'], + 'crawl': lambda: server.import_crawl_video('fixture', 'video')['filename'], + 'dance_library': lambda: server.import_dance_library_template('fixture', 'video')['filename'], + 'chain': lambda: server.import_view_item_to_input('fixture.mp4', '', 'output', 'video')['filename'], + 'url': lambda: server.fetch_video_url('http://' + 'fixture.invalid/x', 'video', shared_cookies=True)['filename'], + } + for kind, writer in writers.items(): + names = [writer(), writer()] + assert names[0] != names[1], kind + for name in names: + assert re.match(r'^castle_' + kind + r'_\d{10}_[0-9a-f]{32}_', name), kind + assert re.fullmatch(r'[A-Za-z0-9._-]{1,200}', name), kind + assert len(name.encode()) <= 200, kind + assert (state.input / name).is_file(), kind + if kind in {'web', 'drive'}: + assert all(name.endswith('.mp4') for name in names) + max_slot = server.staged_input_name('dance_library', 'a' * 100, 'x' * 300 + '.mp4') + assert len(max_slot.encode()) <= 200 and max_slot.endswith('.mp4') + + +def test_l_source_sidecars_are_hidden_before_receipt_or_prefix(state): + for name in ('castle_fixture.source.json', 'plain.SOURCE.JSON'): + (state.input / name).write_bytes(b'metadata') + server.record_input_upload_owner(name, B) + ordinary, administrator, missing = handler(B), handler(ADMIN), handler(B) + ordinary.api_view('type=input&filename=' + name) + administrator.api_view('type=input&filename=' + name) + missing.api_view('type=input&filename=missing.json') + assert ordinary.status == missing.status == 404 + assert ordinary.wfile.getvalue() == missing.wfile.getvalue() + assert administrator.status == 200 and administrator.wfile.getvalue() == b'metadata' + + diff --git a/scripts/test_security_s1d.py b/scripts/test_security_s1d.py new file mode 100644 index 0000000..3785dee --- /dev/null +++ b/scripts/test_security_s1d.py @@ -0,0 +1,442 @@ +"""Offline checks for the S1d download, H3 name, and rename guards.""" +import hashlib +import io +import json +import os +import socket +import stat +import subprocess +import sys +import threading +from pathlib import Path +from types import SimpleNamespace + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "webui")) +sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(ROOT / "scripts" / "minimax_h3")) + +import server # noqa: E402 +from provider_fabric.h3_worker import ( # noqa: E402 + H3SubmissionProcessor, + h3_upload_basename, + load_or_create_upload_name_key, +) +from provider_fabric.provider_worker import DefiniteLocalFailure # noqa: E402 +from run_provider_graph import SAFE_UPLOAD # noqa: E402 +from test_h3_provider_worker import H3ProviderWorkerTests # noqa: E402 + +ADMIN = {"email": "administrator" + "@" + "example.invalid", "role": "admin", "displayName": "administrator"} +RESERVED_RENAME_ERROR = "輸入素材的新檔名不可以用 castle_、library_ 或 reference_opc_ 開頭(系統保留名稱)" +UNSAFE_FORMAT_ERROR = "這個網址的影片只提供無法安全下載的串流格式,請改為上傳影片檔" +KEY_ERROR = "H3 upload-name key is not a private 32-byte file" + + +@pytest.fixture +def state(tmp_path, monkeypatch): + input_dir, output_dir, temp_dir = (tmp_path / name for name in ("input", "output", "temp")) + for directory in (input_dir, output_dir, temp_dir): + directory.mkdir() + monkeypatch.setattr(server, "COMFY_INPUT", input_dir) + monkeypatch.setattr(server, "COMFY_OUTPUT", output_dir) + monkeypatch.setattr(server, "COMFY_TEMP", temp_dir) + monkeypatch.setattr(server, "VIEW_DIRS", {"input": input_dir, "output": output_dir, "temp": temp_dir}) + monkeypatch.setattr(server, "HIDDEN_PATH", tmp_path / ".hidden.json") + monkeypatch.setattr(server, "JOB_INDEX_PATH", tmp_path / "jobs.json") + monkeypatch.setattr(server, "history_gallery_item_for_view", lambda *args, **kwargs: None) + monkeypatch.setattr(server, "load_job_index", lambda: {}) + monkeypatch.setattr(server.library_service, "catalog_path", lambda: tmp_path / "no-catalog.json") + return SimpleNamespace(root=tmp_path, input=input_dir, output=output_dir, temp=temp_dir) + + +def handler(body): + target = object.__new__(server.Handler) + target.headers = {} + target.current_user = lambda: ADMIN + target.read_json = lambda *args: body + target.status = None + target.response_headers = {} + target.wfile = io.BytesIO() + target.send_response = lambda status: setattr(target, "status", status) + target.send_header = lambda name, value: target.response_headers.__setitem__(name, str(value)) + target.end_headers = lambda: None + return target + + +def response_json(target): + return json.loads(target.wfile.getvalue()) + + +def rename_input(state, old_name, new_name, view_type="input", payload=b"synthetic-fixture"): + directory = {"input": state.input, "output": state.output, "temp": state.temp}[view_type] + source = directory / old_name + source.write_bytes(payload) + target = handler({"filename": old_name, "subfolder": "", "type": view_type, "name": new_name}) + target.api_history_rename() + return target.status, response_json(target), source, directory / new_name + + +class FakeProxy: + def __init__(self): + self.url = "http://127.0.0.1:9" + self.refusals = [] + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + +def install_download_fakes(monkeypatch, input_dir, calls): + monkeypatch.setattr(server, "COMFY_INPUT", input_dir) + monkeypatch.setattr(server, "CRAWL_DIR", input_dir) + monkeypatch.setattr(server.time, "time", lambda: 1700000000) + monkeypatch.setattr(server.secrets, "token_hex", lambda n=16: "ab" * n) + monkeypatch.setattr(server, "_resolve_yt_dlp", lambda: "/fixture/yt-dlp") + monkeypatch.setattr(server, "_crawl_cookie_file", lambda url: None) + monkeypatch.setattr(server, "_video_codec", lambda path: "h264") + monkeypatch.setattr(server.socket, "getaddrinfo", lambda host, port, *args, **kwargs: [ + (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("8.8.8.8", port or 0)), + ]) + monkeypatch.setattr(server.egress_guard, "GlobalOnlyProxy", lambda: FakeProxy()) + + def run(argv, **kwargs): + calls.append((list(argv), kwargs)) + filename = argv[argv.index("-o") + 1].replace("%(title).40s", "clip").replace("%(ext).16s", "mp4") + Path(filename).parent.mkdir(parents=True, exist_ok=True) + Path(filename).write_bytes(b"video") + return subprocess.CompletedProcess(argv, 0, stdout="", stderr="") + + monkeypatch.setattr(server, "subprocess", SimpleNamespace( + run=run, + TimeoutExpired=subprocess.TimeoutExpired, + CompletedProcess=subprocess.CompletedProcess, + )) + + +def test_d2b_guest_format_lock_and_operator_argv_matches_s1c(tmp_path, monkeypatch): + input_dir = tmp_path / "input" + calls = [] + install_download_fakes(monkeypatch, input_dir, calls) + url = "https://example.invalid/clip" + server.fetch_video_url(url, "slot", shared_cookies=False) + server.fetch_video_url(url, "slot", shared_cookies=True) + guest, operator = calls[0][0], calls[1][0] + # Literal operator argv captured once from the frozen S1c tree for this synthetic input. + output = str( + input_dir / "castle_url_1700000000_abababababababababababababababab_slot_%(title).40s.%(ext).16s" + ) + expected_operator = [ + "/fixture/yt-dlp", + "--no-playlist", + "--restrict-filenames", + "--no-progress", + "--max-filesize", "268435456", + "-f", "mp4/best[ext=mp4]/best", + "-o", output, + "--", + url, + ] + assert guest[0] == "/fixture/yt-dlp" + assert guest[1] == "--ignore-config" + assert guest[guest.index("-f") + 1] == server.GUEST_VIDEO_FORMAT + assert operator == expected_operator + assert "env" not in calls[1][1] + expected_guest = list(expected_operator) + expected_guest.insert(1, "--ignore-config") + expected_guest[expected_guest.index("-f") + 1] = server.GUEST_VIDEO_FORMAT + dash = expected_guest.index("--") + expected_guest[dash:dash] = ["--proxy", "http://127.0.0.1:9"] + assert guest == expected_guest + assert calls[0][1]["env"]["HTTPS_PROXY"] == "http://127.0.0.1:9" + assert "NO_PROXY" not in calls[0][1]["env"] and "no_proxy" not in calls[0][1]["env"] + assert "--ignore-config" not in operator + assert operator[operator.index("-f") + 1] == "mp4/best[ext=mp4]/best" + + +FORMAT_CASES = r""" +import json, os, sys +os.environ["PYTHONDONTWRITEBYTECODE"] = "1" +sys.dont_write_bytecode = True +sys.path.insert(0, sys.argv[1]) +import yt_dlp +from yt_dlp.utils import DownloadError, ExtractorError +fmt = sys.argv[2] +def one(protocol, height, fid, url=None): + item = { + "format_id": fid, + "url": url or ("https://cdn.example.invalid/" + fid + ".mp4"), + "ext": "mp4", "vcodec": "avc1", "acodec": "mp4a", "height": height, + } + if protocol is not None: + item["protocol"] = protocol + return item +def info(formats): + return { + "id": "vid", "title": "clip", "extractor": "generic", "extractor_key": "Generic", + "webpage_url": "https://example.invalid/", "formats": formats, + } +def select(formats): + ydl = yt_dlp.YoutubeDL({"format": fmt, "quiet": True, "simulate": True}) + try: + result = ydl.process_ie_result(info(formats), download=False) + except (ExtractorError, DownloadError) as exc: + return {"status": "unavailable", "exc": type(exc).__name__, "phrase": "Requested format is not available" in str(exc)} + return {"status": "selected", "format_id": result.get("format_id"), "protocol": result.get("protocol"), "height": result.get("height")} +cases = [ + ("rtmp-only", [one("rtmp_ffmpeg", 720, "rtmp-only")], "unavailable", None), + ("prefer-https", [one("rtmp_ffmpeg", 1080, "tall"), one("https", 360, "short")], "selected", "short"), + ("m3u8_native", [one("m3u8_native", 360, "m3u8-native")], "selected", "m3u8-native"), + ("m3u8", [one("m3u8", 360, "m3u8")], "selected", "m3u8"), + ("http_dash_segments", [one("http_dash_segments", 360, "dash")], "selected", "dash"), + ("http", [one("http", 360, "http")], "selected", "http"), +] +for protocol in ("rtmp", "rtmpe", "rtsp", "mms", "websocket_frag", "f4m", "ism", "mhtml", "fc2_live", "niconico_live"): + cases.append((protocol, [one(protocol, 360, protocol)], "unavailable", None)) +cases.append(("missing-protocol", [one(None, 360, "missing", "rtmp://cdn.example.invalid/live")], "unavailable", None)) +rows = [] +for name, formats, _expected, _fid in cases: + row = select(formats) + row["case"] = name + rows.append(row) +json.dump({"version": yt_dlp.version.__version__, "rows": rows}, sys.stdout) +""" + + +def installed_ytdlp(): + """Interpreter and package directory of the yt-dlp shim the server would run.""" + try: + shim = server._resolve_yt_dlp() + except RuntimeError: + pytest.skip("installed yt-dlp not visible") + shim_path = Path(shim) + try: + first = shim_path.read_text(encoding="utf-8", errors="replace").splitlines()[0] + except OSError: + pytest.skip("installed yt-dlp not visible") + if not first.startswith("#!"): + pytest.skip("installed yt-dlp not visible") + interpreter = Path(first[2:].strip().split()[0]) + if not interpreter.is_file() or not os.access(interpreter, os.X_OK): + pytest.skip("installed yt-dlp not visible") + package = None + for candidate in sorted((interpreter.parent.parent / "lib").glob("python*/site-packages")): + if (candidate / "yt_dlp" / "__init__.py").is_file(): + package = candidate + break + if package is None: + pytest.skip("installed yt-dlp not visible") + return interpreter, package + + +def test_d2b_installed_ytdlp_format_selector(tmp_path, capsys): + interpreter, package = installed_ytdlp() + cache_dir = tmp_path / "cache" + config_dir = tmp_path / "config" + cache_dir.mkdir() + config_dir.mkdir() + script = tmp_path / "format_select.py" + script.write_text(FORMAT_CASES) + env = os.environ.copy() + env["PYTHONDONTWRITEBYTECODE"] = "1" + env["XDG_CACHE_HOME"] = str(cache_dir) + env["XDG_CONFIG_HOME"] = str(config_dir) + completed = subprocess.run( + [str(interpreter), "-I", "-B", str(script), str(package), server.GUEST_VIDEO_FORMAT], + cwd=str(tmp_path), + env=env, + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert completed.returncode == 0, completed.stderr[-500:] + payload = json.loads(completed.stdout) + print("yt-dlp version:", payload["version"]) + expected = { + "rtmp-only": ("unavailable", None), + "prefer-https": ("selected", "short"), + "m3u8_native": ("selected", "m3u8-native"), + "m3u8": ("selected", "m3u8"), + "http_dash_segments": ("selected", "dash"), + "http": ("selected", "http"), + "missing-protocol": ("unavailable", None), + } + for protocol in ("rtmp", "rtmpe", "rtsp", "mms", "websocket_frag", "f4m", "ism", "mhtml", "fc2_live", "niconico_live"): + expected[protocol] = ("unavailable", None) + assert {row["case"] for row in payload["rows"]} == set(expected) + for row in payload["rows"]: + status, format_id = expected[row["case"]] + assert row["status"] == status + if status == "unavailable": + assert row["phrase"] is True + assert row["exc"] in {"ExtractorError", "DownloadError"} + else: + assert row["format_id"] == format_id + if row["case"] == "prefer-https": + assert row["protocol"] == "https" + assert row["height"] == 360 + + +def test_d2b_unavailable_format_error_is_mapped_for_guests_only(tmp_path, monkeypatch): + calls = [] + install_download_fakes(monkeypatch, tmp_path / "input", calls) + + def fail(argv, **kwargs): + calls.append((list(argv), kwargs)) + return subprocess.CompletedProcess( + argv, 1, stdout="prefix ", stderr="Requested format is not available", + ) + + monkeypatch.setattr(server.subprocess, "run", fail) + with pytest.raises(ValueError, match=UNSAFE_FORMAT_ERROR): + server.fetch_video_url("https://example.invalid/clip", "slot", shared_cookies=False) + with pytest.raises(ValueError, match="下載失敗") as caught: + server.fetch_video_url("https://example.invalid/clip", "slot", shared_cookies=True) + assert UNSAFE_FORMAT_ERROR not in str(caught.value) + + +def test_h3_keyed_name_is_stable_and_not_content_derived(tmp_path): + helper = H3ProviderWorkerTests() + helper.path = tmp_path / "avatar.png" + helper.path.write_bytes(b"h3-avatar") + helper.observed = [] + key = bytes(range(32)) + other_key = bytes(range(32, 64)) + + def make(upload_key): + return H3SubmissionProcessor( + lambda owner, asset: helper.path, + helper.executor, + profile_resolver=helper.profile, + upload_name_key=upload_key, + ) + + bundle = helper.bundle() + make(key)(bundle) + make(key)(bundle) + first, second = helper.observed + digest = hashlib.sha256(b"h3-avatar").hexdigest() + assert first.upload_basename == second.upload_basename + assert first.graph_sha256 == second.graph_sha256 + assert first.upload_basename == h3_upload_basename(key, digest, ".png") + assert SAFE_UPLOAD.fullmatch(first.upload_basename) + assert first.upload_basename != "castle_h3_" + digest[:32] + ".png" + make(other_key)(bundle) + assert helper.observed[-1].upload_basename != first.upload_basename + assert h3_upload_basename(other_key, digest, ".png") != first.upload_basename + plain = H3SubmissionProcessor( + lambda owner, asset: helper.path, + helper.executor, + profile_resolver=helper.profile, + ) + assert isinstance(plain._upload_name_key, bytes) and len(plain._upload_name_key) == 32 + with pytest.raises(ValueError): + H3SubmissionProcessor( + lambda owner, asset: helper.path, + helper.executor, + profile_resolver=helper.profile, + upload_name_key=b"\x00" * 31, + ) + with pytest.raises(DefiniteLocalFailure, match="H3 asset digest is invalid"): + h3_upload_basename(key, "A" * 64, ".png") + with pytest.raises(ValueError): + h3_upload_basename(b"\x00" * 31, digest, ".png") + + +def write_key(path, payload, mode): + path.write_bytes(payload) + os.chmod(path, mode) + + +def test_h3_upload_name_key_file(tmp_path): + created = tmp_path / "created.key" + first = load_or_create_upload_name_key(created) + info = created.lstat() + assert stat.S_ISREG(info.st_mode) and not stat.S_ISLNK(info.st_mode) + assert info.st_size == 32 and (info.st_mode & 0o777) == 0o600 + assert len(first) == 32 + assert load_or_create_upload_name_key(created) == first + + reused = tmp_path / "reused.key" + payload = bytes(range(32)) + write_key(reused, payload, 0o600) + inode = reused.lstat().st_ino + assert load_or_create_upload_name_key(reused) == payload + assert reused.read_bytes() == payload and reused.lstat().st_ino == inode + + target = tmp_path / "target.key" + write_key(target, payload, 0o600) + linked = tmp_path / "linked.key" + linked.symlink_to(target) + short = tmp_path / "short.key" + write_key(short, b"x" * 31, 0o600) + grouped = tmp_path / "grouped.key" + write_key(grouped, payload, 0o640) + for path in (linked, short, grouped): + with pytest.raises(RuntimeError, match=KEY_ERROR): + load_or_create_upload_name_key(path) + + raced = tmp_path / "race" + raced.mkdir() + key_path = raced / "h3-upload-name.key" + barrier = threading.Barrier(2) + found, errors = [], [] + lock = threading.Lock() + + def worker(): + barrier.wait() + try: + value = load_or_create_upload_name_key(key_path) + except Exception as exc: + with lock: + errors.append(type(exc).__name__) + return + with lock: + found.append(value) + + threads = [threading.Thread(target=worker) for _ in range(2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert errors == [] + assert len(found) == 2 and found[0] == found[1] and len(found[0]) == 32 + assert [item.name for item in raced.iterdir()] == ["h3-upload-name.key"] + + + + +@pytest.mark.parametrize("new_name", ["Castle_x.png", "LIBRARY_x.png"]) +def test_kr_reserved_input_rename_is_refused(state, new_name): + status, body, source, destination = rename_input(state, "clip.png", new_name) + assert status == 400 + assert body == {"ok": False, "error": RESERVED_RENAME_ERROR} + assert source.read_bytes() == b"synthetic-fixture" + assert not destination.exists() + + +def test_kr_ordinary_input_rename_stays_allowed(state): + status, body, source, destination = rename_input(state, "clip.mp4", "my_clip.mp4", payload=b"clip-bytes") + assert status == 200 and body["ok"] is True + assert not source.exists() + assert destination.read_bytes() == b"clip-bytes" + + +def test_kr_output_may_still_use_staged_prefix(state): + status, body, source, destination = rename_input(state, "clip.png", "castle_x.png", view_type="output") + assert status == 200 and body["ok"] is True + assert not source.exists() + assert destination.read_bytes() == b"synthetic-fixture" + + +def test_kr_staged_input_may_be_renamed_to_an_ordinary_name(state): + old = "castle_colab_" + "ab" * 16 + ".png" + status, body, source, destination = rename_input(state, old, "clip.png") + assert status == 200 and body["ok"] is True + assert not source.exists() + assert destination.name == "clip.png" + assert destination.read_bytes() == b"synthetic-fixture" diff --git a/scripts/test_session_controls_r38.js b/scripts/test_session_controls_r38.js new file mode 100644 index 0000000..52d6be2 --- /dev/null +++ b/scripts/test_session_controls_r38.js @@ -0,0 +1,18 @@ +'use strict'; +const fs=require('fs'),vm=require('vm'),assert=require('assert'),path=require('path'); +const source=fs.readFileSync(path.join(__dirname,'../webui/static/compute-settings.js'),'utf8'); +const fn=source.slice(source.indexOf(' function sessionControls(){'),source.indexOf(' async function run(')); +function render(snapshot){ + const ctx={colabSession:snapshot,el:(tag,props,children=[])=>({tag,...props,children}),button:(text,click,props)=>({tag:'button',text,...props}),label:(text,child)=>({tag:'label',text,children:[child]}),run:()=>{throw Error('no operations')},api:()=>{throw Error('no network')}}; + vm.runInNewContext(fn+';result=sessionControls()',ctx); + return {status:ctx.result.children[0].text,open:ctx.result.children[1].children[0]}; +} +let result=render({session:{phase:'closed',close_requested:true}}); +assert.equal(result.status,'未開啟');assert.equal(result.open.text,'開啟工作階段');assert.equal(result.open.disabled,false); +for(const phase of ['closing','stopping','released_unsettled']){ + result=render({session:{phase,close_requested:false}});assert.equal(result.status,'關閉中');assert.equal(result.open.disabled,true); +} +for(const snapshot of [null,{}, {session:{}},{session:{phase:'surprise'}}]){ + result=render(snapshot);assert.equal(result.status,'工作階段狀態暫時無法確認');assert.equal(result.open.disabled,true); +} +console.log('session controls: 8 offline regressions passed'); diff --git a/scripts/test_session_safety_r35.py b/scripts/test_session_safety_r35.py new file mode 100644 index 0000000..859b21d --- /dev/null +++ b/scripts/test_session_safety_r35.py @@ -0,0 +1,227 @@ +"""Additional offline boundaries: sweeper, shutdown meter, actual voice paths.""" +import ast +from contextlib import contextmanager +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +from types import SimpleNamespace +import pytest +from test_review_r35 import rig, allocated, job, Crash, CANDIDATE +from test_compute_r35 import load_worker +from scripts.colab_lease_sweeper import sweep +from colab_service import BridgeError + + +def test_deadline_committed_before_post_and_immediate_watchdog(rig,monkeypatch): + s,b,clock,account,state=rig + original=s._call + def checked(state,op,**kw): + if op=='runtime_allocate': + persisted=s.sessions.get(state['id']) + assert persisted['deadline_epoch']==clock[0]+21600 + assert persisted['allocation_id']==kw['allocation_id'] + return original(state,op,**kw) + monkeypatch.setattr(s,'_call',checked) + s.sessions.tick_all() + final=s.sessions.get(state['id']) + assert final['watchdog_armed'] and final['phase']=='uploading' + assert [op for op,_ in b.calls if op in {'runtime_allocate','remote_exec'}]==['runtime_allocate','remote_exec'] + + +@pytest.mark.parametrize('age',[1,7*3600]) +def test_independent_sweeper_recovers_pre_arm_gap(rig,monkeypatch,age): + s,b,clock,account,state=rig + monkeypatch.setattr(s.sessions,'assigned',lambda *a:(_ for _ in ()).throw(Crash())) + with pytest.raises(Crash):s.sessions.tick_all() + b.found=True;clock[0]+=age;before=len(b.calls) + assert sweep(s.root,b,s.clock) + final=s.sessions.get(state['id']) + assert final['released'] and final['phase']=='closed' + assert final['deadline_epoch']==state['created_at']+21600 + assert {op for op,_ in b.calls[before:]}<={'runtime_lookup','runtime_stop','account_status'} + + +def test_sweeper_obeys_same_worker_flock(rig): + s,b,clock,account,state=rig + allocated(rig);clock[0]+=301 + before=len(b.calls) + with (s.root/'worker.lock').open('a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + assert sweep(s.root,b,s.clock) is False + assert len(b.calls)==before + assert sweep(s.root,b,s.clock) + assert s.sessions.get(state['id'])['released'] + + +def test_stop_confirmed_balance_unavailable_remains_reserved(rig,monkeypatch): + s,b,clock,account,state=rig;state=allocated(rig) + j=job(rig,state['id'],'cleanup_pending',runtime_id=state['runtime_id'],outcome='failed') + state=s.sessions.save(state['id'],active_job=j['id'],phase='closing') + b.balance-=2;b.stop_cost=1 + original=s._call;stopped=[False];missing=[True] + def bridge(state,op,**kw): + if op=='account_status' and stopped[0] and missing[0]:raise BridgeError() + result=original(state,op,**kw) + if op=='runtime_stop':stopped[0]=True + return result + monkeypatch.setattr(s,'_call',bridge) + s.sessions.release(state) + line=s.sessions.snapshot('owner')['session_ledger'][0] + assert line['amount'] is None and not line['settled'] + assert s.sessions.get(state['id'])['phase']=='released_unsettled' + assert not s.job('owner',j['id'])['released'] + s.sessions.tick_all();assert len([op for op,_ in b.calls if op=='runtime_stop'])==1 + missing[0]=False;s.sessions.tick_all() + final=s.sessions.get(state['id']) + assert final['phase']=='closed' and final['job_units']==2 and final['session_units']==1 + assert final['units_observed']==3 and s.job('owner',j['id'])['units_observed']==2 + + +def test_live_but_overlong_bootstrap_never_renews_heartbeat(rig,monkeypatch): + s,b,clock,account,state=rig;state=allocated(rig,'bootstrap') + clock[0]+=1801;s.sessions.save(state['id'],last_tick=clock[0]) + original=s._exec;codes=[] + def remote(state,code): + codes.append(code) + if 'bootstrap-status.json' in code:return {'phase':'running','alive':True,'progress_at':clock[0],'identity':{'pid':1,'start_ticks':'123'}} + return original(state,code) + monkeypatch.setattr(s,'_exec',remote) + s.sessions.tick_all() + assert s.sessions.get(state['id'])['released'] + assert s.sessions.get(state['id'])['reason']=='bootstrap_timeout' + assert not any("'heartbeat':True" in code for code in codes) + + +def test_cancel_during_balance_check_blocks_post(rig,monkeypatch): + s,b,clock,account,state=rig + original=s._call + def call(state,op,**kw): + if op=='account_status': + s.sessions.close('owner') + s.sessions.settings('owner',{'idle_minutes':37}) + return original(state,op,**kw) + monkeypatch.setattr(s,'_call',call) + s.sessions.tick_all() + final=s.sessions.get(state['id']) + assert final['close_requested'] and final['settings']['idle_minutes']==37 + assert not any(op=='runtime_allocate' for op,_ in b.calls) + + +@pytest.mark.parametrize('marker',[{}, {'clean':True}, {'clean':True,'job_id':'wrong','manifest_sha256':'wrong'}]) +def test_missing_or_mismatched_cleanup_proof_closes_lease(rig,monkeypatch,marker): + s,b,clock,account,state=rig;state=allocated(rig) + j=job(rig,state['id'],'cleanup_pending',runtime_id=state['runtime_id'],outcome='completed',manifest_sha256='a'*64) + s.sessions.save(state['id'],active_job=j['id']) + monkeypatch.setattr(s,'_exec',lambda *a:marker) + s.sessions.finish_job(j) + assert s.sessions.get(state['id'])['released'] + assert s.sessions.get(state['id'])['reason']=='isolation_unproven' + assert not s.job('owner',j['id']).get('session_runtime_retained') + + +def test_success_meter_and_handoff_roll_back_together(rig,monkeypatch): + s,b,clock,account,state=rig;state=allocated(rig) + j=job(rig,state['id'],'cleanup_pending',runtime_id=state['runtime_id'],outcome='completed',manifest_sha256='a'*64) + s.sessions.save(state['id'],active_job=j['id']);b.balance-=2 + monkeypatch.setattr(s,'_exec',lambda *a:{'clean':True,'job_id':j['id'],'manifest_sha256':'a'*64}) + real_db=s.db + class DB: + def __init__(self,db):self.db=db + def execute(self,sql,args=()): + result=self.db.execute(sql,args) + if sql.startswith('UPDATE work_sessions') and json.loads(args[0]).get('active_job') is None:raise Crash() + return result + @contextmanager + def crashing(): + with real_db() as db:yield DB(db) + with monkeypatch.context() as m: + m.setattr(s,'db',crashing) + with pytest.raises(Crash):s.sessions.finish_job(j) + assert not s.job('owner',j['id'])['released'] and s.job('owner',j['id'])['units_observed']==0 + assert s.sessions.get(state['id'])['active_job']==j['id'] + s.sessions.finish_job(j) + assert s.job('owner',j['id'])['released'] and s.job('owner',j['id'])['units_observed']==2 + assert s.sessions.get(state['id'])['active_job'] is None + + +def test_actual_persona_consumer_uses_job_cache_view(tmp_path,monkeypatch): + worker=load_worker(monkeypatch) + root=tmp_path/'job';root.mkdir();session=tmp_path/'session';(session/'cache').mkdir(parents=True) + cache=worker.cache_view(root,session) + (root/'comfy-input/reference.wav').write_bytes(b'offline fixture') + (cache/'voice-export.json').write_text(json.dumps({'persona':'test','reference_name':'reference.wav','reference_text':''})) + p=CANDIDATE/'scripts/colab_remote/native_voice_node.py' + tree=ast.parse(p.read_text());cls=next(n for n in tree.body if isinstance(n,ast.ClassDef) and n.name=='CastleBreezyVoiceTTS') + class Captured(Exception):pass + def capture(args,**kw): + request=json.loads(Path(args[-1]).read_text()) + assert Path(request['reference']).resolve()==root/'comfy-input/reference.wav' + assert Path(request['reference']).is_file() + raise Captured() + scope={'Path':Path,'os':os,'json':json,'tempfile':tempfile,'__file__':str(p), + 'subprocess':SimpleNamespace(run=capture,DEVNULL=-3)} + exec(compile(ast.Module(body=[cls],type_ignores=[]),str(p),'exec'),scope) + monkeypatch.setenv('CASTLE_PARITY_CACHE',str(cache)) + with pytest.raises(Captured):scope['CastleBreezyVoiceTTS']().synth('test','') + + +def test_real_cpu_process_group_is_gone_before_cleanup(tmp_path,monkeypatch): + worker=load_worker(monkeypatch) + proc=subprocess.Popen([sys.executable,'-c','import time; time.sleep(120)'],start_new_session=True) + try: + worker.stop_group(proc) + assert proc.poll() is not None + with pytest.raises(ProcessLookupError):os.killpg(proc.pid,0) + finally: + if proc.poll() is None:proc.kill();proc.wait() + + +def test_private_view_cleanup_failure_is_not_proof(tmp_path,monkeypatch): + worker=load_worker(monkeypatch);root=tmp_path/'job';root.mkdir() + private=root/'cache';private.mkdir();(private/'voice-export.json').write_text('{}') + monkeypatch.setattr(worker.shutil,'rmtree',lambda path:None) + with pytest.raises(RuntimeError):worker.clean_job(root,None) + assert private.exists() and not (root/'reusable-clean.json').exists() + + +def test_cancel_auto_session_job_inside_dispatch_transaction(rig,monkeypatch): + s,b,clock,account,state=rig + j=job(rig,state['id']);s.sessions.save(state['id'],admission_created=True) + original=s._call + def call(state,op,**kw): + if op=='account_status':s.cancel('owner',j['id']) + return original(state,op,**kw) + monkeypatch.setattr(s,'_call',call) + s.sessions.tick_all();s.sessions.tick_all() + assert s.sessions.get(state['id'])['phase']=='closed' + assert not any(op=='runtime_allocate' for op,_ in b.calls) + + + + +def test_web_reconciler_retries_startup_sweeper_lock(rig,monkeypatch): + import colab_service + s,*_=rig;attempts=[];sleeps=[] + def flock(*a): + attempts.append(True) + if len(attempts)==1:raise BlockingIOError() + raise Crash() # Stop before any reconciliation/provider work. + monkeypatch.setattr(colab_service.file_lock,'flock',flock) + monkeypatch.setattr(colab_service.time,'sleep',sleeps.append) + with pytest.raises(Crash):s._loop() + assert len(attempts)==2 and sleeps==[1] + + +def test_recovered_unarmed_runtime_after_heartbeat_gap_is_released(rig): + s,b,clock,account,state=rig + b.uncertain=True;s.sessions.tick_all() + before=s.sessions.get(state['id']) + clock[0]+=301;b.found=True;s.sessions.tick_all() + final=s.sessions.get(state['id']) + assert final['phase']=='closed' and final['deadline_epoch']==before['deadline_epoch'] + assert not any(op=='remote_exec' for op,_ in b.calls) + assert len([op for op,_ in b.calls if op=='runtime_allocate'])==1 diff --git a/tests/conftest.py b/tests/conftest.py index 7ea69cb..8bae771 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -17,6 +17,13 @@ def isolated_comfy_admission(tmp_path, monkeypatch): monkeypatch.setenv('CASTLE_COMFY_ADMISSION_LOCK', str(tmp_path / 'comfy-admission.lock')) +class SyntheticServer(tuple): + def __new__(cls, base, opener, cookie, root): + result = super().__new__(cls, (base, opener, cookie)) + result.root = root + return result + + @pytest.fixture(scope="module") def test_server(tmp_path_factory, request): tmp_path = tmp_path_factory.mktemp("test_server") @@ -42,6 +49,9 @@ def do_POST(self): env = {key: os.environ[key] for key in ('PATH', 'HOME', 'LANG') if key in os.environ} env.update({ 'COMFY_HOME': str(tmp_path / 'comfy'), + 'CASTLE_COLAB_ROOT': str(tmp_path / 'colab'), + 'CASTLE_PROVIDER_DATABASE_PATH': str(tmp_path / 'provider-fabric.sqlite3'), + 'CASTLE_PROVIDER_CREDENTIAL_ROOT': str(tmp_path / 'provider-secrets'), 'COMFYUI_URL': f'http://127.0.0.1:{comfy.server_port}', 'WEB_COMFYUI_DATA_DIR': str(tmp_path / 'data'), 'WEB_COMFYUI_CACHE_DIR': str(tmp_path / 'cache'), @@ -84,7 +94,7 @@ def do_POST(self): cookie_header = cookies[0].split(';')[0] - yield base, opener, cookie_header + yield SyntheticServer(base, opener, cookie_header, tmp_path) finally: if process is not None: process.terminate() @@ -92,3 +102,41 @@ def do_POST(self): except subprocess.TimeoutExpired: process.kill(); process.wait(timeout=5) comfy.shutdown(); comfy.server_close() + + +@pytest.fixture(autouse=True) +def enable_colab_browser_fixture(request): + """Enable the synthetic Colab connection once its browser login completes.""" + if (request.path.name != 'test_colab_browser.py' or + not request.node.name.startswith('test_colab_real_http_login_admission_and_cancel[')): + yield + return + + base, opener, cookie = request.getfixturevalue('test_server') + headers = {'Content-Type': 'application/json', 'Origin': base, 'Cookie': cookie} + stop = threading.Event() + def enable(): + while not stop.wait(0.01): + try: + req = urllib.request.Request(base + '/api/compute/connections', headers=headers) + with opener.open(req, timeout=5) as response: + cards = json.load(response)['connections'] + colab = next(card for card in cards if card['provider'] == 'colab') + if not colab['credential_present']: + continue + req = urllib.request.Request(base + '/api/compute/connections/colab', + data=json.dumps({'revision': colab['revision'], 'use_enabled': True}).encode(), + headers=headers, method='PATCH') + with opener.open(req, timeout=5) as response: + json.load(response) + return + except (OSError, KeyError, StopIteration): + continue + + thread = threading.Thread(target=enable, daemon=True) + thread.start() + yield + stop.set() + thread.join(timeout=10) + if thread.is_alive(): + pytest.fail('Synthetic Colab connection setup did not stop') diff --git a/tests/test_colab_bridge.py b/tests/test_colab_bridge.py index ec95336..baf98ae 100644 --- a/tests/test_colab_bridge.py +++ b/tests/test_colab_bridge.py @@ -337,7 +337,7 @@ def test_allocation_records_identity_before_transport_and_never_retries(setup): assert error["error"]["ambiguous"] is True assert "SECRET" not in json.dumps(error) saved = bridge.private_json(account / "runtimes" / (runtime_id + ".json")) - assert saved["state"] == "allocating" + assert saved["state"] == "allocation_uncertain" assert saved["accelerator"] == "G4" error = call("runtime_allocate", allocation_id=runtime_id, gpu="G4") assert error["error"]["code"] == "allocation_already_attempted" @@ -427,8 +427,10 @@ def test_remote_exec_persists_kernel_and_redacts_transport_secrets(setup): "text": "result private-proxy-token private-access-token private-refresh-token"}] result = call("remote_exec", runtime_id=runtime_id, code="print('status')", timeout_seconds=30) assert result["result"]["stdout"] == "result [redacted] [redacted] [redacted]" - assert sdk.calls[-2:] == [("exec", "print('status')", {"allow_stdin": False, "timeout": 30}), - ("close", {"shutdown_kernel": False})] + assert sdk.calls[-2][:2] == ("exec", "print('status')") + assert sdk.calls[-2][2]["allow_stdin"] is False + assert 1 <= sdk.calls[-2][2]["timeout"] <= 30 + assert sdk.calls[-1] == ("close", {"shutdown_kernel": False}) saved = bridge.private_json(account / "runtimes" / (runtime_id + ".json")) assert (saved["kernel_id"], saved["session_id"]) == ("kernel-1", "session-1") @@ -520,7 +522,7 @@ def conflict(method, url, **kwargs): sdk.request = conflict result = call("upload", runtime_id=runtime_id, local_path=str(source), remote_path="/content/web-comfyui/job/input.png") - assert result["error"]["code"] == "invalid_remote_directory" + assert result["error"]["code"] == "upload_transport_failed" assert len(calls) == 1 and calls[0]["json"] == {"type": "directory"} @@ -530,7 +532,7 @@ def test_remote_paths_are_contained(setup, tmp_path, remote): source = tmp_path / "input.png" source.write_bytes(b"x") result = call("upload", runtime_id=str(uuid.uuid4()), local_path=str(source), remote_path=remote) - assert result["error"]["code"] == "invalid_request" + assert result["error"]["code"] == "upload_local_invalid" assert not sdk.calls @@ -538,10 +540,10 @@ def test_credentials_and_symlinks_cannot_be_uploaded(setup, tmp_path): account, sdk, call = setup runtime_id = str(uuid.uuid4()) result = call("upload", runtime_id=runtime_id, local_path=str(account / "token.json"), remote_path="/content/token.json") - assert result["error"]["code"] == "private_path" + assert result["error"]["code"] == "upload_local_invalid" link = tmp_path / "input.png" link.symlink_to(account / "token.json") - assert call("upload", runtime_id=runtime_id, local_path=str(link), remote_path="/content/input.png")["error"]["code"] == "invalid_request" + assert call("upload", runtime_id=runtime_id, local_path=str(link), remote_path="/content/input.png")["error"]["code"] == "upload_local_invalid" assert not sdk.calls diff --git a/tests/test_comfyui_api_proxy.py b/tests/test_comfyui_api_proxy.py index 6fd8450..7558752 100644 --- a/tests/test_comfyui_api_proxy.py +++ b/tests/test_comfyui_api_proxy.py @@ -12,6 +12,7 @@ sys.path.insert(0, str(ROOT / 'webui')) import server +from test_compute_web import AdmitAllConsole def test_request_json_success(): with patch("urllib.request.urlopen") as mock_urlopen: @@ -106,7 +107,7 @@ def settimeout(self, timeout): assert messages == ["1234567890"] -def test_api_generate_submit_workflow(): +def test_api_generate_submit_workflow(tmp_path): # Exercise the real _generate_result delegate added to the HTTP handler. # Only the network and attribution sinks below are synthetic. class DummyHandler(server.Handler): @@ -125,6 +126,8 @@ def read_json(self, limit): } def current_user(self): return self._current_user + def _provider_console(self): + return AdmitAllConsole(self._current_user['email'], tmp_path / 'compute-preferences.sqlite3') def is_orchestrator_service_authenticated(self): return False def require_orchestrator_auth(self): diff --git a/tests/test_compute_browser.py b/tests/test_compute_browser.py index 7e8b811..f1d5498 100644 --- a/tests/test_compute_browser.py +++ b/tests/test_compute_browser.py @@ -188,7 +188,7 @@ def test_unified_placement_limits_jobs_and_small_layout(compute_page,width): page.get_by_text('生成中',exact=True).wait_for() assert len(submissions)==1 submitted=submissions[0] - assert submitted['placement']=='auto' and submitted['limits']=={'max_minutes':45,'max_units':15,'max_credits':60,'max_comfy_credits':100,'max_runninghub_coins':100,'account_id':account_id,'gpu':'A100'} + assert submitted['placement']=='auto' and submitted['limits']=={'max_minutes':45,'max_units':15,'max_credits':60,'max_comfy_credits':100,'max_runninghub_coins':100,'max_runninghub_points':1,'account_id':account_id,'gpu':'A100'} assert submitted['request']['files']['image']['data']=='synthetic-private-pixels' assert str(uuid.UUID(submitted['request_id']))==submitted['request_id'] actual=page.evaluate('window.receipts[0]');assert actual['lane']=='colab' and actual['downstream_id']==jobs[actual['request_id']]['downstream_id'] @@ -374,7 +374,7 @@ def test_hosted_provider_choice_uses_real_router_receipt_and_separate_budget(com previews,submissions,_,_,_,_=fake_router(page,hosted_ready=True) page.evaluate('window.mountCompute()');page.get_by_text('工作流:Qwen Image',exact=True).wait_for() selector=page.get_by_label('執行位置',exact=True) - assert selector.locator('option').count()==6 + assert selector.locator('option').count()==7 selector.select_option(lane) page.wait_for_function('window.ComputePlacement.getState(document.querySelector("form")).eligible') page.evaluate('window.submitCompute()');page.get_by_text('生成中',exact=True).wait_for() diff --git a/tests/test_compute_guided_browser.py b/tests/test_compute_guided_browser.py index 1a43063..309d039 100644 --- a/tests/test_compute_guided_browser.py +++ b/tests/test_compute_guided_browser.py @@ -5,105 +5,15 @@ import pytest from test_compute_browser import compute_page, fake_router +from test_provider_console import env +from test_provider_console_http import http_console from test_compute_management_browser import screenshot -def guided_api(page): - recipe={'feature_id':'text2img','recipe_id':'native-synthetic','label':'合成範本','output_kind':'image','estimated_cost':1, - 'workflow':{'6':{'class_type':'SyntheticNode','inputs':{'text':''}}},'partner_nodes':False, - 'bindings':[{'source':'prompt','node_id':'6','input':'text','default':'','value_map':[{'from':'a','to':'b'}]}], 'fixed_settings':{}} - existing={'feature_id':'img2img','recipe_id':'keep-this','label':'保留的其他配方','output_kind':'image','workflow_id':'123', - 'bindings':[{'source':'prompt','node_id':'1','input':'text'}],'fixed_settings':{},'estimated_cost':8,'verified':True} - providers={name:{'provider':name,'enabled':True,'endpoint':url,'credential_configured':True,'recipes':[existing.copy()]} for name,url in [('comfy_cloud','https://cloud.comfy.org'),('runninghub','https://www.runninghub.ai')]} - prefs={'default_placement':'local','feature_placements':{'img2img':'colab'}} - features=[{'id':key,'title':title,'providers':{lane:{'status':'unconfigured' if lane=='runninghub' else 'implemented','reason':'尚未設定此功能配方' if lane=='runninghub' else '已提供此功能契約'} for lane in ['local','colab','autoip','comfy_cloud','runninghub']}} for key,title in [('text2img','文字生圖'),('img2img','指令改圖')]] - writes=[] - def respond(route): - path=route.request.url.split('/api/compute/',1)[1] - if path=='recipe-catalog':route.fulfill(json={'templates':[{'id':'synthetic-template','label':'合成生圖範本','feature_id':'text2img','description':'沿用原生表單語意。','recipe':recipe,'requirements':['需要合成測試模型與節點'],'input_slots':[],'validation':'contract_tested','cost_requires_input':True}]});return - if path=='capabilities':route.fulfill(json={'features':features});return - if path=='preferences': - if route.request.method=='POST':prefs.update(route.request.post_data_json);writes.append(('preferences',route.request.post_data_json)) - route.fulfill(json={'ok':True,**prefs});return - if path=='providers':route.fulfill(json={'providers':list(providers.values())});return - if path.startswith('providers/'): - name=path.split('/')[1];body=route.request.post_data_json;writes.append((name,body));providers[name].update(body);route.fulfill(json={'provider':providers[name]});return - route.fallback() - page.route('**/api/compute/**',respond) - return recipe,existing,providers,prefs,writes -@pytest.mark.parametrize('width',[390,768,1440]) -def test_guided_template_setup_merges_recipes_and_requires_real_estimate(compute_page,tmp_path,width): - page,errors=compute_page;page.set_viewport_size({'width':width,'height':900}) - recipe,existing,providers,_,writes=guided_api(page) - base=page.url.split('/compute-fixture')[0];page.goto(base+'/#/admin') - page.get_by_role('button',name='運算平台',exact=True).click() - page.get_by_label('設定項目',exact=True).select_option('templates') - page.get_by_label('功能範本',exact=True).select_option('synthetic-template') - assert page.get_by_label('每次預估用量',exact=True).input_value()=='' - page.get_by_label('已確認平台具備列出的模型與節點',exact=True).check() - page.get_by_role('button',name='儲存功能配方',exact=True).click() - assert not writes - page.get_by_label('每次預估用量',exact=True).fill('12.5') - page.get_by_role('button',name='儲存功能配方',exact=True).click() - page.get_by_text('功能配方已儲存;其他功能配方已保留,尚未啟動生成。',exact=True).wait_for() - assert len(writes)==1 and writes[0][0]=='comfy_cloud' - saved=writes[0][1]['recipes'];assert len(saved)==2 - assert saved[0]=={key:value for key,value in existing.items() if key!='verified'} - assert saved[1]=={**recipe,'estimated_cost':12.5} - assert page.get_by_label('替換此功能現有配方',exact=True).is_visible() - page.get_by_label('每次預估用量',exact=True).fill('15') - page.get_by_label('已確認平台具備列出的模型與節點',exact=True).check() - page.get_by_role('button',name='儲存功能配方',exact=True).click();assert len(writes)==1 - page.get_by_label('替換此功能現有配方',exact=True).check() - page.get_by_role('button',name='儲存功能配方',exact=True).click() - page.get_by_text('功能配方已儲存;其他功能配方已保留,尚未啟動生成。',exact=True).wait_for() - assert len(writes)==2 and len(writes[-1][1]['recipes'])==2 - page.get_by_label('平台',exact=True).select_option('runninghub') - page.get_by_label('RunningHub 已發布工作流 ID',exact=True).wait_for() - with page.expect_download() as download_info:page.get_by_role('button',name='下載工作流供發布',exact=True).click() - download_path=tmp_path/'downloaded-graph.json';download_info.value.save_as(str(download_path)) - assert json.loads(download_path.read_text())==recipe['workflow'] - page.get_by_label('RunningHub 已發布工作流 ID',exact=True).fill('998877') - page.get_by_label('每次預估用量',exact=True).fill('9') - page.get_by_label('已確認平台具備列出的模型與節點',exact=True).check() - assert '尚未在你的平台或 GPU 實跑' in page.get_by_role('dialog').inner_text() - screenshot(page,f'guided-template-{width}.png') - page.get_by_role('button',name='儲存功能配方',exact=True).click() - page.get_by_text('功能配方已儲存;其他功能配方已保留,尚未啟動生成。',exact=True).wait_for() - rh=writes[-1][1]['recipes'][-1] - assert writes[-1][0]=='runninghub' and rh['workflow_id']=='998877' - assert 'workflow' not in rh and 'partner_nodes' not in rh - assert rh['bindings']==recipe['bindings'] and rh['estimated_cost']==9 - assert page.evaluate('document.documentElement.scrollWidth<=innerWidth') - assert not errors,errors -@pytest.mark.parametrize('width',[390,768,1440]) -def test_capability_overview_and_private_placement_preferences(compute_page,width): - page,errors=compute_page;page.set_viewport_size({'width':width,'height':900}) - _,_,_,prefs,writes=guided_api(page) - base=page.url.split('/compute-fixture')[0];page.goto(base+'/#/admin') - page.get_by_role('button',name='運算平台',exact=True).click() - page.get_by_label('設定項目',exact=True).select_option('capabilities') - page.get_by_label('搜尋可用功能',exact=True).fill('文字') - page.get_by_label('篩選平台',exact=True).select_option('runninghub') - page.get_by_text('尚未設定此功能配方',exact=True).wait_for() - assert page.locator('.compute-capability-row').count()==1 - assert page.locator('[data-capability-lane]').count()==1 - screenshot(page,f'guided-capabilities-{width}.png') - page.get_by_label('設定項目',exact=True).select_option('preferences') - page.get_by_label('一般預設位置',exact=True).select_option('auto') - page.get_by_label('指定功能',exact=True).select_option('text2img') - page.get_by_label('此功能預設位置',exact=True).select_option('runninghub') - page.get_by_role('button',name='儲存預設安排',exact=True).click() - page.get_by_text('預設安排已儲存;現有表單與任務維持原選擇。',exact=True).wait_for() - assert writes==[('preferences',{'default_placement':'auto','feature_placements':{'img2img':'colab','text2img':'runninghub'}})] - assert prefs['default_placement']=='auto' - screenshot(page,f'guided-preferences-{width}.png') - assert page.evaluate('document.documentElement.scrollWidth<=innerWidth') - assert not errors,errors def test_saved_default_and_manual_choice_win_over_delayed_preferences(compute_page): @@ -217,16 +127,6 @@ def respond(route): assert not errors -def test_member_preferences_excludes_credential_management(compute_page): - page,errors=compute_page;guided_api(page) - base=page.url.split('/compute-fixture')[0];page.goto(base+'/#/studio/qwen21-text2img') - page.wait_for_function('window.castleTimers && foregroundRefreshes.size === 0') - page.evaluate("() => {currentUser={...currentUser,role:'user',operator:false};openComputeSettings(document.querySelector('#identityChip'),'preferences');}") - choices=page.get_by_label('設定項目',exact=True) - assert choices.locator('option').all_text_contents()==['可用功能','預設安排'] - assert page.get_by_label('API 金鑰',exact=True).is_hidden() - assert page.get_by_label('一般預設位置',exact=True).is_visible() - assert not errors def test_voice_quick_recipe_compiles_video_input_and_dynamic_step_ids(compute_page,monkeypatch): @@ -290,26 +190,6 @@ def pipelines(route): assert not errors,errors -def test_platform_switch_and_partial_save_preserve_stored_key_and_recipes(compute_page): - page,errors=compute_page;_,existing,providers,_,writes=guided_api(page) - page.goto(page.url.split('/compute-fixture')[0]+'/#/admin') - page.get_by_role('button',name='運算平台',exact=True).click() - page.get_by_text('金鑰已設定;連線與配方仍會在使用時檢查。',exact=True).wait_for() - page.get_by_label('API 金鑰',exact=True).fill('synthetic-unsaved-key') - page.get_by_label('平台',exact=True).select_option('runninghub') - page.get_by_text('金鑰已設定;連線與配方仍會在使用時檢查。',exact=True).wait_for() - page.get_by_label('平台',exact=True).select_option('comfy_cloud') - page.get_by_label('平台網址',exact=True).wait_for() - assert page.get_by_label('API 金鑰',exact=True).input_value()=='' and not writes - assert providers['comfy_cloud']['credential_configured'] is True - page.get_by_label('啟用此平台',exact=True).uncheck() - page.get_by_role('button',name='儲存平台設定',exact=True).click() - page.get_by_text('平台設定已儲存;尚未啟動生成。',exact=True).wait_for() - assert writes==[('comfy_cloud',{'enabled':False,'endpoint':'https://cloud.comfy.org'})] - assert providers['comfy_cloud']['credential_configured'] is True - assert providers['comfy_cloud']['recipes']==[existing] - assert 'synthetic-unsaved-key' not in page.locator('body').inner_text() - assert not errors,errors def test_switching_back_to_builtin_ignores_hidden_custom_required_fields(compute_page): @@ -326,3 +206,39 @@ def test_switching_back_to_builtin_ignores_hidden_custom_required_fields(compute page.get_by_label('圖片製作影片執行位置',exact=True).select_option('autoip') assert page.get_by_label('AutoIP 影片秒數',exact=True).is_enabled() assert not errors,errors + + +def test_member_console_shows_only_own_connection_state(http_console): + import shutil + from test_provider_console import write + h = http_console + write(h.env.console('owner@example.invalid', 'admin'), p='comfy_cloud', secret='synthetic-' + 'test-key-1') + write(h.env.console('bob@example.test'), p='comfy_cloud', secret='synthetic-' + 'test-key-2') + playwright = pytest.importorskip('playwright.sync_api') + with playwright.sync_playwright() as p: + browser = p.chromium.launch(headless=True, executable_path=shutil.which('chromium'), args=['--no-sandbox', '--disable-dev-shm-usage']) + context = browser.new_context() + context.add_cookies([{'name': 'castle_comfy_session', 'value': h.sessions['other@example.invalid'], 'url': h.origin}]) + page = context.new_page() + errors = [] + page.on('pageerror', lambda e: errors.append(str(e))) + page.goto(h.origin, wait_until='domcontentloaded') + page.wait_for_function("currentUser?.email === 'other@example.invalid'") + page.evaluate("openComputeSettings(document.getElementById('accountMenuBtn'))") + page.locator('.console-card').first.wait_for() + assert page.get_by_role('button', name='平台管理', exact=True).count() == 0 + cloud = page.locator('[data-provider=comfy_cloud]') + assert cloud.get_by_role('button', name='儲存金鑰', exact=True).count() == 1 + assert cloud.get_by_role('button', name='更換金鑰', exact=True).count() == 0 + write(h.env.console('other@example.invalid'), secret='synthetic-' + 'test-key-3') + page.keyboard.press('Escape') + page.evaluate("openComputeSettings(document.getElementById('accountMenuBtn'))") + page.locator('[data-provider=runninghub]').get_by_role('button', name='更換金鑰', exact=True).wait_for() + assert page.locator('[data-provider=comfy_cloud]').get_by_role('button', name='更換金鑰', exact=True).count() == 0 + text = page.locator('.compute-settings').inner_text() + for value in ('owner@example.invalid', 'bob@example.test', 'synthetic-test-key-1', 'synthetic-test-key-2', 'synthetic-test-key-3'): + assert value not in text + assert page.locator('input[type=password]').evaluate_all('(els)=>els.every(el=>!el.value)') + assert not h.calls + assert not errors, errors + browser.close() diff --git a/tests/test_compute_http.py b/tests/test_compute_http.py index 770b364..aeda00a 100644 --- a/tests/test_compute_http.py +++ b/tests/test_compute_http.py @@ -4,6 +4,7 @@ import urllib.request import urllib.error import pytest +from test_compute_web import enable_colab_for_fixture @pytest.mark.parametrize('test_server', ['colab_transport'], indirect=True) @@ -14,7 +15,11 @@ def call(path, body=None, authenticated=True): if authenticated: headers['Cookie'] = cookie req = urllib.request.Request(base+path, headers=headers, data=json.dumps(body).encode() if body is not None else None) - with opener.open(req, timeout=15) as response: return json.load(response) + with opener.open(req, timeout=15) as response: + result = json.load(response) + if path.endswith('/refresh'): + enable_colab_for_fixture(base, opener, cookie) + return result with pytest.raises(urllib.error.HTTPError) as error: call('/api/compute/jobs', authenticated=False) assert error.value.code == 401 diff --git a/tests/test_compute_management_browser.py b/tests/test_compute_management_browser.py index 1c1e23b..25d4292 100644 --- a/tests/test_compute_management_browser.py +++ b/tests/test_compute_management_browser.py @@ -19,60 +19,6 @@ def screenshot(page,name): page.screenshot(path=str(Path(directory)/name),full_page=True) -@pytest.mark.parametrize('width',[390,768,1440]) -def test_management_write_only_credentials_and_recipe_import(compute_page,width): - page,errors=compute_page;page.set_viewport_size({'width':width,'height':900}) - providers={name:{'provider':name,'enabled':False,'credential_configured':False,'connection_state':'not_configured', - 'endpoint':url,'recipes':[]} for name,url in [('comfy_cloud','https://cloud.comfy.org'),('runninghub','https://www.runninghub.ai')]} - writes=[] - def respond(route): - if route.request.method=='GET':route.fulfill(json={'ok':True,'providers':list(providers.values())});return - name=route.request.url.rsplit('/',1)[-1];body=route.request.post_data_json;writes.append((name,body)) - providers[name].update({key:value for key,value in body.items() if key not in ['api_key','clear_api_key']}) - if body.get('api_key'):providers[name]['credential_configured']=True - if body.get('clear_api_key'):providers[name]['credential_configured']=False - route.fulfill(json={'ok':True,'provider':providers[name]}) - page.route('**/api/compute/providers**',respond) - base=page.url.split('/compute-fixture')[0];page.goto(base+'/#/admin') - page.get_by_role('button',name='運算平台',exact=True).wait_for() - screenshot(page,f'compute-management-before-{width}.png') - page.get_by_role('button',name='運算平台',exact=True).click() - dialog=page.get_by_role('dialog',name='運算平台');dialog.wait_for() - page.get_by_text('尚未設定 API 金鑰。',exact=True).wait_for() - page.get_by_label('啟用此平台',exact=True).check() - page.get_by_label('API 金鑰',exact=True).fill('synthetic-key-only-for-testing') - page.get_by_text('進階:功能配方',exact=True).click() - recipe={'feature_id':'text2img','recipe_id':'synthetic-v1','label':'合成生圖配方','output_kind':'image', - 'workflow':{'6':{'class_type':'SyntheticNode','inputs':{'text':''}}}, - 'bindings':[{'source':'prompt','node_id':'6','input':'text'}],'fixed_settings':{},'estimated_cost':4} - page.get_by_label('配方檔案',exact=True).set_input_files({'name':'synthetic-recipe.json','mimeType':'application/json','buffer':json.dumps({'recipes':[{**recipe,'verified':True}]}).encode()}) - page.get_by_text('已讀取 1 個配方;按儲存後取代原清單。',exact=True).wait_for() - page.get_by_role('button',name='儲存平台設定',exact=True).click() - page.get_by_text('平台設定已儲存;尚未啟動生成。',exact=True).wait_for() - assert writes==[('comfy_cloud',{'enabled':True,'endpoint':'https://cloud.comfy.org','api_key':'synthetic-key-only-for-testing','recipes':[recipe]})] - assert page.get_by_label('API 金鑰',exact=True).input_value()=='' - assert 'synthetic-key-only-for-testing' not in dialog.inner_text() - assert page.evaluate("![JSON.stringify(localStorage),JSON.stringify(sessionStorage)].some(value=>/synthetic-key|synthetic-unsaved|paper kite|pipeline_id|data:image/.test(value))") - assert page.evaluate('document.documentElement.scrollWidth<=innerWidth') - assert dialog.bounding_box()['width']<=400 - dialog.locator('.sheet-body').evaluate('element=>element.scrollTop=0') - screenshot(page,f'compute-management-after-{width}.png') - page.get_by_label('平台',exact=True).select_option('runninghub') - page.get_by_text('尚未設定 API 金鑰。',exact=True).wait_for() - assert page.get_by_label('平台網址',exact=True).input_value()=='https://www.runninghub.ai' - assert page.get_by_label('API 金鑰',exact=True).input_value()=='' - page.get_by_label('平台',exact=True).select_option('comfy_cloud') - page.get_by_text('金鑰已設定;連線與配方仍會在使用時檢查。',exact=True).wait_for() - page.get_by_label('移除已儲存的金鑰',exact=True).check() - page.get_by_role('button',name='儲存平台設定',exact=True).click() - page.get_by_text('平台設定已儲存;尚未啟動生成。',exact=True).wait_for() - assert writes[-1][1]['clear_api_key'] is True and 'api_key' not in writes[-1][1] - page.get_by_label('API 金鑰',exact=True).fill('synthetic-unsaved-key') - page.keyboard.press('Escape');dialog.wait_for(state='hidden') - page.get_by_role('button',name='運算平台',exact=True).click() - page.get_by_text('尚未設定 API 金鑰。',exact=True).wait_for() - assert page.get_by_label('API 金鑰',exact=True).input_value()=='' - assert not errors,errors @pytest.mark.parametrize('recipe_id',['text-image-video','edit-image-video']) @@ -108,21 +54,31 @@ def pipelines(route): assert not errors,errors -def test_management_does_not_echo_provider_error_or_retain_failed_key(compute_page): - page,errors=compute_page - def respond(route): - if route.request.method=='POST':route.fulfill(status=422,json={'ok':False,'error':{'code':'provider_error','message':'synthetic-secret-reflected-by-error'}}) - else:route.fulfill(json={'ok':True,'providers':[]}) - page.route('**/api/compute/providers**',respond) - base=page.url.split('/compute-fixture')[0];page.goto(base+'/#/admin') - page.get_by_role('button',name='運算平台',exact=True).click() - page.get_by_text('尚未設定 API 金鑰。',exact=True).wait_for() - page.get_by_label('API 金鑰',exact=True).fill('synthetic-secret-reflected-by-error') - page.get_by_role('button',name='儲存平台設定',exact=True).click() - page.get_by_text('設定尚未儲存。請檢查連線與配方格式後再試;新金鑰需重新輸入。',exact=True).wait_for() - assert 'synthetic-secret-reflected-by-error' not in page.locator('body').inner_text() - assert page.get_by_label('API 金鑰',exact=True).input_value()=='' - assert not errors +def test_console_does_not_echo_rejected_key_or_retain_input(compute_page): + page, errors = compute_page + credential = 'synthetic-test-key-1' + writes = [] + + def reject(route): + writes.append(route.request.post_data_json) + route.fulfill(status=422, json={'ok': False, 'error': { + 'code': 'provider_error', 'message': 'Provider rejected ' + credential}}) + + page.route('**/api/compute/connections/comfy_cloud/credential', reject) + base = page.url.split('/compute-fixture')[0] + page.goto(base + '/#/studio/qwen21-text2img') + page.wait_for_function("typeof openComputeSettings === 'function'") + page.evaluate("openComputeSettings(document.querySelector('#identityChip'))") + card = page.locator('[data-provider=comfy_cloud]') + key = card.get_by_label('Comfy Cloud API 金鑰', exact=True) + key.fill(credential) + card.get_by_role('button', name='儲存金鑰', exact=True).click() + page.get_by_text('操作未完成,請重新整理後再試。', exact=True).wait_for() + assert writes and writes[0]['credential'] == credential + assert credential not in page.locator('body').inner_text() + assert all(credential not in value for value in page.locator('input').evaluate_all('(nodes) => nodes.map(node => node.value)')) + assert card.get_by_label('Comfy Cloud API 金鑰', exact=True).input_value() == '' + assert not errors, errors def test_operator_can_open_platform_management_from_account_menu(compute_page): @@ -131,9 +87,9 @@ def test_operator_can_open_platform_management_from_account_menu(compute_page): base=page.url.split('/compute-fixture')[0];page.goto(base+'/#/studio/qwen21-text2img') page.wait_for_function('window.castleTimers && foregroundRefreshes.size === 0') page.evaluate('''() => {currentUser={...currentUser,role:'user',operator:true};openAccountMenu(document.querySelector('#identityChip'));}''') - page.get_by_role('button',name='運算平台',exact=True).click() - page.get_by_role('dialog',name='運算平台').wait_for() - page.get_by_text('尚未設定 API 金鑰。',exact=True).wait_for() + page.get_by_role('button',name='我的運算平台',exact=True).click() + page.get_by_role('dialog',name='我的運算平台').wait_for() + page.get_by_text('不需要帳號或金鑰。',exact=True).wait_for() assert not errors,errors diff --git a/tests/test_compute_management_http.py b/tests/test_compute_management_http.py index f672d56..44784ee 100644 --- a/tests/test_compute_management_http.py +++ b/tests/test_compute_management_http.py @@ -25,7 +25,10 @@ def call(path, body=None, *, authenticated=True): config = call('/api/compute/providers') assert {row['provider'] for row in config['providers']} == {'comfy_cloud', 'runninghub'} assert 'api_key' not in json.dumps(config) - call('/api/compute/providers/comfy_cloud', {'enabled': False, 'endpoint': 'https://cloud.comfy.org', 'recipes': []}) + with pytest.raises(urllib.error.HTTPError) as legacy_error: + call('/api/compute/providers/comfy_cloud', {'enabled': False, 'endpoint': 'https://cloud.comfy.org', 'recipes': []}) + assert legacy_error.value.code == 409 + assert json.load(legacy_error.value)['error']['code'] == 'legacy_write_disabled' request = {'featureId': 'text2img', 'settings': {'positive': 'Synthetic blue landscape', 'aspect': '1024x1024'}, 'files': {}} preview = call('/api/compute/preview', {'request': request, 'placement': 'auto', 'limits': {}}) assert {row['lane'] for row in preview['candidates']} == {'local', 'colab', 'autoip', 'comfy_cloud', 'runninghub'} @@ -73,7 +76,36 @@ def call(path, body=None): coverage = call('capabilities') assert coverage['readiness_checked'] is False assert any(row['id'] == 'text2img' for row in coverage['features']) - prefs = {'default_placement': 'auto', 'feature_placements': {'text2img': 'runninghub'}} + # Follow test_provider_console.py::write and its authenticated inventory test. + from types import SimpleNamespace + from colab_service import ColabService + from provider_console import ProviderConsole + from provider_fabric.runtime import actor_context_from_castle, load_or_create_identity_key + from provider_fabric.store import ProviderFabricStore + from compute_parity.readiness import save + root = test_server.root + with opener.open(urllib.request.Request(base + '/api/auth/status', headers={'Cookie': cookie})) as response: + user = json.load(response)['user'] + identity = load_or_create_identity_key(root / 'actor-identity.key') + runtime = SimpleNamespace(config=SimpleNamespace(credential_root=root / 'provider-secrets'), + store=ProviderFabricStore(root / 'provider-fabric.sqlite3'), + actor_context=lambda email, role: actor_context_from_castle(email, role, identity_key=identity)) + console = ProviderConsole(root, runtime, user, ColabService(root / 'colab'), + probes={'runninghub': lambda _: {'connected': True, 'account_type': 'NORMAL', 'balances': []}}) + def rh_card(): + return next(c for c in console.snapshot()['connections'] if c['provider'] == 'runninghub') + console.write_credential('runninghub', {'credential': 'synthetic-test-key-1', 'revision': rh_card()['revision'], 'operation_id': str(uuid.uuid4())}) + console.test('runninghub', {'revision': rh_card()['revision']}) + catalog_path = root / 'compute-parity/bundles-r29' + catalog_path.mkdir(parents=True, exist_ok=True) + (catalog_path / 'catalog.json').write_text(json.dumps({'cases': [{'owner': console.owner, 'ready': True, 'bundle_sha256': 'synthetic-bundle'}]})) + save(root / 'compute-parity', {'owner': console.owner, 'lane': 'runninghub', 'credential_version': rh_card()['credential_version'], + 'bundle_sha256': 'synthetic-bundle', 'observed_at': time.time(), 'expires_at': time.time() + 300, + 'connection_verified': True, 'dependencies_ready': True, 'hashes_verified': True, 'lifecycle_verified': True, + 'alias_map_version': '20261111-r29b', 'alias_evidence_verified': True}) + console.toggle('runninghub', {'revision': rh_card()['revision'], 'use_enabled': True}) + prefs = {'default_placement': 'auto', 'feature_placements': {'text2img': 'runninghub'}, + 'auto_order': console.snapshot()['preferences']['auto_order']} assert call('preferences', prefs)['feature_placements'] == prefs['feature_placements'] assert call('preferences')['default_placement'] == 'auto' request = {'featureId': 'text2img', 'settings': {'positive': 'Synthetic blue sky', 'width': 1024, 'height': 1024}, 'files': {}} @@ -108,7 +140,7 @@ def call(path, body=None): {'id': 'invalid', 'request': {'featureId': 'not-a-feature', 'settings': {}, 'files': {}}, 'placement': 'local'}]}}) assert error.value.code in (400, 422) assert json.load(error.value)['submission_state'] == 'not_submitted' - call('preferences', {'default_placement': 'local', 'feature_placements': {}}) + call('preferences', {'default_placement': 'local', 'feature_placements': {}, 'auto_order': console.snapshot()['preferences']['auto_order']}) def test_pipeline_initial_media_is_frozen_and_kind_checked(test_server): diff --git a/tests/test_compute_preferences.py b/tests/test_compute_preferences.py index b046c27..bf214ce 100644 --- a/tests/test_compute_preferences.py +++ b/tests/test_compute_preferences.py @@ -10,15 +10,21 @@ from test_compute_web import web_fixture -def test_defaults_owner_isolation_and_strict_options(tmp_path): +@pytest.fixture +def auto_preferences_body(): + return {'default_placement': 'auto', 'feature_placements': {'text2img': 'colab'}, + 'auto_order': ['local', 'colab']} + + +def test_defaults_owner_isolation_and_strict_options(tmp_path, auto_preferences_body): store = ComputePreferences(tmp_path / 'prefs.sqlite3') assert store.get('alice')['default_placement'] == 'local' - body = {'default_placement': 'auto', 'feature_placements': {'text2img': 'colab'}} - assert store.save('alice', body, {'text2img'}) == body + body = auto_preferences_body + assert store.save('alice', body, {'text2img'}) == {**body, 'auto_policy': 'user_order', 'revision': 1} assert store.placement('alice', 'text2img') == 'colab' assert store.placement('alice', 'img2img') == 'auto' assert store.get('bob')['default_placement'] == 'local' - assert ComputePreferences(store.path).get('alice') == body + assert ComputePreferences(store.path).get('alice') == {**body, 'auto_policy': 'user_order', 'revision': 1} assert store.path.stat().st_mode & 0o077 == 0 for invalid in ({**body, 'owner': 'bob'}, {**body, 'default_placement': 'unknown'}, {**body, 'feature_placements': {'hidden-admin-feature': 'local'}}): diff --git a/tests/test_compute_status.py b/tests/test_compute_status.py index b417e70..51b4fe6 100644 --- a/tests/test_compute_status.py +++ b/tests/test_compute_status.py @@ -12,6 +12,7 @@ from compute_web import ComputeWeb from compute_routing import ComputeAdapter, ComputeRouter from provider_fabric.store import ProviderFabricStore +from test_compute_web import AdmitAllConsole @pytest.mark.parametrize(('source','expected'), [ @@ -113,8 +114,9 @@ def access(user, task, metadata=None, index=None): with pytest.raises(PermissionError):web.status_local('owner','local-synthetic') -def test_local_capacity_counts_direct_and_gpu_orchestrator_jobs_once(): +def test_local_capacity_counts_direct_and_gpu_orchestrator_jobs_once(tmp_path): web=object.__new__(ComputeWeb);web.user={} + web.console=AdmitAllConsole('owner', tmp_path/'compute-preferences.sqlite3') web.s=SimpleNamespace(FEATURE_BY_ID={'text2img':{'id':'text2img','builder':'text'}}, feature_status=lambda:[{'id':'text2img','ready':True}], request_json=lambda path:{'queue_running':[[0,'shared-wrapper'],[1,'native']], 'queue_pending':[]}, diff --git a/tests/test_compute_web.py b/tests/test_compute_web.py index c10da57..22edb29 100644 --- a/tests/test_compute_web.py +++ b/tests/test_compute_web.py @@ -29,6 +29,38 @@ ROOT = Path(__file__).resolve().parents[1] +class AdmitAllConsole: + """Ported provider-console interface for tests written before it existed: the same + owner check, every lane admitted, real default preferences.""" + def __init__(self, owner, preferences_path): + from compute_preferences import ComputePreferences + self.owner = owner + self._prefs = ComputePreferences(preferences_path) + + def snapshot(self): + return {'owner': self.owner, 'connections': [], 'preferences': self._prefs.get(self.owner)} + + def gate(self, provider, owner=None): + if owner is not None and owner != self.owner: + raise PermissionError('connection owner mismatch') + return None + + +def enable_colab_for_fixture(base, opener, cookie): + """Finish the ported connection setup after a synthetic account refresh.""" + import urllib.request + headers = {'Content-Type': 'application/json', 'Origin': base, 'Cookie': cookie} + request = urllib.request.Request(base + '/api/compute/connections', headers=headers) + with opener.open(request, timeout=15) as response: + connections = json.load(response)['connections'] + colab = next(item for item in connections if item['provider'] == 'colab') + body = {'revision': colab['revision'], 'use_enabled': True} + request = urllib.request.Request(base + '/api/compute/connections/colab', + data=json.dumps(body).encode(), headers=headers, method='PATCH') + with opener.open(request, timeout=15) as response: + json.load(response) + + def test_history_api_pages_owned_rows_and_rejects_foreign_cursor(tmp_path, monkeypatch): import sys import urllib.parse @@ -119,7 +151,7 @@ def load_server_functions(namespace): "validate_feature_option_contract", "resolve_server_file", "stage_character_asset_for_comfy", "bind_character_capability_files", "character_entry_for_generation", "user_can_see_character", "user_can_generate_character", "safe_path_segment", "validate_client_generation_files", - "plan_colab_generation_request", "record_input_upload_owner", "user_can_use_uploaded_input", + "plan_colab_generation_request", "character_feature_definition", "record_input_upload_owner", "user_can_use_uploaded_input", "stage_colab_uploaded_file", "decode_data_url"] nodes = [ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0)] nodes.extend(copy.deepcopy(functions[name]) for name in selected) @@ -202,7 +234,7 @@ def runtime_policy(entry, cap, runtime): raise ValueError("character release policy blocks generation") return cap - namespace = {"Path": Path, "os": os, "re": re, "secrets": secrets, "shutil": shutil, + namespace = {"Path": Path, "os": os, "re": re, "secrets": secrets, "shutil": shutil, "copy": copy, "base64": base64, "mimetypes": mimetypes, "time": time, "hmac": hmac, "MAX_UPLOAD_DECODED": 64 * 1024 * 1024, "RequestTooLarge": ValueError, "JOB_INDEX_PATH": tmp_path / "library" / ".job_index.json", @@ -232,6 +264,8 @@ def runtime_policy(entry, cap, runtime): "user_can_access_view_item": lambda who, filename, *args: filename.startswith("owned-upload-"), } load_server_functions(namespace) + console = AdmitAllConsole(user['email'], service.root.parent / 'compute-preferences.sqlite3') + console.root = service.root.parent # The parity runtime keeps its synthetic journal here. class Handler: _generate_result = namespace["_generate_result"] @@ -240,6 +274,9 @@ class Handler: def current_user(self): return user + def _provider_console(self): + return console + def is_orchestrator_service_authenticated(self): return False @@ -460,7 +497,10 @@ def call(path, body): request = urllib.request.Request(base + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json", "Origin": base, "Cookie": cookie}) with opener.open(request, timeout=15) as response: - return json.load(response) + result = json.load(response) + if path.endswith('/refresh'): + enable_colab_for_fixture(base, opener, cookie) + return result account = call("/api/colab/accounts", {"label": "Synthetic raw upload"}) flow = call(f"/api/colab/accounts/{account['id']}/login", {}) diff --git a/tests/test_demo_publication.py b/tests/test_demo_publication.py index 9532401..5046e9c 100644 --- a/tests/test_demo_publication.py +++ b/tests/test_demo_publication.py @@ -127,3 +127,10 @@ def test_git_scan_checks_staged_media_not_a_clean_worktree_replacement(tmp_path) cwd=root, check=True, capture_output=True) path.write_bytes((EXAMPLES / path.name).read_bytes()) assert scan(root).returncode == 1 + + +def test_runninghub_referral_svg_is_native_vector(): + svg = (ROOT / 'webui/docs/runninghub-referral.svg').read_text(encoding='utf-8') + assert '' in svg and 'qqgzxufp' in svg + for forbidden in ('' in referral_svg and 'qqgzxufp' in referral_svg + for forbidden in ('= 2 and demo.count('rel="sponsored noopener noreferrer"') >= 2 assert 'href="../"' in demo hardware = read_json(output / 'app-guide.json')['hardware'] assert hardware and 'none' in {profile['id'] for profile in hardware['profiles']} diff --git a/tests/test_hosted_compute.py b/tests/test_hosted_compute.py index 2d4ea8f..240d750 100644 --- a/tests/test_hosted_compute.py +++ b/tests/test_hosted_compute.py @@ -6,8 +6,10 @@ import json import os from pathlib import Path +import sys import threading import time +from types import SimpleNamespace import uuid from PIL import Image @@ -67,10 +69,32 @@ def request(self, method, url, **kwargs): return item -def configured(tmp_path, provider='comfy_cloud', *, image=False, http=None, endpoint=None, clock=None): +def configured(tmp_path, provider='comfy_cloud', *, image=False, http=None, endpoint=None, clock=None, standard_layout=False): + # Follow the write-only vault setup in test_provider_console.py::write. + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'webui')) + from colab_service import ColabService + from provider_console import ProviderConsole + from provider_fabric.runtime import actor_context_from_castle, load_or_create_identity_key + from provider_fabric.store import ProviderFabricStore + + tmp_path.mkdir(mode=0o700, parents=True, exist_ok=True) + identity = load_or_create_identity_key(tmp_path / 'actor-identity.key') + runtime = SimpleNamespace( + config=SimpleNamespace(credential_root=tmp_path / 'provider-secrets'), + store=ProviderFabricStore(tmp_path / 'provider-fabric.sqlite3'), + actor_context=lambda email, role: actor_context_from_castle(email, role, identity_key=identity), + ) + colab = ColabService(tmp_path / 'colab') + console = ProviderConsole(tmp_path, runtime, {'email': OWNER, 'role': 'member'}, colab) + console.write_credential(provider, {'credential': KEY, 'revision': 0, 'operation_id': str(uuid.uuid4())}) + root = tmp_path / 'hosted-compute' + if not standard_layout: + root.rename(tmp_path / 'state') + root = tmp_path / 'state' http = http or FakeHTTP() - service = H.HostedComputeService(tmp_path / 'state', transport=http, **({'clock': clock} if clock else {})) - body = {'enabled': True, 'api_key': KEY, 'recipes': [recipe(provider, image=image)]} + service = H.HostedComputeService(root, transport=http, **({'clock': clock} if clock else {})) + service.test_console = console + body = {'enabled': True, 'recipes': [recipe(provider, image=image)]} if endpoint: body['endpoint'] = endpoint service.configure(OWNER, provider, body) @@ -103,10 +127,14 @@ def test_config_is_owner_scoped_write_only_private_and_offline(tmp_path): assert http.calls == [] for path in (tmp_path / 'state').rglob('*'): assert path.stat().st_mode & 0o077 == 0 - service.configure(OWNER, 'comfy_cloud', {'api_key': ''}) + with pytest.raises(H.HostedComputeError) as write_error: + service.configure(OWNER, 'comfy_cloud', {'api_key': ''}) + assert (write_error.value.code, write_error.value.status) == ('legacy_write_disabled', 409) + assert service.public_config(OWNER)['providers'][0]['credential_configured'] + with pytest.raises(H.HostedComputeError) as clear_error: + service.configure(OWNER, 'comfy_cloud', {'clear_api_key': True}) + assert (clear_error.value.code, clear_error.value.status) == ('legacy_write_disabled', 409) assert service.public_config(OWNER)['providers'][0]['credential_configured'] - service.configure(OWNER, 'comfy_cloud', {'clear_api_key': True}) - assert not service.public_config(OWNER)['providers'][0]['credential_configured'] @pytest.mark.parametrize('url', ['http://cloud.comfy.org', 'https://127.0.0.1', 'https://cloud.comfy.org.evil.test', @@ -163,7 +191,7 @@ def test_finite_budget_and_deadline_required(tmp_path, limits, reason): def test_cloud_create_poll_download_restart_and_tamper(tmp_path): http = FakeHTTP([accepted(urls={'self': '/api/v2/jobs/custom-path'}), completed(), response(png())]) - service, _ = configured(tmp_path, http=http) + service, _ = configured(tmp_path, http=http, standard_layout=True) first = service.submit(OWNER, 'comfy_cloud', RID, REQUEST, LIMITS) assert first['state'] == 'queued' and first['downstream_id'] == RID create = json.loads(http.calls[0][2]['body']) @@ -171,7 +199,7 @@ def test_cloud_create_poll_download_restart_and_tamper(tmp_path): assert 'metadata' not in create assert http.calls[0][2]['headers']['Idempotency-Key'] == RID assert not service.inspect(OWNER, 'comfy_cloud', REQUEST, LIMITS)['auto_eligible'] - restarted = H.HostedComputeService(tmp_path / 'state', http) + restarted = H.HostedComputeService(service.root, http) done = restarted.status(OWNER, 'comfy_cloud', RID) assert done['state'] == 'completed' assert http.calls[1][1].endswith('/api/v2/jobs/custom-path') @@ -186,7 +214,10 @@ def test_cloud_create_poll_download_restart_and_tamper(tmp_path): file.write_bytes(b'tampered') with pytest.raises(H.HostedComputeError): restarted.artifact(OWNER, 'comfy_cloud', RID, item['name']) - restarted.configure(OWNER, 'comfy_cloud', {'api_key': 'rotated-test-key'}) + console = service.test_console + card = next(c for c in console.snapshot()['connections'] if c['provider'] == 'comfy_cloud') + console.write_credential('comfy_cloud', {'credential': 'synthetic-test-key-rotation', + 'revision': card['revision'], 'operation_id': str(uuid.uuid4())}) assert not restarted.inspect(OWNER, 'comfy_cloud', REQUEST, LIMITS)['auto_eligible'] @@ -430,13 +461,15 @@ def test_config_and_recipe_changes_invalidate_verified_auto(tmp_path): def test_credential_removal_does_not_lose_existing_binding(tmp_path): - service, http = configured(tmp_path, http=FakeHTTP([accepted(), response({'id': REMOTE, 'status': 'running'})])) + service, http = configured(tmp_path, http=FakeHTTP([accepted(), response({'id': REMOTE, 'status': 'running'})]), standard_layout=True) service.submit(OWNER, 'comfy_cloud', RID, REQUEST, LIMITS) - service.configure(OWNER, 'comfy_cloud', {'clear_api_key': True}) - blocked = service.status(OWNER, 'comfy_cloud', RID) - assert blocked['state'] == 'queued' and blocked['error_code'] == 'credential_required_for_recovery' + console = service.test_console + card = next(c for c in console.snapshot()['connections'] if c['provider'] == 'comfy_cloud') + result = console.delete_credential('comfy_cloud', {'revision': card['revision']}) + retained = next(c for c in result['connections'] if c['provider'] == 'comfy_cloud') + assert '仍需此連線' in result['notice'] + assert retained['credential_present'] and not retained['use_enabled'] assert len(http.calls) == 1 - service.configure(OWNER, 'comfy_cloud', {'api_key': KEY}) assert service.recover(OWNER, 'comfy_cloud', RID)['state'] == 'running' assert len(http.calls) == 2 @@ -453,3 +486,29 @@ def test_documented_sdxl_recipe_imports_and_maps_real_form_defaults(): assert mapping[('5', 'width')] == 1088 and mapping[('5', 'height')] == 1920 assert mapping[('3', 'cfg')] == 1.0 and mapping[('7', 'text')] == 'synthetic negative' assert mapping[('3', 'seed')] == 123 + + +def test_recipe_import_cannot_forge_verification_or_omit_real_estimate(tmp_path): + service, http = configured(tmp_path) + before = service.public_config(OWNER) + item = recipe() + invalid = [{k: v for k, v in item.items() if k != 'estimated_cost'}, + {**item, 'estimated_cost': 0}, {**item, 'verified': True}] + for value in invalid: + with pytest.raises(H.HostedComputeError): + service.configure(OWNER, 'comfy_cloud', {'recipes': [value]}) + assert service.public_config(OWNER) == before + assert http.calls == [] + + +def test_partial_provider_save_preserves_key_and_other_recipes(tmp_path): + service, http = configured(tmp_path) + items = [recipe(), {**recipe(image=True), 'recipe_id': 'synthetic-second'}] + service.configure(OWNER, 'comfy_cloud', {'recipes': items}) + before = service.public_config(OWNER)['providers'][0] + service.configure(OWNER, 'comfy_cloud', {'enabled': False}) + after = service.public_config(OWNER)['providers'][0] + assert after['recipes'] == before['recipes'] + assert after['credential_configured'] is True + assert KEY not in json.dumps(after) + assert http.calls == [] diff --git a/tests/test_hosted_compute_http.py b/tests/test_hosted_compute_http.py index 441c0ab..da5aa78 100644 --- a/tests/test_hosted_compute_http.py +++ b/tests/test_hosted_compute_http.py @@ -90,3 +90,14 @@ def test_public_dns_guard_blocks_private_and_mixed_answers(monkeypatch, addresse def test_url_validation_rejects_unsafe_destinations(url): with pytest.raises(T.TransportError): T.public_url(url) + + +def test_package_import_needs_only_the_repository_root(): + import sys + from pathlib import Path + root = Path(__file__).resolve().parents[1] + code = ("import sys; sys.path.insert(0, sys.argv[1]); " + "import webui.hosted_compute_http, webui.hosted_compute") + result = subprocess.run([sys.executable, '-I', '-c', code, str(root)], + capture_output=True, text=True, timeout=60) + assert result.returncode == 0, result.stderr[-400:] diff --git a/tests/test_provider_console.py b/tests/test_provider_console.py new file mode 100644 index 0000000..afb890f --- /dev/null +++ b/tests/test_provider_console.py @@ -0,0 +1,342 @@ +import hashlib +import io +import json +import os +from pathlib import Path +import sqlite3 +import sys +import threading +from types import SimpleNamespace +import uuid + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1]/'webui')) +from provider_console import ProviderConsole, PREPARING +from provider_fabric.store import ProviderFabricStore +from provider_fabric.runtime import actor_context_from_castle, load_or_create_identity_key +from provider_fabric.config import SecretValue, SecretReference +from provider_fabric.credentials import ProviderCredentialVault +from colab_service import ColabService +from compute_preferences import ComputePreferences +from compute_routing import ComputeRouter, ComputeAdapter, ComputeRoutingError +from provider_console_migration import migrate, rollback, inventory + +SECRET=('test-' + 'key-not-' + 'secret-0001') +AUTOIP='aip_sy' + 'ntheti' + 'c_only' + '_do_no' + 't_use_' + '123456' + '789' + +@pytest.fixture +def env(tmp_path): + root=tmp_path/'state'; root.mkdir(mode=0o700) + key=load_or_create_identity_key(root/'actor-identity.key') + runtime=SimpleNamespace(config=SimpleNamespace(credential_root=root/'provider-secrets'),store=ProviderFabricStore(root/'provider-fabric.sqlite3'), + actor_context=lambda email,role:actor_context_from_castle(email,role,identity_key=key)) + class Bridge: + installed=True + def __call__(self,op,path,**kwargs): + if op=='account_status': return {'authenticated':True,'balance_compute_units':25} + if op=='oauth_begin': return {'flow_id':'synthetic-flow','authorization_url':'https://accounts.google.com/o/oauth2/auth?state=synthetic'} + if op=='oauth_finish': return {'authenticated':True} + raise AssertionError('unexpected bridge operation') + colab=ColabService(root/'colab',bridge=Bridge()) + def console(owner='other@example.invalid',role='member',**kwargs): + return ProviderConsole(root,runtime,{'email':owner,'role':role},colab,**kwargs) + return SimpleNamespace(root=root,runtime=runtime,colab=colab,console=console) + +def card(c,p): return next(x for x in c.snapshot()['connections'] if x['provider']==p) +def write(c,p='runninghub',secret=SECRET,operation=None): + return c.write_credential(p,{'credential':secret,'revision':card(c,p)['revision'],'operation_id':operation or str(uuid.uuid4())}) +def probe(c,p='runninghub'): + return c.test(p,{'revision':card(c,p)['revision']}) +def toggle(c,p,enabled): return c.toggle(p,{'use_enabled':enabled,'revision':card(c,p)['revision']}) + +def test_write_only_isolated_and_never_echoed(env,capsys): + c=env.console(); before=c.snapshot(); assert not list(env.root.glob('hosted-compute/*')) + operation=str(uuid.uuid4()); result=write(c,operation=operation) + assert SECRET not in json.dumps(result) + assert 'credential_ref' not in json.dumps(result) + assert card(c,'runninghub')['disabled_code']=='rh_key_type_unknown' + assert not card(c,'runninghub')['use_enabled'] + assert not card(env.console('bob@example.test'),'runninghub')['credential_present'] + assert not card(env.console('admin@example.test','admin'),'runninghub')['credential_present'] + with pytest.raises(PermissionError): c.gate('runninghub','bob@example.test') + with pytest.raises(ComputeRoutingError): c.write_credential('runninghub',{'credential':SECRET,'owner':'bob@example.test','revision':1,'operation_id':operation}) + # Replay of a successful write is idempotent and cannot mutate another secret. + assert write(c,secret=('test-' + 'key-not-' + 'secret-0001'),operation=operation)['connections']==result['connections'] + assert SECRET.encode() not in (env.root/'compute-preferences.sqlite3').read_bytes() + assert SECRET not in capsys.readouterr().out + assert before['preferences']['default_placement'] is None + +def test_vault_permissions_and_exact_secret(env): + c=env.console(); write(c) + files=list((env.root/'provider-secrets').rglob('*.secret')); assert len(files)==1 + assert files[0].read_text()==SECRET + assert files[0].stat().st_mode&0o777==0o600 + for directory in (files[0].parent,files[0].parent.parent,env.root/'provider-secrets'): + assert directory.stat().st_mode&0o777==0o700 + with pytest.raises(ValueError): write(c,secret=' '+SECRET) + assert card(c,'runninghub')['credential_version']==1 + assert files[0].read_text()==SECRET + +@pytest.mark.parametrize('unsafe',['symlink','hardlink','permissions']) +def test_vault_rejects_unsafe_files(env,tmp_path,unsafe): + c=env.console();write(c); path=next((env.root/'provider-secrets').rglob('*.secret')) + if unsafe=='symlink': + target=tmp_path/'target'; path.rename(target); path.symlink_to(target) + elif unsafe=='hardlink': os.link(path,tmp_path/'linked') + else: path.chmod(0o644) + with pytest.raises(PermissionError): SecretReference(kind='file',locator=str(path)).resolve() + +@pytest.mark.parametrize('provider,reason',[('local','local_permission_required'),('colab','login_required'),('autoip','credential_required'),('runninghub','credential_required'),('comfy_cloud','credential_required')]) +def test_disabled_reasons(env,provider,reason): + c=env.console(); assert card(c,provider)['disabled_code']==reason + with pytest.raises(ComputeRoutingError):toggle(c,provider,True) + toggle(c,provider,False) # Turning off is always allowed. + +def test_identity_balance_and_no_recipe_success(env): + c=env.console(probes={'runninghub':lambda _: {'connected':True,'account_type':'SHARED','balances':[{'unit':'POINT','value':1000},{'unit':'coins','value':0}]}}) + write(c);probe(c) + value=card(c,'runninghub'); assert value['connection_state']=='connected' + assert value['balances'][0]['value']==1000 and value['balances'][1]['value']==0 + assert value['disabled_code']=='rh_membership_required' + with pytest.raises(ComputeRoutingError): toggle(c,'runninghub',True) + with pytest.raises(ComputeRoutingError) as error: probe(c) + assert error.value.status==429 + +def test_unknown_balance_and_malicious_upstream(env,capsys): + c=env.console(probes={'runninghub':lambda _: {'connected':True,'email':SECRET,'account_type':SECRET,'balances':[{'unit':SECRET,'value':1},{'unit':'POINT','value':SECRET}]}}) + write(c);result=probe(c) + assert SECRET not in json.dumps(result) and card(c,'runninghub')['balances']==[] + def explode(_): raise RuntimeError(SECRET) + c=env.console('b@example.test',probes={'runninghub':explode});write(c);result=probe(c) + assert SECRET not in json.dumps(result) + assert card(c,'runninghub')['safe_reason']=='平台暫時無回應,請稍後再試' + assert SECRET not in capsys.readouterr().err + +def test_stale_test_cannot_overwrite_rotation(env): + started,finish=threading.Event(),threading.Event() + def delayed(_): started.set(); assert finish.wait(5); return {'connected':True} + c=env.console(probes={'runninghub':delayed});write(c);errors=[] + def run(): + try: probe(c) + except ComputeRoutingError as e: errors.append(e.code) + thread=threading.Thread(target=run);thread.start();assert started.wait(5) + write(c,secret=SECRET+'new');finish.set();thread.join(5) + assert errors==['revision_conflict'] + assert card(c,'runninghub')['credential_version']==2 + assert card(c,'runninghub')['connection_state']=='untested' + +def test_toggle_default_and_order_atomic(env,monkeypatch): + monkeypatch.setattr(env.runtime.store,"latest_accessible_capability_snapshot",lambda owner,account:{"offerings":[{"enabled":True}]}) + c=env.console('admin@example.test','admin',probes={'autoip':lambda _: {'connected':True}}) + write(c,'autoip',AUTOIP);probe(c,'autoip');toggle(c,'autoip',True) + prefs=c.snapshot()['preferences']; assert prefs['auto_order']==['local','autoip'] + saved=c.save_preferences({'default_placement':'autoip','feature_placements':{'video':'autoip'},'revision':prefs['revision']}, {'video'}) + result=toggle(c,'autoip',False) + assert result['preferences']['default_placement']=='auto' + assert result['preferences']['auto_order']==['local'] + assert result['preferences']['feature_placements']=={'video':'autoip'} + result=toggle(c,'local',False);assert result['preferences']['default_placement']=='auto' + # Closing the actual default with no other enabled lanes yields unset. + toggle(c,'local',True);prefs=c.snapshot()['preferences'] + c.save_preferences({'default_placement':'local','feature_placements':{},'revision':prefs['revision']},{}) + assert toggle(c,'local',False)['preferences']['default_placement'] is None + with pytest.raises(ComputeRoutingError): c.save_preferences({'default_placement':'autoip','feature_placements':{},'revision':saved['revision']},{}) + +def test_legacy_load_migration_only_explicit_order_changes_policy(env): + c=env.console('admin@example.test','admin') + with c.prefs.db(write=True) as db:c.prefs.put(db,c.owner,{'default_placement':'auto','feature_placements':{'video':'local'}}) + prefs=c.snapshot()['preferences'];assert prefs['auto_policy']=='legacy_load' + c.save_preferences({'default_placement':'auto','feature_placements':{'video':'local'},'revision':0},{'video'}) + assert c.snapshot()['preferences']['auto_policy']=='legacy_load' + c.save_preferences({'default_placement':'auto','feature_placements':{},'auto_order':['local'],'revision':1},{}) + assert c.snapshot()['preferences']['auto_policy']=='user_order' + for order in (['local','local'],['runninghub'],['bad']): + with pytest.raises(ComputeRoutingError): c.save_preferences({'default_placement':'auto','feature_placements':{},'auto_order':order,'revision':2},{}) + assert c.snapshot()['preferences']['revision']==2 + +def test_router_policy_and_replay(env): + from compute_routing import ComputeRejected + policy={'auto_policy':'legacy_load','auto_order':['local','autoip']};calls=[] + def adapter(lane,depth):return ComputeAdapter(lambda *args:{'eligible':True,'queue_depth':depth},lambda *args:calls.append(lane) or {'state':'queued','downstream_id':'task-1'}) + r=ComputeRouter(env.root/'routing-test.sqlite3',{'local':adapter('local',10),'autoip':adapter('autoip',0)},policy=lambda owner:policy) + assert r.preview('a',{},'auto')['selected_lane']=='autoip' + policy['auto_policy']='user_order';assert r.preview('a',{},'auto')['selected_lane']=='local' + request=str(uuid.uuid4());r.submit('a',request,{},'auto');policy['auto_order']=['autoip'];r.submit('a',request,{},'auto');assert calls==['local'] + with pytest.raises(ComputeRoutingError):r.status('b',request) + r.admission=lambda *args: (_ for _ in ()).throw(ComputeRejected('使用已關閉',code='use_disabled')) + assert r.submit('a',str(uuid.uuid4()),{},'auto')['state']=='rejected';assert calls==['local'] + +def legacy(env,owner='owner@example.invalid'): + folder=env.root/'hosted-compute'/hashlib.sha256(owner.encode()).hexdigest()/'runninghub';folder.mkdir(parents=True,mode=0o700) + for parent in (folder.parent,folder.parent.parent):parent.chmod(0o700) + from hosted_compute import _write + _write(folder/'config.json',{'api_key':SECRET,'enabled':False,'endpoint':'https://www.runninghub.ai','recipes':[],'credential_epoch':'keep-this-epoch'}) + return folder/'config.json' + +def test_migration_idempotency_and_rollback(env): + path=legacy(env); c=env.console('owner@example.invalid') + with c.prefs.db(write=True) as db:c.prefs.put(db,c.owner,{'default_placement':'auto','feature_placements':{'video':'local'}}) + args=(env.root,env.runtime.config.credential_root,env.root/'actor-identity.key',['owner@example.invalid']) + original=path.read_bytes();backup=env.root/'backup' + result=migrate(*args,backup);assert result['migrated']==1 + assert path.read_bytes()==original + overlay=path.with_name('console-config.json') + assert SECRET not in overlay.read_text();assert not json.loads(overlay.read_text())['enabled'] + assert json.loads(path.read_text())['credential_epoch']=='keep-this-epoch' + assert c.snapshot()['preferences']['auto_policy']=='legacy_load' + assert card(c,'runninghub')['legacy_modified_at'] and card(c,'runninghub')['credential_saved_at'] is None + assert migrate(*args,env.root/'unused-backup')['state']=='unchanged' + from hosted_compute import HostedComputeService + hosted=HostedComputeService(env.root/'hosted-compute');assert hosted._config(path.parent)['api_key']==SECRET + assert SECRET not in json.dumps(hosted.public_config('owner@example.invalid')) + rollback(backup);assert path.read_bytes()==original + assert not (env.root/'provider-secrets').exists() + +def test_migration_failure_and_unknown_owner(env): + path=legacy(env);original=path.read_bytes() + with pytest.raises(ValueError):migrate(env.root,env.runtime.config.credential_root,env.root/'actor-identity.key',['wrong@example.test'],env.root/'unknown') + def fault(_):raise OSError('synthetic disk failure') + with pytest.raises(RuntimeError):migrate(env.root,env.runtime.config.credential_root,env.root/'actor-identity.key',['owner@example.invalid'],env.root/'backup',fault=fault) + assert path.read_bytes()==original + assert not (env.root/'provider-secrets').exists() + +def test_active_jobs_preserve_credentials_and_disable_new_work(env): + c=env.console();write(c) + r=ComputeRouter(env.root/'compute-routing.sqlite3',{'runninghub':ComputeAdapter(lambda *args:{'eligible':True},lambda *args:{'state':'running','downstream_id':'task-1'})}) + request=str(uuid.uuid4());r.submit(c.owner,request,{},'runninghub') + with pytest.raises(ComputeRoutingError):write(c,secret=SECRET+'new') + result=c.delete_credential('runninghub',{'revision':card(c,'runninghub')['revision']}) + assert '仍需此連線' in result['notice'] + assert card(c,'runninghub')['credential_present'] and not card(c,'runninghub')['use_enabled'] + assert next((env.root/'provider-secrets').rglob('*.secret')).read_text()==SECRET + +def test_colab_owner_and_admin_projection(env): + a=env.colab.create_account('other@example.invalid','我的 Google 帳號') + with pytest.raises(ValueError):env.colab.account_action('bob@example.test',a['id'],'refresh',{}) + env.colab.account_action('other@example.invalid',a['id'],'refresh',{}) + assert card(env.console(),'colab')['credential_present'] + assert not card(env.console('bob@example.test'),'colab')['credential_present'] + admin=env.console('owner@example.invalid','admin');write(env.console()) + users={'other@example.invalid':{'role':'member'},'bob@example.test':{'role':'member'}} + result=admin.admin_snapshot(users) + assert 'balances' not in json.dumps(result) and SECRET not in json.dumps(result) + admin.grant('other@example.invalid',True);assert env.console().local_allowed() + admin.grant('other@example.invalid',False);assert env.console().gate('local')=='local_permission_required' + with pytest.raises(PermissionError):env.console().grant('bob@example.test',True) + with pytest.raises(PermissionError):env.console().admin_snapshot(users) + +def test_probe_only_fixed_account_endpoints(env): + from provider_connection_probe import probe_key + from hosted_compute_http import Response + c=env.console();write(c) + with c.prefs.db() as db:ref=SecretReference.from_mapping(c._raw('runninghub',db)['credential_ref']) + class Transport: + def __init__(self):self.calls=[] + def request(self,method,url,**kwargs): + self.calls.append((method,url,kwargs)) + return Response(200,{},json.dumps({'code':0,'data':{'remainPoint':12,'remainCoins':'0','apiType':'SHARED'}}).encode()) + transport=Transport();result=probe_key('runninghub',ref,transport=transport) + assert result['connected'];assert [(m,u) for m,u,_ in transport.calls]==[('POST','https://www.runninghub.ai/uc/openapi/accountStatus')] + assert transport.calls[0][2]['timeout']==10 + with pytest.raises(ValueError):probe_key('comfy_cloud',ref,transport=transport) + assert len(transport.calls)==1 + + +def test_autoip_without_owner_recipes_stays_disabled(env): + c=env.console(probes={'autoip':lambda _: {'connected':True}}) + write(c,'autoip',AUTOIP);probe(c,'autoip') + assert card(c,'autoip')['status_message']==PREPARING + with pytest.raises(ComputeRoutingError):toggle(c,'autoip',True) + + +def test_r26_dry_run_read_only_and_apply_reads_latest(env): + from provider_console_migration import dry_run + from hosted_compute import _read, _write + path=legacy(env);root=env.root + args=(root,env.runtime.config.credential_root,root/'actor-identity.key',['owner@example.invalid']) + def state():return {str(p.relative_to(root)):(p.stat().st_mtime_ns,p.stat().st_mode,p.read_bytes()) for p in root.rglob('*') if p.is_file()} + before=state();report=dry_run(*args);assert state()==before + assert all(type(v) is bool for row in report.values() for v in row.values()) + assert report['runninghub']['has_key'] and report['runninghub']['recipes_count_is_zero'] + fresh=SECRET+'-entered-after-dry-run';value=_read(path);value['api_key']=fresh;_write(path,value) + original=path.read_bytes() + migrate(*args,root/'backup') + assert path.read_bytes()==original + overlay=_read(path.with_name('console-config.json')) + assert SecretReference.from_mapping(overlay['credential_ref']).resolve().reveal()==fresh + assert migrate(*args,root/'unused')['state']=='unchanged' + + +def test_r26_migration_reuses_autoip_and_colab_owner_bindings(env): + root=env.root;owner='other@example.invalid';actor=env.runtime.actor_context(owner,'member') + vault=ProviderCredentialVault(env.runtime.config.credential_root) + ref=vault.provision('autoip','existing-account',AUTOIP).reference + env.runtime.store.register_owned_provider_account(actor.user_id,'existing-account','autoip','Existing',ref,enabled=False) + account=env.colab.create_account(owner,'Existing Google');env.colab.account_action(owner,account['id'],'refresh',{}) + # Opaque bridge token remains byte-identical; migration must not open/copy it. + token=env.colab.account_dir(account['id'])/'token.json';token.write_text('synthetic-bridge-token');token.chmod(0o600) + before={p:p.read_bytes() for p in (root/'provider-secrets').rglob('*.secret')} + colab_before={p:p.read_bytes() for p in (root/'colab').rglob('*') if p.is_file()} + args=(root,env.runtime.config.credential_root,root/'actor-identity.key',[owner]) + result=migrate(*args,root/'backup');assert result['migrated']==2 + assert {p:p.read_bytes() for p in before}==before + assert {p:p.read_bytes() for p in colab_before}==colab_before + assert card(env.console(owner),'autoip')['credential_present'] + assert not card(env.console('bob@example.test'),'autoip')['credential_present'] + assert card(env.console(owner),'colab')['credential_present'] + assert migrate(*args,root/'unused')['state']=='unchanged' + rollback(root/'backup');assert {p:p.read_bytes() for p in colab_before}==colab_before + + +def test_r26_overlay_rotation_and_deletion_never_rewrite_rollback_original(env): + from hosted_compute import HostedComputeService + path=legacy(env);original=path.read_bytes();owner='owner@example.invalid' + migrate(env.root,env.runtime.config.credential_root,env.root/'actor-identity.key',[owner],env.root/'backup') + c=env.console(owner);write(c,secret=SECRET+'rotated') + service=HostedComputeService(env.root/'hosted-compute') + assert service._config(path.parent)['api_key']==SECRET+'rotated' + assert path.read_bytes()==original + c.delete_credential('runninghub',{'revision':card(c,'runninghub')['revision']}) + assert not service._config(path.parent)['api_key'] + assert path.read_bytes()==original + + +def test_r26_read_only_inventory_refuses_uncheckpointed_wal(env): + from provider_console_migration import read_rows + path=env.root/'probe.sqlite3' + db=sqlite3.connect(path);db.execute('PRAGMA journal_mode=WAL');db.execute('CREATE TABLE test (value TEXT)');db.commit() + try: + with pytest.raises(ValueError,match='pending journal'):read_rows(path,'SELECT * FROM test') + finally:db.close() + + +def test_cloud_authenticated_inventory_opens_card_without_preferences_write(env): + from compute_parity.readiness import save + import time + c=env.console();write(c,p='comfy_cloud') + catalog=env.root/'compute-parity/bundles-r29';catalog.mkdir(parents=True) + (catalog/'catalog.json').write_text(json.dumps({'cases':[{'owner':c.owner,'ready':True,'bundle_sha256':'fake-bundle'}]})) + with c.prefs.db() as db:before=c._raw('comfy_cloud',db) + evidence={'owner':c.owner,'lane':'comfy_cloud','credential_version':before['credential_version'], + 'bundle_sha256':'fake-bundle','observed_at':time.time(),'expires_at':time.time()+300, + 'connection_verified':True,'dependencies_ready':True,'hash_mode':'name_size_provisional', + 'lora_sha_verified':True,'alias_map_version':'20261111-r29b','alias_evidence_verified':True} + save(env.root/'compute-parity',evidence) + assert card(c,'comfy_cloud')['can_enable'] + with c.prefs.db() as db:assert c._raw('comfy_cloud',db)==before + for change in ({'connection_verified':False},{'credential_version':999},{'owner':'other'}, + {'expires_at':0},{'alias_evidence_verified':False}): + path=env.root/'compute-parity/readiness.json' + path.write_text(json.dumps({'entries':[{**evidence,**change}]})) + assert not card(c,'comfy_cloud')['can_enable'] + +@pytest.mark.parametrize('kind,label,reason',[('NORMAL','會員點數',None),('SHARED','企業錢包','rh_membership_required'),('OTHER','尚未確認金鑰類型','rh_key_type_unknown')]) +def test_r34_detected_type_is_safe_and_cleared_on_rotation(env,kind,label,reason): + c=env.console();write(c) + c._probe=lambda *a:{'connected':True,'account_type':kind,'balances':[{'unit':'POINT','value':1000}]} + probe(c);row=card(c,'runninghub') + assert row['key_type_label']==label + if reason:assert row['disabled_code']==reason and not row['can_enable'] + write(c,secret=('test-' + 'key-not-' + 'secret-0002')) + assert card(c,'runninghub')['key_type_label']=='尚未確認金鑰類型' and card(c,'runninghub')['account_type'] is None diff --git a/tests/test_provider_console_backfill.py b/tests/test_provider_console_backfill.py new file mode 100644 index 0000000..18c4096 --- /dev/null +++ b/tests/test_provider_console_backfill.py @@ -0,0 +1,180 @@ +"""r26b regression tests; all identities, vaults and credentials are synthetic.""" +import json +from pathlib import Path +import subprocess +import sys +import threading +from types import SimpleNamespace + +import pytest + +from test_provider_console import env, write, card, legacy, SECRET +from hosted_compute import HostedComputeService, PROVIDERS, _read, _write +from provider_console_backfill import backfill, main +from provider_fabric.config import SecretReference, SecretValue + + +def overlay(console, provider): + return console._legacy_path(provider).with_name('console-config.json') + + +def state(root): + return {str(p.relative_to(root)): (p.stat().st_mode, p.stat().st_mtime_ns, + p.read_bytes() if p.is_file() else None) for p in root.rglob('*')} + + +@pytest.mark.parametrize('provider', ['comfy_cloud', 'runninghub']) +def test_first_save_rotate_delete_with_fake_vault(env, monkeypatch, provider, capsys, caplog): + values = {} + class Vault: + def __init__(self, root): self.root = Path(root) + def provision(self, provider, account, secret, *, credential_id): + path = str(self.root / provider / account / (credential_id + '.secret')) + values[path] = secret + return SimpleNamespace(reference=SecretReference(kind='file', locator=path)) + def delete(self, provider, account, *, credential_id, confirm): + assert confirm + del values[str(self.root / provider / account / (credential_id + '.secret'))] + monkeypatch.setattr('provider_console.ProviderCredentialVault', Vault) + monkeypatch.setattr(SecretReference, 'resolve', lambda ref: SecretValue(values[ref.locator])) + c = env.console(); path = overlay(c, provider) + assert not path.parent.exists() + result = write(c, provider) + config = _read(path) + assert config['enabled'] is False and config['recipes'] == [] + assert config['endpoint'] == PROVIDERS[provider] and config['credential_epoch'] == '1' + assert 'api_key' not in config and 'credential_ref' in config + assert not c._legacy_path(provider).exists() + assert path.stat().st_mode & 0o777 == 0o600 + for directory in (path.parent, path.parent.parent, path.parent.parent.parent): + assert directory.stat().st_mode & 0o777 == 0o700 + service = HostedComputeService(env.root / 'hosted-compute') + assert service._config(path.parent)['api_key'] == SECRET + first_ref = config['credential_ref'] + write(c, provider, SECRET + '-rotated') + assert service._config(path.parent)['api_key'] == SECRET + '-rotated' + assert _read(path)['credential_epoch'] == '2' and _read(path)['credential_ref'] != first_ref + c.delete_credential(provider, {'revision': card(c, provider)['revision']}) + assert service._config(path.parent)['api_key'] == '' + assert _read(path)['credential_epoch'] == '3' and 'credential_ref' not in _read(path) + output = capsys.readouterr() + assert SECRET not in path.read_text() + json.dumps(result) + output.out + output.err + caplog.text + + +@pytest.mark.parametrize('provider', ['comfy_cloud', 'runninghub']) +def test_backfill_dry_run_idempotent_and_latest_row(env, provider, capsys, caplog): + c = env.console(); write(c, provider) + path = overlay(c, provider); path.unlink() + before = state(env.root) + assert backfill(env.root, dry_run=True) == {'ok': True, 'dry_run': True, 'needs_backfill': True, 'changed': False} + assert state(env.root) == before + # A rotation after the dry-run must win; apply re-reads the DB under lock. + write(c, provider, SECRET + '-latest'); path.unlink() + assert main(['--state-root', str(env.root)]) == 0 + report = json.loads(capsys.readouterr().out) + assert all(type(value) is bool for value in report.values()) and report['changed'] + assert HostedComputeService(env.root / 'hosted-compute')._config(path.parent)['api_key'] == SECRET + '-latest' + before = state(env.root) + assert not backfill(env.root)['changed'] + assert state(env.root) == before + assert SECRET not in path.read_text() + caplog.text + + +def test_backfill_legacy_preserved_and_overlay_preferred(env): + c = env.console('owner@example.invalid'); path = legacy(env) + # A preexisting console row is authoritative over the legacy raw key. + with c.prefs.db(write=True) as db: + c._put(db, 'runninghub', {'actor_id': c.actor.user_id, 'credential_present': False, + 'credential_version': 0, 'revision': 0, 'use_enabled': False, 'connection_state': 'not_configured'}) + original = path.read_bytes() + write(c); target = overlay(c, 'runninghub') + assert _read(target)['endpoint'] == _read(path)['endpoint'] + assert path.read_bytes() == original + config = _read(target); config.update(recipes=[{'preserve': True}], credential_epoch='migrated-epoch') + _write(target, config) + before = target.read_bytes() + assert not backfill(env.root)['changed'] + assert target.read_bytes() == before # Matching migrated epoch must survive. + config['credential_ref']['locator'] += '-stale'; _write(target, config) + assert backfill(env.root)['changed'] + assert _read(target)['recipes'] == [{'preserve': True}] and _read(target)['credential_epoch'] == '1' + assert path.read_bytes() == original and SECRET not in target.read_text() + target.unlink(); assert backfill(env.root)['changed'] + assert _read(target)['recipes'] == [] and path.read_bytes() == original + + +@pytest.mark.parametrize('field', ['actor_id', 'account_id', 'credential_ref']) +def test_backfill_owner_mismatch_refuses_entire_batch(env, field, capsys): + c = env.console(); write(c); write(c, 'comfy_cloud') + for provider in ('comfy_cloud', 'runninghub'): overlay(c, provider).unlink() + with c.prefs.db(write=True) as db: + data = c._raw('runninghub', db) + data[field] = {'kind': 'file', 'locator': '/wrong-owner/secret'} if field == 'credential_ref' else 'wrong-owner' + c._put(db, 'runninghub', data) + before = state(env.root) + for dry_run in (True, False): + with pytest.raises(PermissionError): backfill(env.root, dry_run=dry_run) + assert state(env.root) == before + assert main(['--state-root', str(env.root)]) == 1 + output = capsys.readouterr() + assert all(type(v) is bool for v in json.loads(output.out).values()) + assert SECRET not in output.out + output.err and 'wrong-owner' not in output.out + + +@pytest.mark.parametrize('change', ['rotate', 'delete']) +def test_backfill_waits_for_console_write_lock_and_reads_committed_row(env, change, monkeypatch): + c = env.console(); write(c); path = overlay(c, 'runninghub'); path.unlink() + started = threading.Event(); finished = threading.Event(); errors = [] + import provider_console_backfill as module + real_connect = module.sqlite3.connect + def connect(*args, **kwargs): + if threading.current_thread().name == 'backfill-test': started.set() + return real_connect(*args, **kwargs) + monkeypatch.setattr(module.sqlite3, 'connect', connect) + def run(): + try: backfill(env.root) + except Exception as exc: errors.append(type(exc)) + finally: finished.set() + # Simulate the console's transaction while the separate connection waits. + with c.prefs.db(write=True) as db: + data = c._raw('runninghub', db) + thread = threading.Thread(target=run, name='backfill-test'); thread.start() + assert started.wait(5) and not finished.wait(.15) + if change == 'delete': data.pop('credential_ref') + else: data['credential_version'] += 1 + c._put(db, 'runninghub', data) + thread.join(5) + assert finished.is_set() and not errors + if change == 'delete': assert not path.exists() + else: assert _read(path)['credential_epoch'] == '2' + + +def test_cli_dry_run_zero_writes_and_sanitized_error(env, capsys, monkeypatch): + c = env.console(); write(c); overlay(c, 'runninghub').unlink() + before = state(env.root) + script = Path(__file__).resolve().parents[1] / 'webui/provider_console_backfill.py' + result = subprocess.run([sys.executable, '-B', str(script), '--state-root', str(env.root), '--dry-run'], capture_output=True, text=True) + assert result.returncode == 0 and state(env.root) == before + assert all(type(v) is bool for v in json.loads(result.stdout).values()) + assert SECRET not in result.stdout + result.stderr + def fail(*args, **kwargs): raise RuntimeError(SECRET) + monkeypatch.setattr('provider_console_backfill.backfill', fail) + assert main(['--state-root', str(env.root)]) == 1 + captured = capsys.readouterr() + assert SECRET not in captured.out + captured.err + + +def test_dry_run_refuses_wal_and_absent_state_is_noop(env, tmp_path): + c = env.console(); write(c) + import sqlite3 + db = sqlite3.connect(c.prefs.path) + try: + db.execute('PRAGMA journal_mode=WAL') + db.execute("INSERT INTO local_grants VALUES ('wal@example.test',1)"); db.commit() + before = state(env.root) + with pytest.raises(ValueError, match='pending journal'): backfill(env.root, dry_run=True) + assert state(env.root) == before + finally: db.close() + missing = tmp_path / 'absent' + for dry_run in (True, False): assert not backfill(missing, dry_run=dry_run)['changed'] + assert not missing.exists() diff --git a/tests/test_provider_console_browser.py b/tests/test_provider_console_browser.py new file mode 100644 index 0000000..983ef1e --- /dev/null +++ b/tests/test_provider_console_browser.py @@ -0,0 +1,84 @@ +"""Production JS/CSS and real session APIs on a disposable loopback server.""" +import json +import os +import shutil +from pathlib import Path + +import pytest +from test_provider_console import env,write,SECRET +from test_provider_console_http import http_console + + +def test_console_browser_sizes_and_write_only(http_console,tmp_path): + playwright=pytest.importorskip('playwright.sync_api') + h=http_console + admin=h.env.console('owner@example.invalid','admin');write(admin) + with admin.prefs.db(write=True) as db:admin.prefs.put(db,admin.owner,{'default_placement':'local','feature_placements':{}}) + output=Path(os.environ.get('CONSOLE_SCREENSHOTS',str(tmp_path/'screenshots')));output.mkdir(parents=True,exist_ok=True) + with playwright.sync_playwright() as p: + browser=p.chromium.launch(headless=True, executable_path=shutil.which('chromium'), args=['--no-sandbox', '--disable-dev-shm-usage']) + context=browser.new_context() + context.add_cookies([{'name':'castle_comfy_session','value':h.sessions['owner@example.invalid'],'url':h.origin}]) + page=context.new_page();errors=[];page.on('pageerror',lambda e:errors.append(str(e))) + page.goto(h.origin,wait_until='domcontentloaded') + page.wait_for_function("typeof openComputeSettings === 'function' && currentUser?.email === 'owner@example.invalid'") + page.evaluate("openComputeSettings(document.getElementById('accountMenuBtn'))") + page.locator('.console-card').first.wait_for() + for width,height in [(390,844),(768,1024),(1440,1000)]: + page.set_viewport_size({'width':width,'height':height}) + page.locator('.compute-settings-sheet .sheet-body').evaluate('(el)=>el.scrollTop=0') + page.screenshot(path=str(output/f'console-{width}.png')) + assert page.evaluate('document.documentElement.scrollWidth<=window.innerWidth') + assert page.locator('.compute-settings').evaluate('(el)=>el.scrollWidth<=el.clientWidth') + page.locator('[data-provider=runninghub]').scroll_into_view_if_needed() + page.screenshot(path=str(output/f'console-{width}-saved.png')) + assert page.locator('[data-provider=runninghub]').get_by_role('button',name='更換金鑰',exact=True).count()==1 + assert page.locator('[data-provider=runninghub] input[type=password]').count()==0 + assert SECRET not in page.content() + assert page.locator('[data-provider=runninghub] [role=switch]').is_disabled() + assert not h.calls # GET and rendering never tested providers. + page.get_by_role('button',name='平台管理',exact=True).click() + page.get_by_text('本機使用權與連線').wait_for() + page.screenshot(path=str(output/'admin-1440.png')) + assert page.get_by_text('Alice',exact=True).count()==0 # Projection is Castle email, no provider identity. + page.close();context.close() + context=browser.new_context(viewport={'width':390,'height':844}) + context.add_cookies([{'name':'castle_comfy_session','value':h.sessions['other@example.invalid'],'url':h.origin}]) + page=context.new_page();page.on('pageerror',lambda e:errors.append(str(e))) + page.goto(h.origin,wait_until='domcontentloaded') + page.wait_for_function("currentUser?.email === 'other@example.invalid'") + # Account-menu entry must exist for an ordinary authenticated user. + assert page.evaluate("renderAccountMenuContent().textContent.includes('我的運算平台')") + page.evaluate("openComputeSettings(document.getElementById('accountMenuBtn'))") + page.locator('.console-card').first.wait_for() + assert page.get_by_role('button',name='平台管理',exact=True).count()==0 + assert page.get_by_label('新任務預設',exact=True).input_value()=='' + rh=page.locator('[data-provider=runninghub]');key=rh.get_by_label('RunningHub API 金鑰',exact=True) + assert rh.get_by_role('button',name='儲存金鑰',exact=True).is_disabled() + key.fill(SECRET) + assert rh.get_by_role('button',name='測試連線',exact=True).is_disabled() + rh.get_by_role('button',name='儲存金鑰',exact=True).click() + page.get_by_text('金鑰已儲存,請測試連線。',exact=True).wait_for() + assert page.locator('[data-provider=runninghub] input[type=password]').count()==0 + assert SECRET not in page.content() + assert SECRET not in page.evaluate('JSON.stringify(localStorage) + JSON.stringify(sessionStorage)') + rh=page.locator('[data-provider=runninghub]') + rh.get_by_role('button',name='測試連線',exact=True).click() + page.get_by_text('連線檢查完成;請查看平台狀態。').wait_for() + assert h.calls==['runninghub'] + # Closing and reopening keeps the saved indicator without filling a password field. + page.keyboard.press('Escape');page.evaluate("openComputeSettings(document.getElementById('accountMenuBtn'))") + page.locator('[data-provider=runninghub]').wait_for() + assert page.locator('[data-provider=runninghub] input[type=password]').count()==0 + page.locator('.compute-settings-sheet .sheet-body').evaluate('(el)=>el.scrollTop=0') + page.screenshot(path=str(output/'member-390.png')) + # Keyboard focus stays visible and every interactive hit target is at least 44px high. + page.keyboard.press('Tab') + assert page.evaluate("document.activeElement !== document.body") + sizes=page.locator('.compute-settings button:visible').evaluate_all('(els)=>els.map(e=>e.getBoundingClientRect().height)') + assert min(sizes)>=44 + assert not errors,errors + browser.close() + assert SECRET not in '\n'.join(h.logs) + + diff --git a/tests/test_provider_console_http.py b/tests/test_provider_console_http.py new file mode 100644 index 0000000..79a6532 --- /dev/null +++ b/tests/test_provider_console_http.py @@ -0,0 +1,107 @@ +"""Real Handler + session cookies + isolated SQLite/vault, with provider fakes.""" +import importlib.util +import io +import json +from pathlib import Path +import sys +import threading +import urllib.error +import urllib.request +import uuid +from types import SimpleNamespace + +import pytest +from test_provider_console import env, card, write, SECRET + +@pytest.fixture +def http_console(env,monkeypatch): + root=env.root + monkeypatch.setenv('XDG_DATA_HOME',str(root/'xdg')) + monkeypatch.setenv('CASTLE_COMFY_AUTH_PATH',str(root/'auth.json')) + monkeypatch.setenv('CASTLE_PROVENANCE_KEY_PATH',str(root/'provenance.key')) + monkeypatch.setenv('CASTLE_COMFY_USERS_PATH',str(root/'users.json')) + monkeypatch.setenv('CASTLE_COMFY_SESSION_STORE_PATH',str(root/'auth'/'sessions.json')) + monkeypatch.setenv('CASTLE_COLAB_ROOT',str(root/'colab')) + spec=importlib.util.spec_from_file_location('console_test_server',Path(__file__).resolve().parents[1]/'webui/server.py') + server=importlib.util.module_from_spec(spec);sys.modules[spec.name]=server;spec.loader.exec_module(server) + server._COLAB_SERVICE=env.colab + from hosted_compute import HostedComputeService + server._HOSTED_COMPUTE_SERVICE=HostedComputeService(root/'hosted-compute') + users={email:{'role':role,'displayName':name,'passwordHash':server.password_hash('synthetic-test-password'),'mustSetPassword':False,'disabled':False} + for email,role,name in [('other@example.invalid','user','Alice'),('bob@example.test','user','Bob'),('owner@example.invalid','admin','Owner(測試帳號)')]} + server.save_users(users) + sessions={email:server.session_create({**value,'email':email}) for email,value in users.items()} + logs=[];calls=[] + class Handler(server.Handler): + def _provider_runtime(self): return env.runtime + def _provider_console(self): + user=self.current_user() or {} + return env.console(user.get('email'),user.get('role'),probes={p:lambda data,p=p: calls.append(p) or {'connected':True,'balances':[]} for p in ('local','autoip','colab','runninghub')},local_check=lambda:True) + def log_message(self,fmt,*args): logs.append(fmt%args) + def do_GET(self): + if self.path.startswith('/api/auth/status'): + self.send_json({'ok':True,'configured':True,'authenticated':bool(self.current_user()),'user':self.current_user(),'lane':'local','needsSetup':False});return + if self.path.startswith(('/api/compute/connections','/api/compute/preferences','/api/compute/platform-admin','/api/compute/jobs','/api/colab','/static/')) or self.path=='/': + return super().do_GET() + if self.path=='/api/compute/providers': + self.send_json({'providers':[{'provider':'runninghub','credential_configured':True,'enabled':False,'endpoint':'https://www.runninghub.ai','recipes':[]}]});return + if self.path=='/api/compute/capabilities':self.send_json({'ok':True,'features':[]});return + # Unrelated app requests have inert data; never touch real runtime/state. + self.send_json({'ok':True,'features':[],'studios':[],'characters':[],'actions':[],'jobs':[],'items':[],'providers':[],'assets':[],'tasks':[],'runs':[]}) + def do_POST(self): + if self.path.startswith(('/api/compute/connections','/api/compute/preferences','/api/colab')):return super().do_POST() + self.send_json({'ok':False},404) + http=server.CastleThreadingHTTPServer(('127.0.0.1',0),Handler) + origin=f'http://127.0.0.1:{http.server_port}';server.ALLOWED_ORIGIN_HOSTS={f'127.0.0.1:{http.server_port}'} + thread=threading.Thread(target=http.serve_forever,daemon=True);thread.start() + def request(method,path,body=None,owner='other@example.invalid',origin_value=origin): + headers={'Content-Type':'application/json','Origin':origin_value} + if owner:headers['Cookie']=f'{server.SESSION_COOKIE}={sessions[owner]}' + req=urllib.request.Request(origin+path,data=json.dumps(body).encode() if body is not None else None,headers=headers,method=method) + try:response=urllib.request.urlopen(req,timeout=10) + except urllib.error.HTTPError as error:response=error + return response.status,json.loads(response.read()),dict(response.headers) + yield SimpleNamespace(env=env,request=request,origin=origin,logs=logs,calls=calls,sessions=sessions,server=server) + http.shutdown();http.server_close();thread.join(5) + + +def test_http_write_only_and_session_owner(http_console): + h=http_console;operation=str(uuid.uuid4());payload={'credential':SECRET,'revision':0,'operation_id':operation} + status,result,headers=h.request('PUT','/api/compute/connections/runninghub/credential',payload) + assert status==200 and headers['Cache-Control']=='private, no-store' + assert SECRET not in json.dumps(result) and not h.calls + for owner in ('bob@example.test','owner@example.invalid'): + status,result,_=h.request('GET','/api/compute/connections',owner=owner) + assert status==200 and not next(c for c in result['connections'] if c['provider']=='runninghub')['credential_present'] + assert h.request('POST','/api/compute/connections/runninghub/test',{'revision':0},owner=owner)[0]==409 + assert h.request('GET','/api/compute/connections/runninghub/credential')[0]==404 + assert h.request('GET','/api/compute/connections?owner=bob@example.test')[0]==400 + assert h.request('PUT','/api/compute/connections/runninghub/credential',{**payload,'owner':'bob@example.test'})[0]==400 + assert h.request('GET','/api/compute/connections',owner=None)[0]==401 + assert h.request('PUT','/api/compute/connections/runninghub/credential',payload,origin_value='https://evil.example')[0]==403 + assert SECRET not in '\n'.join(h.logs) + assert h.request('PATCH','/api/compute/platform-admin/local-grant',{'email':'bob@example.test','allowed':True})[0]==403 + assert h.request('GET','/api/compute/platform-admin')[0]==403 + status,result,_=h.request('GET','/api/compute/platform-admin',owner='owner@example.invalid') + assert status==200 and 'balances' not in json.dumps(result) and SECRET not in json.dumps(result) + assert h.request('POST','/api/compute/connections/runninghub/test',{'revision':1})[0]==200 + assert h.calls==['runninghub'] + + +def test_http_colab_cross_owner_and_disabled_session(http_console): + h=http_console + _,account,_=h.request('POST','/api/colab/accounts',{'label':'我的 Google 帳號'}) + assert h.request('POST',f"/api/colab/accounts/{account['id']}/login",{},owner='bob@example.test')[0]==400 + assert h.request('POST',f"/api/colab/accounts/{account['id']}/refresh",{'owner':'bob@example.test'})[0]==400 + status,snapshot,_=h.request('GET','/api/colab',owner='bob@example.test');assert snapshot['accounts']==[] + users=h.server.load_users();users['other@example.invalid']['disabled']=True;h.server.save_users(users) + assert h.request('GET','/api/compute/connections')[0]==401 + + +def test_http_cross_owner_status_route(http_console): + from compute_routing import ComputeRouter,ComputeAdapter + h=http_console + router=ComputeRouter(h.env.root/'compute-routing.sqlite3',{'local':ComputeAdapter(lambda *a:{'eligible':True},lambda *a:{'state':'queued','downstream_id':'synthetic-task'})}) + rid=str(uuid.uuid4());router.submit('other@example.invalid',rid,{},'local') + assert h.request('GET','/api/compute/jobs/'+rid,owner='bob@example.test')[0]==404 + assert h.request('GET','/api/compute/jobs/'+rid,owner='owner@example.invalid')[0]==404 From 3f54195b441a04732007a61cb2eabafffda0542c Mon Sep 17 00:00:00 2001 From: Ted H Date: Sat, 14 Nov 2026 20:12:02 -0500 Subject: [PATCH 3/7] Update docs and the project site; add the RunningHub referral Document the five compute lanes, Colab work sessions, the provider console and upstream pins. Add the owner's RunningHub referral card, demo banner link and QR code, each with a disclosure. Co-Authored-By: Claude Fable 5.2 --- README.md | 12 ++- README.zh-TW.md | 12 ++- docs/autoip-cloud-demo.md | 2 +- docs/colab.md | 10 ++- docs/compute-platforms.md | 88 ++++++++++++++++++- docs/getting-started.md | 2 +- docs/hosted-compute.md | 8 +- docs/runninghub-referral.md | 21 +++++ docs/site.md | 4 +- docs/workflow-audit/README.md | 3 + docs/workflow-audit/h3-colab-study.md | 3 + docs/workflow-audit/review-20261110.md | 3 + .../templates-audit-20261110.md | 3 + .../workflows-audit-20261110.md | 3 + webui/docs/hardware.js | 13 ++- webui/docs/landing.css | 13 +-- webui/docs/landing.html | 2 +- webui/docs/runninghub-referral.svg | 1 + 18 files changed, 180 insertions(+), 23 deletions(-) create mode 100644 docs/runninghub-referral.md create mode 100644 webui/docs/runninghub-referral.svg diff --git a/README.md b/README.md index e1bf3c9..23d00bd 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,15 @@ The installed app also includes [character portrait composition](docs/character-portraits.md): Qwen 2.1 identity-image conditioning, separate anime/realistic clothing references, scene and pose choices, and compact previews. -The optional [Google Colab H3 lane](docs/colab.md) adds separate account connections, durable cloud jobs, output retrieval and verified GPU release. Its source, CPU and browser contracts are tested; real-account GPU qualification is still pending. The [exhaustive upstream audit](docs/workflow-audit/README.md) distinguishes indexed workflows, importable graphs and actual execution evidence. +Five lanes, in short: + +- **Local** is the reference lane. Every catalog workflow runs on your own ComfyUI. Hosted time estimates start from your own completed Local runs or an estimate the owner enters; the repository ships no measurements. +- **Google Colab** opens one work session per connected Google account. Real-account video jobs (dance and video replace) completed on A100 work sessions on 2026-11-13. Voice on Colab is not available yet: the voice environment still fails to build there, and this repository does not ship the pinned VoxCPM wheel, so that environment fails closed (`voice_env_mismatch`). See [Colab](docs/colab.md). +- **AutoIP** quotes credits before dispatch and settles afterwards. Real-account dance generations completed on 2026-11-11 and 2026-11-12. Identity similarity to Local varies by character. The seven media operations are covered by contract and synthetic tests in CI. +- **Comfy Cloud** takes your own API key and submits the same graph bundle through the `/api/v2` jobs and assets API, after an object-info readiness check. Real-account dance jobs completed on 2026-11-11 and 2026-11-12. The API reported settlement as pending, so the UI shows an estimate until the provider reports an actual cost. +- **RunningHub** takes your own membership API key and runs the same graph through its ComfyUI-compatible API (`/proxy-plus/` prompt, object info, upload, history, queue and interrupt) plus an account-status check. A real-account calibration produced 8 of 8 outputs on 2026-11-12. Identity similarity to Local ranged from close to clearly lower for realistic characters, and anime characters drifted toward a realistic face, so identity parity with Local is not reached yet. + +Since 2026-11-10 the installed app adds Colab work sessions and an independent lease sweeper, cross-lane graph bundles with readiness checks, estimates and a local journal, a provider console for bring-your-own keys, and hosted readiness and inventory checks. [Compute platforms](docs/compute-platforms.md) is the current description. The [upstream audit](docs/workflow-audit/README.md) remains a historical snapshot from 2026-11-10. A local front end for your own ComfyUI: image and video forms, a searchable workflow library, generation queues, and user-managed character, voice and media collections. Use the top-right **繁中 / English** control to switch the interface language on the documentation site or in the installed app. @@ -20,7 +28,7 @@ The working application runs on **your computer**, with a separately installed C **Reference blending now preserves the original subject:** SAM3 creates a subject mask and composites the original person over your second image as the background. It does not redraw the face, change clothes or add lighting/shadows. See the [model setup, actual GPU example and pixel comparison](docs/subject-blend.md). Recorded demos display labeled simulated progress before revealing their results. -The demo's hardware selector offers no NVIDIA GPU, common 8/12/16/24/32 GB VRAM tiers, and two 24 GB cards. These are planning estimates, not measured minimums or benchmarks; two 24 GB cards are not treated as a pooled 48 GB device. Selecting a profile changes only the static demo's availability hints, never your installed app's configuration or permissions. Choosing **AutoIP** enables all 23 demo forms for exploration; real cloud support remains limited to available provider services and implemented integrations. The [cloud/demo guide](docs/autoip-cloud-demo.md) explains those boundaries and discloses referral code `TEDH2FND` used by the optional AutoIP registration link and QR code. +The demo's hardware selector offers no NVIDIA GPU, common 8/12/16/24/32 GB VRAM tiers, and two 24 GB cards. These are planning estimates, not measured minimums or benchmarks; two 24 GB cards are not treated as a pooled 48 GB device. Selecting a profile changes only the static demo's availability hints, never your installed app's configuration or permissions. Choosing **AutoIP** enables all 23 demo forms for exploration; real cloud support remains limited to available provider services and implemented integrations. The [cloud/demo guide](docs/autoip-cloud-demo.md) explains those boundaries and discloses referral code `TEDH2FND` used by the optional AutoIP registration link and QR code. The RunningHub card uses referral code `qqgzxufp` and the link `https://www.runninghub.ai?inviteCode=qqgzxufp`; the disclosure is in [docs/runninghub-referral.md](docs/runninghub-referral.md). ## Start locally diff --git a/README.zh-TW.md b/README.zh-TW.md index 5189309..bb81422 100644 --- a/README.zh-TW.md +++ b/README.zh-TW.md @@ -4,7 +4,15 @@ 安裝版新增[角色搭配寫真](docs/character-portraits.md):以 Qwen 2.1 參考角色原圖,搭配場景、服裝與姿勢。動畫/寫實服裝分開,圖卡使用小型預覽視窗。 -選用的 [Google Colab H3 整合](docs/colab.md) 提供分開的帳號連線、可恢復的雲端任務、成果下載與 GPU 釋放確認;已通過來源、CPU 與瀏覽器測試,真實帳號的 GPU 生成仍待驗證。[完整上游逐條研究](docs/workflow-audit/README.md) 分清楚已收錄、可匯入及有實跑證據的工作流。 +五條運算路線目前是: + +- **本機**是對照路線。目錄裡的每個工作流都在你自己的 ComfyUI 上跑。託管路線的時間估計來自你自己已完成的本機執行,或由擁有者輸入的估計;儲存庫不附帶測量資料。 +- **Google Colab** 對每個已連接的 Google 帳號開一個工作階段。2026-11-13 已在 A100 工作階段完成真實帳號的舞蹈與影片替換。Colab 上的語音還不能用:語音環境建置仍然失敗,此儲存庫也不附帶釘選的 VoxCPM wheel,因此語音環境以 `voice_env_mismatch` 失敗關閉。見 [Colab](docs/colab.md)。 +- **AutoIP** 在派送前報價、完成後結算。2026-11-11 與 2026-11-12 已完成真實帳號的舞蹈生成。和本機的身份相似度依角色而異。七個媒體操作由 CI 的契約與合成測試覆蓋。 +- **Comfy Cloud** 使用你自己的 API 金鑰,把同一份圖束經 `/api/v2` 的工作與素材 API 送出,並先做 object-info 就緒檢查。2026-11-11 與 2026-11-12 已完成真實帳號的舞蹈工作。API 回報結算仍待處理,所以介面顯示估計,直到供應商回報實際費用。 +- **RunningHub** 使用你自己的會員 API 金鑰。同一張圖走 RunningHub 相容 ComfyUI 的 API(`/proxy-plus/` 的 prompt、object info、上傳、history、queue、interrupt)以及帳戶狀態。2026-11-12 的真實帳號校正產出 8 個成果、8 個都成功。和本機的身份相似度,寫實角色從接近到明顯較低都有,動漫角色會往寫實的臉偏移,因此還沒有達到和本機一致。 + +2026-11-10 之後,安裝版新增 Colab 工作階段與獨立租約清掃、跨路線圖束與就緒檢查、估計與本機日誌、自備金鑰的供應商主控台,以及託管就緒與清單檢查。現況見 [運算平台](docs/compute-platforms.md)。[上游逐條研究](docs/workflow-audit/README.md) 仍是 2026-11-10 的歷史快照。 在自己的電腦上,用網頁介面操作 ComfyUI 生圖、影片、工作流、角色、聲音與素材。公開文件站與安裝後的 WebUI 都可用右上角 **繁中 / English** 切換介面語言。角色、帳號與素材庫從空白開始,需要 API 的功能可設定自己的帳號與金鑰。 @@ -16,7 +24,7 @@ 成果範例必須來自對應工作流的實際執行,並記錄輸入、不同的輸出、GPU 與執行證據。參考插圖只作為輸入,不充當生成成果;尚未實跑的影片、語音、訓練及其他功能不以替代媒體展示成果。[示範來源紀錄](webui/docs/examples/provenance.json) 保留公開素材與執行證據;發布只開放經審核的指定路徑與固定雜湊,個人與執行期媒體仍不納入。詳見 [文件站說明](docs/site.md)。 -示範的硬體選單提供無 NVIDIA GPU、8/12/16/24/32 GB 常見顯存級距,以及雙 24 GB 顯卡。這是規劃估計,不是最低需求實測或效能測試;雙 24 GB 不視為合併的 48 GB。切換只影響示範中的可用性提示,不偵測顯卡,也不更動安裝後 WebUI 的設定或停用本機功能。選 **AutoIP** 可探索全部 23 項示範表單,不代表每個本機節點、訓練器或功能都已有雲端 API 對應。選用的註冊連結與 QR code 帶推薦碼 `TEDH2FND`;服務界線與聯盟推薦揭露見 [AutoIP 雲端與示範說明](docs/autoip-cloud-demo.md)。 +示範的硬體選單提供無 NVIDIA GPU、8/12/16/24/32 GB 常見顯存級距,以及雙 24 GB 顯卡。這是規劃估計,不是最低需求實測或效能測試;雙 24 GB 不視為合併的 48 GB。切換只影響示範中的可用性提示,不偵測顯卡,也不更動安裝後 WebUI 的設定或停用本機功能。選 **AutoIP** 可探索全部 23 項示範表單,不代表每個本機節點、訓練器或功能都已有雲端 API 對應。選用的註冊連結與 QR code 帶推薦碼 `TEDH2FND`;服務界線與聯盟推薦揭露見 [AutoIP 雲端與示範說明](docs/autoip-cloud-demo.md)。RunningHub 的推薦碼是 `qqgzxufp`,連結為 `https://www.runninghub.ai?inviteCode=qqgzxufp`,揭露見 [RunningHub 推薦連結](docs/runninghub-referral.md)。 女聲示範包含五種風格、三頁簡報旁白與合成聲音延續,共九段實際音檔;以本機 VoxCPM2 在 CPU 生成,沒有私人錄音或真人聲音參考。聲音庫可試聽、選聲音,再帶入語音示範。另補上實跑對嘴、虛構角色換臉、首尾幀影片及循環處理。詳見[女聲範例與重播方法](docs/voice-examples.md)。 diff --git a/docs/autoip-cloud-demo.md b/docs/autoip-cloud-demo.md index 24a513f..3db8cd0 100644 --- a/docs/autoip-cloud-demo.md +++ b/docs/autoip-cloud-demo.md @@ -28,7 +28,7 @@ QR code 與上方連結編碼相同的完整網址。SVG 使用原生向量圖 官方首頁列出 MCP 的七類媒體工具,並說明 API 金鑰及訂閱條件。[官方首頁的 MCP 說明](https://autoip.app/)、[官方串接教學](https://autoip.app/blog/claude-code)、[API 金鑰管理](https://autoip.app/dashboard/api-keys) -本專案已實作七個媒體生成操作:文生圖、圖生圖、文生影片、圖生影片、多參考影片、對嘴與舞蹈影片。這是程式契約及合成測試覆蓋的範圍,並非本次使用真實帳戶執行成功的宣告。詳細端點、選項及限制見 [AutoIP integration](autoip-api.md)。 +本專案已實作七個媒體生成操作:文生圖、圖生圖、文生影片、圖生影片、多參考影片、對嘴與舞蹈影片。CI 覆蓋的是契約與合成測試。真實帳號的結果見 [運算平台](compute-platforms.md)。詳細端點、選項及限制見 [AutoIP integration](autoip-api.md)。 使用者提供的 2026-10-22 **AutoIP Public API Skill** 另描述圖片反推提示詞、圖片融合、多角度、貼文、關鍵幀影片、角色跳舞、影片修復、語音克隆、提示詞擴寫,以及角色/提示詞/聲音庫管理。這些上游能力並未因此自動出現在本 WebUI 的已實作操作中;逐項整合狀態見上述文件。 diff --git a/docs/colab.md b/docs/colab.md index fbf6226..8e8711f 100644 --- a/docs/colab.md +++ b/docs/colab.md @@ -4,7 +4,15 @@ Web ComfyUI 的一般生成表單與角色單步生成表單提供 **執行位 管理員可直接從 **管理 → Google Colab 帳號**,或 **管理中心 → Google Colab 帳號**,新增帳號、完成授權、重新連接及更新餘額。這裡管理的是目前登入使用者自己的 Google 連線,不是全站共用帳號。 它使用 Google 官方 `google-colab-cli` 0.7.4 的傳輸實作,讓已選擇的 Google 帳號申請 GPU、執行 H3、下載成果並釋放 GPU。它不會改變本機 ComfyUI 的位址,也不需要公開 ComfyUI 或建立通道。 -**驗證程度:已完成來源研究、CPU 契約測試與模擬帳號的瀏覽器測試;尚未以真實 Google 帳號完成 Colab GPU 生成。** 首次連線後仍需用小型任務驗證實際配額、GPU、驅動、依賴安裝及模型相容性。公開示範站不提供這個付費執行入口。 +**驗證程度:來源研究、CPU 契約測試與模擬帳號的瀏覽器測試已完成。** 工作階段路線在 2026-11-13 以真實帳號於 A100 完成舞蹈與影片替換。語音在 Colab 還不能用:語音環境建置仍然失敗,此儲存庫不附帶釘選的 VoxCPM wheel,語音環境以 `voice_env_mismatch` 失敗關閉。首次連線後仍需用小型任務確認你自己的配額、GPU、驅動與依賴。公開示範站不提供這個付費執行入口。 + +每個已連接的 Google 帳號,Web 只開一個工作階段:所選等級的 GPU 執行環境(仍受 Colab 當下是否有機器影響)、依 `scripts/colab_session_overlays/` 釘選的獨立 CPython、覆疊與版本來啟動、上傳輸入、執行工作、送心跳,並在閒置、故障上限或狀態遺失時自己關閉。Web 沒在跑時,獨立租約清掃 `scripts/colab_lease_sweeper.py` 仍會釋放租約。使用者單元是 `scripts/systemd/web-comfyui-colab-lease-sweeper.service` 與 `.timer`,每 5 分鐘清掃一次。單元假設簽出位於 `~/Web_Comfyui`、Web 使用該目錄的 `.venv`,Colab 控制器虛擬環境位於 `~/.local/share/web-comfyui/colab-controller`;路徑不同時請編輯單元。狀態目錄採用 Web 的預設值,可用 `CASTLE_COLAB_ROOT` 覆寫。 + +```sh +cp scripts/systemd/web-comfyui-colab-lease-sweeper.* ~/.config/systemd/user/ +systemctl --user daemon-reload +systemctl --user enable --now web-comfyui-colab-lease-sweeper.timer +``` ## 同一平台選算力 diff --git a/docs/compute-platforms.md b/docs/compute-platforms.md index 21542c9..042edee 100644 --- a/docs/compute-platforms.md +++ b/docs/compute-platforms.md @@ -5,7 +5,7 @@ ## 如何使用 1. 在生成表單選擇「執行方式」。本機沿用既有工作流;Colab 使用已整合的 PRISM / P-H3 配方;AutoIP 使用已支援的服務契約。 -2. 管理介面開啟「運算平台」,設定 Comfy Cloud 或 RunningHub 的官方網址、API 金鑰與功能配方。內建配方可直接選取;RunningHub 須先在其工作台儲存並成功手動執行對應工作流,再填入其 ID;不要求公開發布至社群。金鑰不會回填至瀏覽器。Google Colab 帳號管理仍在同一個 Web。 +2. 管理介面開啟「運算平台」。每位已登入的使用者連接自己的金鑰,並選擇要使用哪些路線;金鑰留在本機狀態目錄,不會回填到瀏覽器。連線探測只檢查金鑰、不跑工作:目前涵蓋 AutoIP 與 RunningHub,Comfy Cloud 還沒有這支探測。舊的配方路徑仍可選內建配方;RunningHub 的 workflow-ID 配方要先在其工作台儲存並成功手動執行,再填入 ID,不要求公開發布。圖束路線則把同一張圖送到 Comfy Cloud 的 `/api/v2` 或 RunningHub 的 `/proxy-plus/`,不必先取得 workflow ID。Google Colab 帳號管理仍在同一個 Web。 3. 每個託管配方必須先手動選用平台,取得下載並驗證成功的成果,才會納入自動安排。變更金鑰、端點或配方會重新要求驗證。 4. 創作頁或側欄開啟「多步製作」,使用三條快速流程,或自行加入製作步驟、選擇各步平台、上傳素材或綁定前一步的成果。可選同一平台,也可跨平台。流程不接受任意程式或節點圖,只能使用平台已開放的生成功能。 5. 每一步的進度、成果、取消與失敗重試都留在此頁。關閉瀏覽器後,已接受的流程會繼續;重新開啟可讀取原紀錄。 @@ -38,6 +38,90 @@ ## 費用與驗證範圍 -各平台費用單位分開檢查,不把 Colab 運算單位、AutoIP 點數、Comfy 點數、RunningHub 金幣視為同一貨幣。Comfy Cloud / RunningHub 目前以設定的配方估計值與執行期限作為准入條件;這不是供應商保證的帳單硬上限。取消已開始的工作仍可能有費用。 +各平台費用單位分開檢查,不把 Colab 運算單位、AutoIP 點數、Comfy 點數、RunningHub 金幣視為同一貨幣。舊的 Comfy Cloud/RunningHub 配方路徑仍以設定的配方估計值與執行期限作為准入條件;這不是供應商保證的帳單硬上限。圖束路線則要先有報價才算就緒,見下一節。取消已開始的工作仍可能有費用。 合成測試覆蓋 HTTP 權限、UI、五平台選擇、下載與驗證、重啟、重複送出、並行 worker、取消和續跑。這些測試不申請真實 GPU、不使用真實帳號金鑰,也不代表五條路線的每個模型已完成實際生成。託管 API 契約與配方格式見 [託管運算設定](hosted-compute.md)。 + +## 目前各路線 + +本機是對照路線。目錄裡的每個工作流都在使用者自己的 ComfyUI 上跑。託管路線的執行時間估計來自使用者自己已完成的本機執行,或由擁有者輸入的估計;儲存庫不附帶測量資料。 + +Google Colab 工作階段:每個已連接的 Google 帳號開一個工作階段(所選等級的 GPU,仍看 Colab 當時有沒有機器)。它用 `scripts/colab_session_overlays/` 裡釘選的獨立 CPython、覆疊與版本啟動環境,上傳輸入、執行工作、送心跳,並在閒置、故障上限或狀態遺失時關閉。Web 沒在跑時,`scripts/colab_lease_sweeper.py` 配合 systemd 使用者單元 `scripts/systemd/web-comfyui-colab-lease-sweeper.service` 與 `.timer`(每 5 分鐘)釋放租約。單元假設簽出位於 `~/Web_Comfyui`(Web 使用其 `.venv`),控制器虛擬環境位於 `~/.local/share/web-comfyui/colab-controller`;路徑不同時請編輯單元。狀態目錄採用 Web 的預設值,可用 `CASTLE_COLAB_ROOT` 覆寫。安裝方式見 [Colab](colab.md)。2026-11-13 已在 A100 工作階段完成真實帳號的舞蹈與影片替換。語音還不能用:語音環境在 Colab 上仍建置失敗,此儲存庫不附帶釘選的 VoxCPM wheel,語音環境以 `voice_env_mismatch` 失敗關閉。 + +AutoIP:派送前向報價 API 取點數報價,完成後結算。2026-11-11 與 2026-11-12 已完成真實帳號的舞蹈生成。和本機的身份相似度依角色而異。七個媒體操作由 CI 的契約與合成測試覆蓋。 + +Comfy Cloud:自備 API 金鑰。同一份圖束經 `/api/v2` 的工作與素材 API 送出,並做 object-info 就緒檢查。2026-11-11 與 2026-11-12 已完成真實帳號的舞蹈工作。API 把結算回報為待處理,介面因此顯示估計,直到供應商回報實際費用。 + +RunningHub:自備會員 API 金鑰。同一張圖經 RunningHub 相容 ComfyUI 的 API 執行(`/proxy-plus/` 的 prompt、object info、上傳、history、queue、interrupt),並查帳戶狀態。2026-11-12 的真實帳號校正產出 8/8。和本機的身份相似度,寫實角色從接近到明顯較低都有,動漫角色會往寫實的臉偏移,因此還沒有和本機對齊。推薦連結見 [RunningHub 推薦連結](runninghub-referral.md)。 + +## 估計與實際費用 + +Comfy Cloud 的估計對照官方點數說明 與定價頁 。RunningHub 用公開工作流作者所說的約 60 POINT/4 分鐘作包絡();這支 API 沒有成文費率。AutoIP 的數字來自分派前的報價 API。 + +圖束路線在有報價之前不算就緒,原因碼是 `parity_probe_quote_required`(`webui/compute_parity/hosted_readiness.py`)。報價來自這位使用者自己的本機同款執行;沒有的話,由擁有者輸入 `runninghub_points` 或 `comfy_cloud_credits`,標成「擁有者估計,非官方報價」。實際費用只在供應商回報後出現。 + +## 供應商主控台 + +每位已登入的使用者在主控台連接自己的金鑰,並選擇要開哪些路線。金鑰留在本機狀態目錄。連線探測不跑工作:RunningHub 查帳戶狀態,AutoIP 查帳戶與餘額;Comfy Cloud 尚無這支探測。 + +離線升級請先停止 Web,先乾跑再套用。 + +`webui/provider_console_migration.py` 不連網。旗標:`--state-root`、`--vault-root`、`--identity-key`、可重複的 `--owner`、`--backup`。`--dry-run`、`--apply`、`--rollback` 互斥;都沒給時走乾跑。`--rollback` 使用 `--backup`。 + +`webui/provider_console_backfill.py` 需要 `--state-root`。加上 `--dry-run` 只報告;不加上就寫入。先乾跑。 + +## 上游來源 / Upstream sources + +下列呼叫只列主機與路徑。查詢字串不列入。RunningHub 把金鑰拼進路徑的寫法不展開,只記 `/proxy-plus/`。 + +### 本機 / Local + +| | | +| --- | --- | +| 官方 | | +| API | 使用者自己的 ComfyUI。預設位址字串是 `127.0.0.1:8188`,另有 `/history/{id}` 與 `/queue` | +| 此程式呼叫 | 沒有固定的公開主機。執行器使用使用者設定的 ComfyUI | + +### Google Colab + +| | | +| --- | --- | +| 官方 | ;方案說明見 [Colab](colab.md) 所引的 Google 頁 | +| 此程式呼叫 | `accounts.google.com/`、`accounts.google.com/.well-known/openid-configuration`、`openidconnect.googleapis.com/v1/userinfo`、`www.googleapis.com/auth/userinfo.profile`、`/auth/userinfo.email`、`/auth/cloud-platform`、`/auth/colaboratory`、`/auth/drive.file`、`sdk.cloud.google.com/applicationdefaultauthcode.html`、執行階段主機 `colab.research.google.com` 或 `*.googleusercontent.com` 的 `/api/contents/{path}` | +| 工作階段安裝 | `pypi.org/simple`、`download.pytorch.org/whl/cu128` | + +釘選的上游(`scripts/colab_session_overlays/`): + +| 專案 | 釘選 | 授權 | +| --- | --- | --- | +| VideoHelperSuite | `4ee72c065db22c9d96c2427954dc69e7b908444b`(`registry.json`) | GPL-3.0(`NOTICE.md`) | +| BreezyVoice | `d592c9d3e8927a0f53f68616387060dcd32a05ea`(`registry.json`) | Apache-2.0(`NOTICE.md`) | +| ComfyUI-KJNodes | `6ab7e8130e449ed2c0037589bcf84146ceb7fc9c`(`comfy-node-supplements.json`) | pin 檔沒有記錄授權或倉庫網址 | +| VoxCPM | `30118a33522ef2d8698fca9bebac7224af242395`(`NOTICE`、`voice-environments.json`) | Apache-2.0。公開樹不附帶該 wheel | +| python-build-standalone | 20260602。`interpreters.comfy`:CPython 3.12.13,`cpython-3.12.13+20260602-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz`,SHA256 `191b5188b42886fb8a14968d714571e8f3d1cef92ac7ad4c7e24cc4d0929b194`。`interpreters.voice`:CPython 3.11.15,`cpython-3.11.15+20260602-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz`,SHA256 `4b79bcb83a22961c8972f8d1d4780bd8925f0b52688d95b090a488f31c8b1139`。發布頁是 `https://github.com/astral-sh/python-build-standalone/releases/download/20260602/`(`voice-environments.json`) | pin 檔沒有另記授權 | + +### AutoIP + +| | | +| --- | --- | +| 官方 | | +| API 文件 | 、金鑰頁 | +| 此程式呼叫 | 基底 `https://autoip.app/api/v1`。POST `/images/text-to-image`、`/images/image-to-image`、`/videos/image-to-video`、`/videos/text-to-video`、`/videos/lip-sync`、`/videos/dance`、`/videos/multi-subject-reference`。GET `/dance-templates`、`/me`、`/credits/balance`、`/pricing`、`/tasks`、`/tasks/{task_uuid}`、`/tasks/{task_uuid}/outputs/{index}` | + +### Comfy Cloud + +| | | +| --- | --- | +| 官方 | ,或已建立的 `https://.run.comfy.app` | +| API 文件 | 、素材上傳說明、點數說明 、定價 | +| 此程式呼叫 | POST `/api/v2/assets`、POST `/api/v2/jobs`、GET `/api/v2/jobs`、GET `/api/v2/jobs/{id}`、GET `/api/object_info`、GET `/api/v2/jobs/{id}/workflow`、POST `/api/v2/jobs/{id}/cancel`、GET `/api/v2/assets/{uuid}/content`、GET `/api/billing/usage/timeseries`。下載主機 `cdn.comfy.org`、`comfy-hub-assets.comfy.org`、`storage.googleapis.com` | + +### RunningHub + +| | | +| --- | --- | +| 官方 | | +| API 文件 | 工作流程部署 `doc-8287465`、錯誤碼 `doc-8287467`、Advanced API `api-425761093`、帳號欄位 `api-425761030`、上傳 `api-425761099`。相容 API 指南 `doc-8287466` | +| 此程式呼叫 | 舊 workflow-ID 路徑:POST `/task/openapi/upload`、`/task/openapi/create`、`/task/openapi/outputs`、`/task/openapi/{operation}`。圖束路徑:POST `www.runninghub.ai/uc/openapi/accountStatus`;`www.runninghub.ai/proxy-plus/` 下的 `/object_info`、`/upload/image`、`/prompt`、`/history`、`/queue`、`/history/{id}`、`/interrupt`、`/view`;POST `www.runninghub.ai/openapi/v2/query`。轉址主機 `rh-images.xiaoyaoyou.com`、`rh-hk-images.xiaoyaoyou.com` | +| 估計出處 | (約 60 POINT/4 分鐘的公開作者包絡,不是這支 API 的費率表) | + diff --git a/docs/getting-started.md b/docs/getting-started.md index c79bfe0..291c2e2 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -21,7 +21,7 @@ Each of the 23 tools, plus character creation, has a prefilled example. Edit the Recorded result examples require actual GPU execution evidence, including the workflow and input/output hashes. Reference illustrations are shown as inputs; unverified features have no result example. The [provenance ledger](../webui/docs/examples/provenance.json) identifies reviewed public assets separately from runtime and personal media. The [site maintenance guide](site.md) explains the publication checks. -The demo hardware selector offers no NVIDIA GPU and common VRAM tiers (8/12/16/24/32 GB), plus two 24 GB cards. Treat its labels as planning estimates, not benchmarks or proven minimums. Two 24 GB cards do not become one 48 GB device. The selector changes only the demo; it never disables or configures your installed app. Choose **AutoIP** to explore all 23 demo forms, while checking real provider support separately. The optional registration link and QR code use referral code `TEDH2FND`; [cloud/demo boundaries and referral disclosure](autoip-cloud-demo.md) explain the distinction. +The demo hardware selector offers no NVIDIA GPU and common VRAM tiers (8/12/16/24/32 GB), plus two 24 GB cards. Treat its labels as planning estimates, not benchmarks or proven minimums. Two 24 GB cards do not become one 48 GB device. The selector changes only the demo; it never disables or configures your installed app. Choose **AutoIP** to explore all 23 demo forms, while checking real provider support separately. The optional registration link and QR code use referral code `TEDH2FND`; [cloud/demo boundaries and referral disclosure](autoip-cloud-demo.md) explain the distinction. The RunningHub referral uses code `qqgzxufp` and `https://www.runninghub.ai?inviteCode=qqgzxufp`; see [docs/runninghub-referral.md](runninghub-referral.md). Most actual generation forms build their own API graphs in Python. A community JSON with a similar title is a separate example, not automatically the form’s template. diff --git a/docs/hosted-compute.md b/docs/hosted-compute.md index 038615b..da651aa 100644 --- a/docs/hosted-compute.md +++ b/docs/hosted-compute.md @@ -1,6 +1,8 @@ # Comfy Cloud 與 RunningHub 託管算力 -研究與協定檢查日期:2026-11-10。這兩個選項使用同一個生產表單,但執行的是管理者明確設定的遠端工作流程。此版本已完成合成素材、注入 HTTP 回應,以及本機 TLS 伺服器的離線驗證;尚未登入真實供應商帳戶、確認付費權益、部署工作流程或執行付費 GPU 工作。既有本機、Colab、AutoIP 的說明見 [算力選擇](compute-platforms.md)。 +研究與協定檢查日期:2026-11-10;路線狀態更新至 2026-11-14。這兩個選項使用同一個生產表單。舊的配方路徑仍執行管理者明確設定的遠端工作流程,並已用合成素材、注入 HTTP 回應與本機 TLS 伺服器做過離線驗證。圖束路線則把與本機相同的圖送出。既有本機、Colab、AutoIP 的說明見 [算力選擇](compute-platforms.md)。 + +真實帳號:Comfy Cloud 的舞蹈工作流已在 2026-11-11 與 2026-11-12 完成。該 API 把結算回報為待處理,所以介面顯示估計,不顯示實際費用,直到供應商回報一筆。RunningHub 在 2026-11-12 的校正產出 8 個成果、8 個都成功。和本機的身份相似度,寫實角色從接近到明顯較低都有,動漫角色會往寫實的臉偏移,因此身份還沒有和本機對齊。 使用「平台設定」為自己的登入身分填入 API key、啟用平台並匯入配方。API key 是只寫欄位,回應只顯示是否已設定;留空保留,明確清除才刪除。各登入身分的配方、憑證、工作與成果分開存放。管理 API 的授權由 WebUI 處理;後端不搜尋其他專案或環境中的憑證。 @@ -10,7 +12,9 @@ RunningHub 使用 `https://www.runninghub.ai`。先在供應商工作台儲存 目前整合的是 RunningHub 的 **workflow-ID REST API**:以 `workflowId` 與 `nodeInfoList` 呼叫 `/task/openapi/create`。官方 Advanced API 雖另有完整圖 JSON 字串的 `workflow` override 欄位,其 schema 仍將 `workflowId` 列為必填;本程式也尚未支援該 inline 欄位。[Advanced API](https://www.runninghub.ai/runninghub-api-doc-en/api-425761093)、[請求 schema](https://www.runninghub.ai/runninghub-api-doc-en/schema-252340070) -RunningHub 另有宣稱相容本機 ComfyUI 的 **Native proxy**,以及不需要 workflow ID、使用個別模型端點的 **Standard Model API**;兩者目前都未整合到本介面。Standard Model API 官方要求 Enterprise-Shared key。它們的模型、節點、輸入控制與計費需分別確認,不能視為本目錄原工作流程已可執行,也不能由帳號查詢成功推定功能可用。[Native proxy 指南](https://www.runninghub.ai/runninghub-api-doc-en/doc-8287466)、[API 類型與資格](https://www.runninghub.ai/runninghub-api-doc-en/doc-8287463)、[Standard Model 端點範例](https://www.runninghub.ai/runninghub-api-doc-en/api-448184514) +RunningHub 的 **ComfyUI 相容 API** 已接入:同一張圖經 `https://www.runninghub.ai/proxy-plus/` 的 prompt、object info、上傳、history、queue 與 interrupt 送出,並另查帳戶狀態。這取代「Native proxy 尚未整合」的舊說明。不需要 workflow ID、改走個別模型端點的 **Standard Model API** 仍未整合;官方要求 Enterprise-Shared key。它的模型、節點、輸入與計費要分開確認,不能把帳戶查詢成功當成該 API 已可執行。[Native proxy 指南](https://www.runninghub.ai/runninghub-api-doc-en/doc-8287466)、[API 類型與資格](https://www.runninghub.ai/runninghub-api-doc-en/doc-8287463)、[Standard Model 端點範例](https://www.runninghub.ai/runninghub-api-doc-en/api-448184514) + +Comfy Cloud 的圖束走 `/api/v2` 的工作與素材 API,並以 object info 做就緒檢查。兩邊都要先有報價,路線才算就緒(`parity_probe_quote_required`):報價來自這位使用者自己跑過的本機同款工作流,或由擁有者輸入 `comfy_cloud_credits`/`runninghub_points`,後者標成「擁有者估計,非官方報價」。Comfy Cloud 的估計對照官方點數說明與定價頁;RunningHub 用公開工作流作者所說的約 60 POINT/4 分鐘作包絡,這支 API 沒有成文費率。實際費用只在供應商回報後出現。細節與上游表見 [運算平台](compute-platforms.md)。 ## 配方與映射 diff --git a/docs/runninghub-referral.md b/docs/runninghub-referral.md new file mode 100644 index 0000000..e44a7ec --- /dev/null +++ b/docs/runninghub-referral.md @@ -0,0 +1,21 @@ +# RunningHub 推薦連結 / Referral link + +**推廣揭露:以下連結與 QR code 使用推薦碼 `qqgzxufp`,屬於聯盟推薦入口;推薦方可能獲得獎勵。** 本頁不承諾折扣、贈點或費用不變。服務費用、點數與優惠以 RunningHub 當下公告為準。 + +[透過推薦連結註冊 RunningHub](https://www.runninghub.ai?inviteCode=qqgzxufp) + +![RunningHub 推薦註冊 QR code;推薦碼 qqgzxufp](../webui/docs/runninghub-referral.svg) + +QR code 與上方連結編碼相同的完整網址 `https://www.runninghub.ai?inviteCode=qqgzxufp`。SVG 使用原生向量圖形,沒有腳本、外部圖片、追蹤像素或自動跳轉。此檔以 segno 1.6.6 產生:`make_qr(url, error='m', boost_error=False)`,再 `save(kind='svg', scale=1, border=4, unit='mm', xmldecl=False, svgns=True)`,標題為 “RunningHub registration referral QR code”,說明為掃描後開啟帶推薦碼 `qqgzxufp` 的註冊頁、且該碼是聯盟推薦而非 API 金鑰;寫出後在根 `` 加上 `role="img"`。相同參數可重現此圖。 + +RunningHub 運算路線如何送出同一張圖、如何檢查帳戶,見 [託管運算](hosted-compute.md)。 + +## English + +**Referral disclosure:** the registration link and QR code contain affiliate referral code `qqgzxufp`. The referrer may receive a reward. No discount or credit offer is promised. Service fees, credits and offers are determined by RunningHub’s current terms. + +[Register for RunningHub via the referral link](https://www.runninghub.ai?inviteCode=qqgzxufp) + +The QR code encodes that same URL. It is native vector geometry: no script, no external image, no tracking pixel and no automatic redirect. It was generated with segno 1.6.6: `make_qr(url, error='m', boost_error=False)`, then `save(kind='svg', scale=1, border=4, unit='mm', xmldecl=False, svgns=True)`, with the title “RunningHub registration referral QR code” and a description that names referral code `qqgzxufp` and states it is an affiliate referral, not an API key. `role="img"` is set on the root ``. Those parameters reproduce the file. + +How the RunningHub lane submits the same graph and checks the account is documented in [hosted compute](hosted-compute.md). diff --git a/docs/site.md b/docs/site.md index 0d79873..686bc49 100644 --- a/docs/site.md +++ b/docs/site.md @@ -10,7 +10,7 @@ 23 項工具與建立角色都保留預填表單與說明,每個工具都有可體驗的結果。已實跑的工具顯示對應紀錄;其餘顯示「預製介面範例 · 非此工作流實測」,清楚標記素材真正的來源引擎。預製範例不證明所選工作流已執行,也不代表其品質。修改提示詞或選項只用來熟悉介面,不會重新生成。 -按下生成前只在上傳區顯示參考素材,結果區保持隱藏;重設或更換參考檔案會清除舊結果。指令改圖在生成後並排顯示青綠白原隊服與紅色上衣、深藍短褲的實測成品,清楚標示修改前後。 +按下生成前只在上傳區顯示參考素材,結果區保持隱藏;重設或更換參考檔案會清除舊結果。指令改圖在生成後並排顯示青綠白原隊服與紅色上衣、深藍短褲的實測成品,清楚標示修改前後。工具選單的「AI 指令改圖」開啟 Qwen 2.1 表單,其預製範例沿用這組 Flux Kontext 實跑的前後圖片並註明來源;Flux Kontext 表單不在選單中,實跑紀錄可從直接路徑 `#/studio/img2img` 開啟。示範頁的「AI 跳舞影片」表單保留動作影片上傳欄,用來顯示實測使用的動作影片;安裝後的 WebUI 在同一位置改用舞蹈模板選擇器,其中「使用自己的影片」可上傳檔案。 文生圖與其他已實跑的範例按下生成後,會先顯示約 2.4 秒的百分比進度,再開啟成果;進度明確標為模擬,不代表即時 GPU 狀態。系統設定減少動態效果時會快速完成。參考圖融合改用 SAM3 分割原人物,再合成夜間球場背景,保留人物原貌;[實際模型、節點與像素比對](subject-blend.md) 有獨立 GPU 紀錄。此合成不會自動補光或新增陰影。 @@ -30,7 +30,7 @@ 硬體選單提供無 NVIDIA GPU、8/12/16/24/32 GB,以及雙 24 GB 等規劃級距。顯存需求是依預設 builder 整理的估計,不是偵測結果、最低需求實測或效能基準;解析度、精度、影格數、參考素材、卸載方式及系統記憶體都會影響實際需求。這些 builder 沒有自動跨卡切分模型,雙 24 GB 以單卡 24 GB 計,不加總成 48 GB。 -選擇只影響靜態示範中的操作提示與範例可用性,不修改安裝後 WebUI 的設定、不啟用原本停用的 API,也不因選擇無 GPU 而停用使用者的本機服務。**AutoIP** 選項開放全部 23 項示範表單供探索;不代表供應商已支援每個本機工作流、節點或訓練器。實際雲端能力與目前七項已實作 API 整合分開核對。首頁的選用註冊連結與 QR code 使用聯盟推薦碼 `TEDH2FND`,詳見 [服務界線與推薦揭露](autoip-cloud-demo.md)。 +選擇只影響靜態示範中的操作提示與範例可用性,不修改安裝後 WebUI 的設定、不啟用原本停用的 API,也不因選擇無 GPU 而停用使用者的本機服務。**AutoIP** 選項開放全部 23 項示範表單供探索;不代表供應商已支援每個本機工作流、節點或訓練器。實際雲端能力與目前七項已實作 API 整合分開核對。首頁的選用註冊連結與 QR code 使用聯盟推薦碼 `TEDH2FND`,詳見 [服務界線與推薦揭露](autoip-cloud-demo.md)。RunningHub 卡片使用推薦碼 `qqgzxufp` 與連結 `https://www.runninghub.ai?inviteCode=qqgzxufp`,見 [RunningHub 推薦連結](runninghub-referral.md)。 ## 本機預覽 diff --git a/docs/workflow-audit/README.md b/docs/workflow-audit/README.md index fa0b817..57c7ad2 100644 --- a/docs/workflow-audit/README.md +++ b/docs/workflow-audit/README.md @@ -1,3 +1,6 @@ +> 歷史快照(2026-11-10,對應 95e2079);目前各運算平台狀態見 `docs/compute-platforms.md`。 +> Historical snapshot (2026-11-10, commit 95e2079). Current compute-platform status is in `docs/compute-platforms.md`. + # 上游工作流完整稽核 這份稽核逐一研究兩個上游來源的工作流、模型與節點、輸入/輸出、授權、公開版本對應位置,以及尚未完成的整合。**目錄收錄、JSON 靜態檢查、原生編輯器載入、表單/執行器串接及實際 GPU 驗證,是不同階段。這兩批上游圖檔的實際 GPU 驗證數為 0。** diff --git a/docs/workflow-audit/h3-colab-study.md b/docs/workflow-audit/h3-colab-study.md index 86df670..bd39fbb 100644 --- a/docs/workflow-audit/h3-colab-study.md +++ b/docs/workflow-audit/h3-colab-study.md @@ -1,3 +1,6 @@ +> 歷史快照(2026-11-10,對應 95e2079);目前各運算平台狀態見 `docs/compute-platforms.md`。 +> Historical snapshot (2026-11-10, commit 95e2079). Current compute-platform status is in `docs/compute-platforms.md`. + # H3 Colab 完整來源研究與整合設計 研究日期:**2026-11-10**。範圍包括 `dseditor/h3-colab-skill` 的全部追蹤檔案、三份相關 Colab 筆記本、Google 官方 CLI、必要節點、模型中繼資料與授權,以及 Web ComfyUI 的傳輸、恢復、取消與費用控制設計。**尚未存取真實 Google 帳號、驗證訂閱餘額、申請 GPU 或完成 Colab 生成。** 後文的來源檢查、離線契約測試及 SDK 匯入檢查,不構成實際 GPU 執行證據。 diff --git a/docs/workflow-audit/review-20261110.md b/docs/workflow-audit/review-20261110.md index 10570b4..8a03095 100644 --- a/docs/workflow-audit/review-20261110.md +++ b/docs/workflow-audit/review-20261110.md @@ -1,3 +1,6 @@ +> 歷史快照(2026-11-10,對應 95e2079);目前各運算平台狀態見 `docs/compute-platforms.md`。 +> Historical snapshot (2026-11-10, commit 95e2079). Current compute-platform status is in `docs/compute-platforms.md`. + # 2026-11-10 工作流整合重查 本次以 **233 個目錄項目的固定版本原始 JSON**,逐項檢查來源雜湊、圖形詳情、啟用節點、相依檢查,以及匯入政策。另以假的 ComfyUI `/object_info` 與 `/userdata` 回應,覆蓋公開工作流庫 **248 個項目**的下載、原生編輯器匯入與重複匯入。這是程式內的整合測試,未操作真實 ComfyUI 編輯器,也未執行上游程式或生成圖像。**這批上游圖的本次實際 GPU 驗證數為 0**。 diff --git a/docs/workflow-audit/templates-audit-20261110.md b/docs/workflow-audit/templates-audit-20261110.md index c011401..502b029 100644 --- a/docs/workflow-audit/templates-audit-20261110.md +++ b/docs/workflow-audit/templates-audit-20261110.md @@ -1,3 +1,6 @@ +> 歷史快照(2026-11-10,對應 95e2079);目前各運算平台狀態見 `docs/compute-platforms.md`。 +> Historical snapshot (2026-11-10, commit 95e2079). Current compute-platform status is in `docs/compute-platforms.md`. + # ComfyUI-Templates:完整整合稽核 — 2026-11-10 > **歷史基準報告:** 本報告比較的是公開版本 `95e2079ed3ae47f76ff67948f80673f410abd407`,不是後續修正後的即時狀態。新修正、測試與尚未完成的執行驗證請見 [稽核索引](README.md)。上游工作流實際 GPU 驗證數仍為 **0**。 diff --git a/docs/workflow-audit/workflows-audit-20261110.md b/docs/workflow-audit/workflows-audit-20261110.md index 346ef99..8f68f12 100644 --- a/docs/workflow-audit/workflows-audit-20261110.md +++ b/docs/workflow-audit/workflows-audit-20261110.md @@ -1,3 +1,6 @@ +> 歷史快照(2026-11-10,對應 95e2079);目前各運算平台狀態見 `docs/compute-platforms.md`。 +> Historical snapshot (2026-11-10, commit 95e2079). Current compute-platform status is in `docs/compute-platforms.md`. + # dseditor ComfyuiWorkflows:完整來源與公開應用程式稽核 > **歷史基準報告:** 本報告比較的是公開版本 `95e2079ed3ae47f76ff67948f80673f410abd407`,不是後續修正後的即時狀態。新修正、測試與尚未完成的執行驗證請見 [稽核索引](README.md)。上游工作流實際 GPU 驗證數仍為 **0**。 diff --git a/webui/docs/hardware.js b/webui/docs/hardware.js index 3838c4c..9ae0ebd 100644 --- a/webui/docs/hardware.js +++ b/webui/docs/hardware.js @@ -53,11 +53,16 @@ let cloudLink = host.querySelector('.hardware-cloud-option'); if (!cloudLink) { cloudLink = document.createElement('p');cloudLink.className='hardware-cloud-option'; - const link = document.createElement('a');link.href='https://autoip.app/register?ref=TEDH2FND&utm_source=affiliate&utm_medium=referral&utm_campaign=TEDH2FND';link.target='_blank';link.rel='sponsored noopener noreferrer'; - label(link, '考慮 AutoIP 雲端服務(推薦連結)', 'Consider AutoIP cloud services (referral)'); - const code = document.createElement('code');code.textContent='TEDH2FND'; - cloudLink.append(link,document.createTextNode(' · '),code);host.append(cloudLink); + const prefix = document.createElement('span');prefix.className='hardware-cloud-prefix'; + const autoip = document.createElement('a');autoip.className='hardware-cloud-autoip';autoip.href='https://autoip.app/register?ref=TEDH2FND&utm_source=affiliate&utm_medium=referral&utm_campaign=TEDH2FND';autoip.target='_blank';autoip.rel='sponsored noopener noreferrer'; + const autoCode = document.createElement('code');autoCode.textContent='TEDH2FND'; + const runninghub = document.createElement('a');runninghub.className='hardware-cloud-runninghub';runninghub.href='https://www.runninghub.ai?inviteCode=qqgzxufp';runninghub.target='_blank';runninghub.rel='sponsored noopener noreferrer'; + const runningCode = document.createElement('code');runningCode.textContent='qqgzxufp'; + cloudLink.append(prefix,document.createTextNode(' '),autoip,document.createTextNode(' '),autoCode,document.createTextNode(' · '),runninghub,document.createTextNode(' '),runningCode);host.append(cloudLink); } + label(cloudLink.querySelector('.hardware-cloud-prefix'), '考慮雲端服務(推薦連結):', 'Consider cloud services (referral):'); + label(cloudLink.querySelector('.hardware-cloud-autoip'), 'AutoIP', 'AutoIP'); + label(cloudLink.querySelector('.hardware-cloud-runninghub'), 'RunningHub', 'RunningHub'); cloudLink.hidden = result.allowed; let details = host.querySelector('details'); if (!details) { diff --git a/webui/docs/landing.css b/webui/docs/landing.css index 169d00f..e076a8e 100644 --- a/webui/docs/landing.css +++ b/webui/docs/landing.css @@ -53,10 +53,10 @@ .landing-step-heading { display: flex; gap: var(--space-3); justify-content: space-between; align-items: center; } .landing-copy { flex: 0 0 auto; } .project-landing pre { margin: 0; padding: var(--space-4); background: var(--panel); border: 1px solid var(--line); border-radius: var(--space-2); white-space: pre-wrap; overflow-wrap: anywhere; font-size: var(--text-sm); line-height: 1.7; } -.landing-cloud { display: grid; grid-template-columns: 1.3fr 1fr; gap: var(--space-7); align-items: start; } -.landing-cloud > div { display: grid; gap: var(--space-4); } -.landing-referral { display: grid; gap: var(--space-4); padding: var(--space-5); background: var(--bg); border-radius: var(--catalogue-radius, 12px); } -.landing-referral .landing-button { justify-self: start; } +.landing-cloud { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-7); align-items: start; } +.landing-cloud > div { grid-column: 1 / -1; display: grid; gap: var(--space-4); } +.landing-referral { display: grid; gap: var(--space-4); min-width: 0; padding: var(--space-5); background: var(--bg); border-radius: var(--catalogue-radius, 12px); } +.landing-referral .landing-button { justify-self: stretch; max-width: 100%; min-width: 0; white-space: normal; overflow-wrap: anywhere; text-align: center; } .landing-referral-code { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--space-3); } .landing-referral-code code { color: var(--blue-dark); font-weight: 700; } .landing-footer { border-top: 1px solid var(--line); padding-block: var(--space-6); } @@ -72,6 +72,9 @@ .landing-install-grid { grid-template-columns: 240px minmax(0, 1fr); gap: var(--space-5); } .landing-step-heading { align-items: start; flex-direction: column; } } +@media (max-width: 899px) { + .landing-cloud { grid-template-columns: 1fr; } +} @media (max-width: 767px) { .landing-shell { width: calc(100% - var(--space-4) * 2); } .landing-header-row { min-height: 0; padding-block: var(--space-3); gap: var(--space-2); flex-wrap: wrap; } @@ -95,6 +98,6 @@ .landing-qr img { width: 144px; height: 144px; background: var(--panel); border: 1px solid var(--line); } .landing-referral { grid-template-columns: minmax(0, 1fr) 144px; } -.landing-referral > h3, .landing-referral > .landing-referral-code, .landing-referral > .landing-button { grid-column: 1; } +.landing-referral > h3, .landing-referral > .landing-referral-code, .landing-referral > .landing-button { grid-column: 1; min-width: 0; } .landing-referral > .landing-qr { grid-column: 2; grid-row: 1 / span 3; } .landing-referral > .landing-note, .landing-referral > .landing-text-link { grid-column: 1 / -1; } diff --git a/webui/docs/landing.html b/webui/docs/landing.html index 9b69fce..c39f775 100644 --- a/webui/docs/landing.html +++ b/webui/docs/landing.html @@ -81,7 +81,7 @@

選用雲端服務

沒有本地顯卡,也有其他選擇。

沒有本地顯卡,可使用 AutoIP 的支援 API 或其 Web 介面;實際服務依模型、額度及串接支援。

這不表示每個 WebUI 工具、社群工作流或訓練流程都能直接透過 AutoIP 執行。API 整合需使用你自己的帳號與設定;此介紹頁不收集金鑰。

- + diff --git a/webui/docs/runninghub-referral.svg b/webui/docs/runninghub-referral.svg new file mode 100644 index 0000000..5df2b96 --- /dev/null +++ b/webui/docs/runninghub-referral.svg @@ -0,0 +1 @@ +RunningHub registration referral QR codeScan to open RunningHub registration with referral code qqgzxufp. Affiliate referral; not an API key. From 0b5765d5af79a8c7a381ad1292245519b4c1227a Mon Sep 17 00:00:00 2001 From: Ted H Date: Sat, 14 Nov 2026 20:12:36 -0500 Subject: [PATCH 4/7] Mount the compute screens in documentation mode and add the demo recorder The application no longer hides the compute settings, the provider console and the per-form platform choice in documentation mode. Add the recorder that captures the canned responses from an isolated, empty server, and align the character-angles walkthrough with the current Qwen-Image 2.1 implementation. Co-Authored-By: Claude Fable 5.2 --- scripts/build_docs.py | 5 +- scripts/demo_catalog.py | 2 +- scripts/record_demo_compute.py | 185 +++++++++++++++++++++++++++++++ scripts/recorded_demo_catalog.py | 22 +--- webui/static/app.js | 24 ++-- webui/static/index.html | 2 +- 6 files changed, 207 insertions(+), 33 deletions(-) create mode 100644 scripts/record_demo_compute.py diff --git a/scripts/build_docs.py b/scripts/build_docs.py index b670a2a..5fdea59 100644 --- a/scripts/build_docs.py +++ b/scripts/build_docs.py @@ -128,7 +128,9 @@ def site_html(root): html = html.replace('/static/', '../assets/') html = html.replace('Web ComfyUI', 'Web ComfyUI · 介面示範') html = html.replace('class="auth-gate"', 'class="auth-gate hidden"') - policy = "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; object-src 'none'; base-uri 'self'; form-action 'none'" + # The app uses style attributes for its existing controls. Permit those in + # the demo while keeping scripts, stylesheets and network sources restricted. + policy = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; object-src 'none'; base-uri 'self'; form-action 'none'" html = html.replace('', '\n\n\n\n') banner = '''''' html = html.replace('', '' + banner, 1) @@ -182,6 +184,7 @@ def build(root: Path = ROOT, output: Path | None = None) -> dict: app_guide['graphs'] = graphs(root, app_guide) app_guide['demos'] = demos(app_guide) app_guide['translations'] = source_json(root, 'manifests/app_guides/en.json') + app_guide['computeDemo'] = source_json(root, 'webui/docs/demo-compute.json') from scripts.hardware_catalog import catalog as hardware_catalog app_guide['hardware'] = hardware_catalog(app_guide) execution_summary = provenance_summary(source_json(root, 'webui/docs/examples/provenance.json')) diff --git a/scripts/demo_catalog.py b/scripts/demo_catalog.py index 0b69c69..d14a96b 100644 --- a/scripts/demo_catalog.py +++ b/scripts/demo_catalog.py @@ -92,7 +92,7 @@ 'img2img': ['Upload an image and enter an editing instruction.', 'Scale with FluxKontextImageScale, encode with AE, and supply ReferenceLatent.', 'Apply FluxGuidance, sample, decode, and save.'], 'anime-scene-card': ['Choose an approved character outfit and scene from the character page.', 'Read the character alpha mask and invert it for compositing.', 'Composite with ImageCompositeMasked and save.'], 'image-blend': ['Upload the original subject and a target background, then name the subject to keep.', 'SAM3 detects the subject and creates a binary mask; resize only the background to match the original.', 'Composite the original subject pixels over the background; no diffusion sampler redraws the face or clothing.'], - 'character-angles': ['Prepare a clear, near-frontal reference face with permission.', 'Analyze it with InsightFace and condition SDXL with InstantID and ControlNet.', 'Sample the requested scene or angle and decode with the checkpoint VAE.'], + 'character-angles': ["Upload one clear, near-frontal photo of a real person's face, then enter the scene/angle description and the number of candidates (1–6).", 'Every candidate uses the original photo as plus one fixed view, in this order: left-facing three-quarter, right-facing three-quarter, frontal, left profile, right profile, frontal with the head slightly raised (camera just below eye level).', 'Each candidate is sampled at the 1024 resolution setting, decoded and saved on its own, with the seed increased by 1 per candidate; a generated image is never used as the reference for the next one.'], 'clipmode-character-photoshoot': ['Choose a character, scene, aspect ratio, and seed on the character page.', 'The installed server binds identity references and models, using InstantID / ReActor or a configured character LoRA.', 'Generate locally, check identity and person consistency, and keep accepted results.'], 'img2video': ['Upload an opening image and describe motion and aspect ratio.', 'Encode with CLIP Vision, create WanImageToVideo conditioning, and load LightX2V LoRA.', 'Defaults are 81 frames, 16 FPS, and 6 steps; decode and assemble MP4.'], 'first-last-frame': ['The graph builder accepts an opening and closing frame.', 'Create video latents from both image conditions and LightX2V LoRA.', 'Sample and decode video frames.'], diff --git a/scripts/record_demo_compute.py b/scripts/record_demo_compute.py new file mode 100644 index 0000000..0d30e9f --- /dev/null +++ b/scripts/record_demo_compute.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Record empty compute screens from a fresh, loopback-only server. + +Run with the Web UI Python dependencies installed. No .env is read, no existing +state is reused, and the child server is forbidden to open outgoing sockets. +These receipts show empty screens; they are not evidence of GPU generation. +""" +from __future__ import annotations + +import argparse +import http.cookiejar +import json +import os +from pathlib import Path +import re +import socket +import subprocess +import sys +import tempfile +import time +import urllib.request +import urllib.error + +ROOT = Path(__file__).resolve().parents[1] +OUTPUT = ROOT / 'webui/docs/demo-compute.json' +# Initial reads and reads on opening a panel/details, enumerated from compute-*.js, +# colab.js and provider-fabric.js. Empty state has no account/job/asset detail IDs. +ENDPOINTS = ( + '/api/compute/connections', '/api/colab/session', + '/api/compute/platform-admin', '/api/compute/capabilities', + '/api/compute/preferences', '/api/compute/jobs', + '/api/compute/parity/cases', '/api/compute/pipeline-recipes', + '/api/compute/pipeline-features', '/api/compute/pipelines', '/api/colab', + '/api/providers', '/api/provider-characters', + '/api/assets?kind=image', '/api/history?max_items=500&scope=own', +) +EMAIL = re.compile(r'[A-Za-z0-9.!#$%&\'*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}') +SECRET = re.compile(r'(?i)(?:\b(?:sk|rk|pk)[-_][a-z0-9_-]{16,}|\b(?:gh[pousr]_|github_pat_|AKIA)[a-z0-9_]{16,}|\bBearer\s+\S+|\beyJ[a-z0-9_-]+\.[a-z0-9_-]+\.[a-z0-9_-]+|\b[a-f0-9]{32,}\b|-----BEGIN .*PRIVATE KEY)') +SECRET_FIELDS = {'password', 'api_key', 'apikey', 'credential', 'credential_value', + 'token', 'access_token', 'refresh_token', 'client_secret', + 'authorization', 'cookie', 'session_cookie', 'private_key'} +STAMP = re.compile(r'^\d{4}-\d\d-\d\d[T ]\d\d:\d\d:\d\d') +UUID = re.compile(r'^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$', re.I) + + +def validate(value, trail='$'): + """Fail closed without echoing a potentially sensitive value in an error.""" + if isinstance(value, dict): + for key, child in value.items(): + if key.lower() in SECRET_FIELDS and child not in (None, '', False): + raise ValueError(f'Credential field at {trail}.{key}') + validate(key, trail + '.') + validate(child, trail + '.' + key) + elif isinstance(value, list): + for index, child in enumerate(value): + validate(child, f'{trail}[{index}]') + elif isinstance(value, str): + if any(not email.endswith('@example.invalid') for email in EMAIL.findall(value)): + raise ValueError(f'Non-example e-mail at {trail}') + # HTTP request paths are relative web references, not filesystem paths. + if re.search(r'(?:^|[\s"\'])/(?!api/)[\w.~/-]+|[A-Za-z]:[\\/]|\\\\[^\\]+\\', value): + raise ValueError(f'Absolute filesystem path at {trail}') + if SECRET.search(value): + raise ValueError(f'Token/key-shaped value at {trail}') + + +def normalize(value, identity, key='', ids=None): + ids = {} if ids is None else ids + if isinstance(value, dict): + return {normalize(k, identity, ids=ids): normalize(v, identity, k, ids) + for k, v in value.items()} + if isinstance(value, list): + return [normalize(v, identity, key, ids) for v in value] + if isinstance(value, str): + value = EMAIL.sub(lambda match: 'demo@example.invalid' + if match.group() == identity['email'] else match.group(), value) + if value == identity.get('displayName'): + value = 'Demo' + if STAMP.match(value): + return '2026-11-14T00:00:00Z' + if UUID.fullmatch(value): + return ids.setdefault(value, f'demo-id-{len(ids) + 1}') + if isinstance(value, (int, float)) and not isinstance(value, bool) and ( + key.endswith(('_at', '_timestamp')) or key in {'created', 'updated', 'now'} + ): + return 0 + return value + + +def serve(port, identity_file): + # Import only after the same launcher configuration used by --no-env. + sys.path.insert(0, str(ROOT)) + import run + run.prepare_environment(port=port) + def offline(event, args): + if event == 'socket.connect': + raise PermissionError('Demo recorder forbids outgoing connections') + sys.addaudithook(offline) + sys.path.insert(0, str(ROOT / 'webui')) + import server + identity_file.write_text(json.dumps(server.LOCAL_SESSION_USER), encoding='utf-8') + sys.argv = [str(ROOT / 'webui/server.py'), '--host', '127.0.0.1', '--port', str(port)] + server.main() + + +def record(): + with tempfile.TemporaryDirectory(prefix='demo-compute-') as directory: + state = Path(directory) + (state / 'home').mkdir() + with socket.socket() as sock: + sock.bind(('127.0.0.1', 0)) + port = sock.getsockname()[1] + env = {key: os.environ[key] for key in ('PATH', 'LANG') if key in os.environ} + env.update({ + 'HOME': str(state / 'home'), + 'USERPROFILE': str(state / 'home'), + 'PYTHONPATH': os.pathsep.join(path for path in sys.path if path), + 'COMFY_HOME': str(state / 'absent-comfy'), + 'WEB_COMFYUI_DATA_DIR': str(state / 'data'), + 'WEB_COMFYUI_CACHE_DIR': str(state / 'cache'), + 'WEB_COMFYUI_TMP_DIR': str(state / 'tmp'), + 'XDG_DATA_HOME': str(state / 'xdg-data'), + 'XDG_CONFIG_HOME': str(state / 'xdg-config'), + 'XDG_CACHE_HOME': str(state / 'xdg-cache'), + 'CASTLE_COMFY_ADMISSION_LOCK': str(state / 'gpu.lock'), + 'PYTHONDONTWRITEBYTECODE': '1', + }) + identity_file = state / 'identity.json' + base = f'http://127.0.0.1:{port}' + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), + urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())) + def call(path, data=None): + request = urllib.request.Request(base + path, + data=None if data is None else json.dumps(data).encode(), + headers={'Content-Type': 'application/json', 'Origin': base}) + try: + with opener.open(request, timeout=30) as response: + return {'status': response.status, 'body': json.load(response)} + except urllib.error.HTTPError as error: + return {'status': error.code, 'body': json.load(error)} + with (state / 'server.log').open('w') as log: + process = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), + '--serve', str(port), str(identity_file)], cwd=ROOT, env=env, + stdout=log, stderr=log) + try: + for _ in range(300): + try: + status = call('/api/auth/status')['body'] + break + except OSError: + if process.poll() is not None: + raise RuntimeError('Temporary server failed to start') from None + time.sleep(.05) + else: + raise RuntimeError('Temporary server readiness timed out') + if status['configured']: + raise RuntimeError('Recorder requires unconfigured first-run state') + password = {'password': 'synthetic-demo-password-1'} + for path in ('/api/auth/setup', '/api/auth/login'): + if call(path, password)['status'] != 200: + raise RuntimeError('Temporary first-run authentication failed') + identity = json.loads(identity_file.read_text(encoding='utf-8')) + ids = {} + result = {path: normalize(call(path), identity, ids=ids) for path in ENDPOINTS} + validate(result) + OUTPUT.write_text(json.dumps(result, ensure_ascii=False, sort_keys=True, + indent=2) + '\n', encoding='utf-8') + finally: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + print(f'Recorded {len(result)} empty-state responses.') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--serve', nargs=2, metavar=('PORT', 'IDENTITY_FILE'), help=argparse.SUPPRESS) + args = parser.parse_args() + if args.serve: + serve(int(args.serve[0]), Path(args.serve[1])) + else: + record() diff --git a/scripts/recorded_demo_catalog.py b/scripts/recorded_demo_catalog.py index bec6350..a21fa1b 100644 --- a/scripts/recorded_demo_catalog.py +++ b/scripts/recorded_demo_catalog.py @@ -225,16 +225,9 @@ 'doll, plastic, airbrushed skin, overexposed, oversized eyes, ' 'huge eyes, giant eyes, juvenile face, child, bad anatomy, ' 'distorted fingers, text, logo, watermark, cropped head', - 'width': 896, - 'height': 1152, 'steps': 36, - 'cfg': 5.5, - 'weight': 0.6, 'batchSize': 2, - 'seed': 2026102325, - 'sampler': 'dpmpp_2m', - 'scheduler': 'karras', - 'aspect': '896x1152'}, + 'seed': 2026102325}, 'prefill_en': {'positive': 'RAW candid close-up photograph of a 26-year-old adult ' 'Taiwanese woman, natural expression, realistic brown eyes, ' 'realistic human facial proportions, realistic adult face, ' @@ -248,16 +241,9 @@ 'eyes, huge eyes, giant eyes, juvenile face, child, bad ' 'anatomy, distorted fingers, text, logo, watermark, cropped ' 'head', - 'width': 896, - 'height': 1152, 'steps': 36, - 'cfg': 5.5, - 'weight': 0.6, 'batchSize': 2, - 'seed': 2026102325, - 'sampler': 'dpmpp_2m', - 'scheduler': 'karras', - 'aspect': '896x1152'}, + 'seed': 2026102325}, 'inputs': [{'src': './assets/examples/cheer-face-reference.webp', 'alt': '裁切後的臉部參考圖', 'alt_en': 'Cropped face reference', @@ -304,11 +290,11 @@ 'alt_en': 'Portrait candidate 2 from the same recorded run'}], 'run_id': 'cheer-instantid-v3'}, 'note': '這是已在本機 RTX 5090 完成的實測記錄;此網站只重播成果,不會依你輸入即時生成。角色為原創虛構成年人。 ' - '保留模型原始候選,臉部細節與寫實度仍須自行挑選;沒有後製修臉。', + '保留模型原始候選,臉部細節與寫實度仍須自行挑選;沒有後製修臉。 此示範由先前的 SDXL + InstantID 版本實測產生;目前的功能改用 Qwen 2.1,結果會不同。', 'note_en': 'Recorded on a local RTX 5090, not generated from your input on this ' 'website. The performer is an original fictional adult. These are ' 'unretouched model candidates; facial detail and realism still require ' - 'selection.'}, + 'selection. This example was recorded with the earlier SDXL + InstantID version; the feature now uses Qwen 2.1, so results will differ.'}, 'img2video': {'title': '走近鏡頭,揮手打招呼', 'title_en': 'Walk toward the camera and wave hello', 'prompt': 'The adult woman takes two small natural steps towards the camera, smiles brightly, ' diff --git a/webui/static/app.js b/webui/static/app.js index a00b433..7b9be79 100644 --- a/webui/static/app.js +++ b/webui/static/app.js @@ -587,7 +587,7 @@ function parseRoute() { return { view: "characters" }; } if (!parts.length) return { view: "characters" }; - if (parts[0] === "compute-production" && !window.WebComfyDocs) return { view: "compute-production" }; + if (parts[0] === "compute-production") return { view: "compute-production" }; if (parts[0] === "studio") { if (parts.length <= 2) return { view: "studio", featureId: parts[1] || "" }; return { view: "characters" }; @@ -1470,7 +1470,7 @@ function renderAccountMenuContent({ managementOnly = false } = {}) { h("span", { text: "服務狀態" }), h("strong", { text: $("servicePill").textContent || "未知" }), ])); - if (!window.WebComfyDocs && window.ComputeSettings) wrap.appendChild(shellMenuButton("我的運算平台", () => openComputeSettings(window.matchMedia("(max-width: 767px)").matches ? $("moreMenuBtn") : $("managementMenuBtn")))); + if (window.ComputeSettings) wrap.appendChild(shellMenuButton("我的運算平台", () => openComputeSettings(window.matchMedia("(max-width: 767px)").matches ? $("moreMenuBtn") : $("managementMenuBtn")))); wrap.appendChild(shellMenuButton("重新整理", refreshAllData)); wrap.appendChild(shellMenuButton("角色創作資源中心", () => navigate({ view: "resources" }))); } @@ -1493,7 +1493,7 @@ function renderAccountMenuContent({ managementOnly = false } = {}) { wrap.appendChild(shellMenuButton("工作流監控", () => navigate({ view: "orchestrator" }))); wrap.appendChild(h("a", { class: "shell-menu-row", href: "/admin", text: "管理中心" })); wrap.appendChild(shellMenuButton("使用者管理", () => navigate({ view: "admin-users" }))); - if (!window.WebComfyDocs && window.WebComfyColab) wrap.appendChild(shellMenuButton("Google Colab 帳號", () => openColabAccounts(window.matchMedia("(max-width: 767px)").matches ? $("moreMenuBtn") : $("managementMenuBtn")))); + if (window.WebComfyColab) wrap.appendChild(shellMenuButton("Google Colab 帳號", () => openColabAccounts(window.matchMedia("(max-width: 767px)").matches ? $("moreMenuBtn") : $("managementMenuBtn")))); } if (!managementOnly) { wrap.appendChild(h("hr", { class: "shell-menu-divider" })); @@ -2190,7 +2190,7 @@ function statusDot(feature) { function renderSidebar() { const wrap = $("sidebarGroups"); clear(wrap); - if (!window.WebComfyDocs && window.ComputePipeline) wrap.appendChild(h("button", {class: `side-tool${currentRoute.view === "compute-production" ? " active" : ""}`, type: "button", text: "多步製作", onclick: () => navigate({view:"compute-production"})})); + if (window.ComputePipeline) wrap.appendChild(h("button", {class: `side-tool${currentRoute.view === "compute-production" ? " active" : ""}`, type: "button", text: "多步製作", onclick: () => navigate({view:"compute-production"})})); for (const studio of studios) { const list = studioFeatures(studio.id); if (!list.length) continue; @@ -2271,7 +2271,7 @@ function renderWorkspace() { else if (currentRoute.view === "character-library") renderCharacterLibraryRoute(); else if (currentRoute.view === "character-wardrobe") renderCharacterWardrobeRoute(); else if (currentRoute.view === "character-settings") renderCharacterSettingsRoute(); - else if (currentRoute.view === "compute-production" && window.ComputePipeline && !window.WebComfyDocs) { + else if (currentRoute.view === "compute-production" && window.ComputePipeline) { if ($("workspace").querySelector('.compute-production[data-compute-pipeline-mounted="true"]')) return; const host = beginWorkspaceRender(); window.ComputePipeline.mount(host, {api, onBack: () => navigate({view:"studio"})}); @@ -2358,7 +2358,7 @@ function providerFabricCharacterVisualClass(character) { function renderProviderFabricView() { const ws = beginWorkspaceRender("workspace-route-root provider-fabric-route"); - if (!window.WebComfyDocs && window.WebComfyColab) window.WebComfyColab.mount(ws, {api, openSheet}); + if (window.WebComfyColab) window.WebComfyColab.mount(ws, {api, openSheet}); const host = h("div", { class: "provider-fabric-host" }); ws.appendChild(host); if (!window.CastleProviderFabric || typeof window.CastleProviderFabric.mount !== "function") { @@ -8479,7 +8479,7 @@ function renderStage() { } ws.appendChild(h("div", { class: "tool-view" }, [ renderStudioToolSelector(feature), - !window.WebComfyDocs && !activeCharacter() && window.ComputePipeline ? h("button", {class:"ghost small compute-production-entry", type:"button", text:"多步製作", onclick:()=>navigate({view:"compute-production"})}) : null, + !activeCharacter() && window.ComputePipeline ? h("button", {class:"ghost small compute-production-entry", type:"button", text:"多步製作", onclick:()=>navigate({view:"compute-production"})}) : null, renderFeaturePanel(feature), renderRecentPanel(), ])); @@ -8578,7 +8578,7 @@ function computeActionReason(form, action, state, feature) { } function mountComputeForm(form, feature, {character = null, capability = null, state = {}, getRequest = null, onAvailability = null} = {}) { - if (!window.ComputePlacement || window.WebComfyDocs || !form) return; + if (!window.ComputePlacement || !form) return; const currentFeature = () => typeof form.computeFeature === "function" ? form.computeFeature() : feature; const currentCapability = () => character ? enabledFeatureCapability(character, currentFeature().id) : capability; const request = getRequest || (() => ({featureId: currentFeature().id, settings: collectSettings(currentFeature()), @@ -13345,12 +13345,12 @@ function renderOrchestratorView() { // ---- admin users ---------------------------------------------------------- function openComputeSettings(opener, initialSection = "connections") { - if (!currentUser || window.WebComfyDocs || !window.ComputeSettings) return; + if (!currentUser || !window.ComputeSettings) return; window.ComputeSettings.open(opener, {api, openSheet, isAdmin: isAdmin(), initialSection}); } function openColabAccounts(opener) { - if (!currentUser || window.WebComfyDocs || !window.WebComfyColab) return; + if (!currentUser || !window.WebComfyColab) return; window.WebComfyColab.openAccounts(opener, {api, openSheet}); } @@ -13363,8 +13363,8 @@ function renderAdminHome() { h("button", { class: "shell-menu-row", text: "採集圖片與影片", onclick: openMaterialCollect }), h("button", { class: "shell-menu-row", text: "外部角色與資源", onclick: () => navigate({ view: "resources" }) }), h("button", { class: "shell-menu-row", text: "使用者管理", onclick: () => navigate({ view: "admin-users" }) }), - !window.WebComfyDocs && window.ComputeSettings ? h("button", {class:"shell-menu-row", type:"button", text:"我的運算平台", "aria-haspopup":"dialog", onclick:event=>openComputeSettings(event.currentTarget)}) : null, - !window.WebComfyDocs && window.WebComfyColab ? h("button", { class: "shell-menu-row", type: "button", text: "Google Colab 帳號", "aria-haspopup": "dialog", onclick: event => openColabAccounts(event.currentTarget) }) : null, + window.ComputeSettings ? h("button", {class:"shell-menu-row", type:"button", text:"我的運算平台", "aria-haspopup":"dialog", onclick:event=>openComputeSettings(event.currentTarget)}) : null, + window.WebComfyColab ? h("button", { class: "shell-menu-row", type: "button", text: "Google Colab 帳號", "aria-haspopup": "dialog", onclick: event => openColabAccounts(event.currentTarget) }) : null, h("button", { class: "shell-menu-row", text: "工作流監控", onclick: () => navigate({ view: "orchestrator" }) }), h("a", { class: "shell-menu-row", href: "http://127.0.0.1:8188/", target: "_blank", rel: "noopener noreferrer", text: "開啟 ComfyUI 節點編輯器 ↗" }), ]), diff --git a/webui/static/index.html b/webui/static/index.html index b7ac422..27feb29 100644 --- a/webui/static/index.html +++ b/webui/static/index.html @@ -121,6 +121,6 @@

設定密碼

- + From c2cc890f716f3141e4be5591603fe932d68299fa Mon Sep 17 00:00:00 2001 From: Ted H Date: Sat, 14 Nov 2026 20:12:36 -0500 Subject: [PATCH 5/7] Test the demo compute screens Cover both languages at phone and desktop widths, the refusal of writes, and the absence of requests the demo cannot answer. Co-Authored-By: Claude Fable 5.2 --- scripts/test_docs_browser.py | 131 +++++++++++++++++++++++++++++++++++ tests/test_docs_site.py | 62 ++++++++++++++++- 2 files changed, 190 insertions(+), 3 deletions(-) diff --git a/scripts/test_docs_browser.py b/scripts/test_docs_browser.py index 60414af..9c1bc00 100644 --- a/scripts/test_docs_browser.py +++ b/scripts/test_docs_browser.py @@ -1,5 +1,6 @@ """Exercise the built guide with Chromium under the real Pages project subpath.""" import json +import os from pathlib import Path import shutil import sys @@ -310,3 +311,133 @@ def do_POST(self): assert any('/downloads/' in path for path in requests) finally: server.shutdown(); server.server_close() + + +@pytest.mark.parametrize('language', ['zh-Hant', 'en']) +@pytest.mark.parametrize('width', [390, 1440]) +def test_compute_screens_are_canned_and_read_only(tmp_path, language, width): + from functools import partial + from http.server import SimpleHTTPRequestHandler + playwright = pytest.importorskip('playwright.sync_api') + browser = shutil.which('chromium') + if not browser: + pytest.skip('Chromium not installed') + output = tmp_path / 'Web_Comfyui' + build(ROOT, output) + requests = [] + + class Handler(SimpleHTTPRequestHandler): + def log_message(self, *args): pass + def do_GET(self): + requests.append(self.path) + super().do_GET() + def do_POST(self): + requests.append('POST ' + self.path) + self.send_error(405) + + server = ThreadingHTTPServer(('127.0.0.1', 0), partial(Handler, directory=str(tmp_path))) + threading.Thread(target=server.serve_forever, daemon=True).start() + origin = f'http://127.0.0.1:{server.server_port}' + try: + with playwright.sync_playwright() as driver: + with driver.chromium.launch(executable_path=browser, args=['--no-sandbox', '--disable-dev-shm-usage']) as instance: + page = instance.new_page(viewport={'width': width, 'height': 1000}) + errors, external = [], [] + page.on('pageerror', lambda error: errors.append(str(error))) + page.on('console', lambda message: errors.append(message.text) if message.type == 'error' else None) + def local_only(route): + if route.request.url.startswith(origin + '/'): + route.continue_() + else: + external.append(route.request.url) + route.abort() + page.route('**/*', local_only) + page.goto(f'{origin}/Web_Comfyui/demo/?lang={language}') + try: + page.locator('form[data-demo-id="text2img"] .compute-placement').wait_for() + except playwright.TimeoutError: + pytest.fail(f'Compute chooser did not mount: {errors}; {page.locator("body").inner_text()[:2500]}') + page.wait_for_function("document.documentElement.lang === " + json.dumps(language)) + page.locator('.compute-placement > .docs-compute-action').wait_for() + page.evaluate("""() => { + window.computeReads = []; + const original = window.fetch; + window.fetch = (input, options) => { + computeReads.push(typeof input === 'string' ? input : input.url); + return original(input, options); + }; + }""") + notice = ('Documentation site: screens only. Nothing connects, no keys are accepted and nothing is saved.' + if language == 'en' else '說明站只展示畫面:不會連線、不接受金鑰,也不會保存設定。') + placeholder = ('Keys are not accepted on the documentation site' if language == 'en' else '說明站不接受金鑰') + def check_screen(selector, name): + screen = page.locator(selector) + assert screen.locator(':scope > .docs-compute-notice').inner_text() == notice + for credential in screen.locator('input[type=password]').all(): + assert credential.is_disabled() + assert credential.input_value() == '' + assert credential.get_attribute('placeholder') == placeholder + assert page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1') + shots = os.environ.get('WEB_COMFYUI_TEST_SCREENSHOTS') + if shots: + target = Path(shots); target.mkdir(parents=True, exist_ok=True) + in_sheet = screen.evaluate("screen => {const sheet = screen.closest('[role=dialog]'); if (!sheet) return false; sheet.querySelector('.sheet-body').scrollTop = 0; return true;}") + page.screenshot(path=str(target / f'{name}-{language}-{width}.png'), full_page=not in_sheet) + + def menu(label): + # The ported desktop app keeps platforms/resources in Account, + # and Colab accounts in Management; mobile combines both. + selector = '#moreMenuBtn' if width < 768 else ('#managementMenuBtn' if label == 'Google Colab 帳號' else '#identityChip') + page.locator(selector).click() + translated = page.evaluate('(text) => WebComfyI18n.t(text)', label) + page.locator('.shell-menu-row').filter(has_text=translated).first.click() + + check_screen('.compute-placement', 'studio') + menu('我的運算平台') + cards = page.locator('.compute-settings [data-provider]') + cards.nth(4).wait_for() + for lane, label in [('local', '本機'), ('colab', 'Google Colab'), ('autoip', 'AutoIP'), + ('comfy_cloud', 'Comfy Cloud'), ('runninghub', 'RunningHub')]: + heading = page.locator(f'.compute-settings [data-provider="{lane}"] h3') + heading.scroll_into_view_if_needed() + assert heading.is_visible() + assert heading.inner_text() == page.evaluate('(text) => WebComfyI18n.t(text)', label) + page.locator('.console-exceptions summary').click() + page.locator('.console-exceptions select').first.wait_for() + assert page.locator('.console-exceptions select').first.locator('option').count() > 0 + assert '/api/compute/capabilities' in page.evaluate('computeReads') + shots = os.environ.get('WEB_COMFYUI_TEST_SCREENSHOTS') + if shots: + page.locator('.console-exceptions').screenshot(path=str(Path(shots) / f'platform-exceptions-{language}-{width}.png')) + check_screen('.compute-settings', 'platforms') + tabs = page.locator('.compute-settings > .console-actions button') + if tabs.count() == 2: + tabs.nth(1).click() + page.locator('.compute-settings > div:last-child > h3').wait_for() + assert page.locator('.console-admin-row').count() == 0 + assert '/api/compute/platform-admin' in page.evaluate('computeReads') + check_screen('.compute-settings', 'platform-admin') + tabs.nth(0).click() + # A real mutation reaches only the 405 documentation adapter. + page.locator('.compute-settings .console-test button').filter(has_text=page.evaluate("WebComfyI18n.t('儲存金鑰')")).first.click() + page.wait_for_function("document.querySelector('.compute-settings .docs-compute-action')?.textContent.length > 0") + assert page.evaluate("fetch('/api/compute/connections').then(r=>r.json()).then(d=>d.connections.every(c=>!c.credential_present))") + page.locator('.sheet-close').click() + page.locator('.compute-production-entry').click() + page.locator('.compute-production form').wait_for() + check_screen('.compute-production', 'production') + menu('Google Colab 帳號') + page.locator('.colab-content select').first.wait_for() + assert page.locator('.colab-content select').first.locator('option').count() == 1 + assert page.locator('.colab-content select').first.input_value() == '' + check_screen('.colab-content', 'colab') + page.locator('.sheet-close').click() + menu('角色創作資源中心') + page.locator('castle-provider-fabric .provider-fabric__inner').wait_for() + check_screen('castle-provider-fabric', 'resources') + assert page.evaluate('WebComfyDocs.unknownRequests') == [] + assert errors == [] + assert external == [] + assert not any('/api/' in request or request.startswith('POST ') for request in requests) + finally: + server.shutdown(); server.server_close() diff --git a/tests/test_docs_site.py b/tests/test_docs_site.py index 7fc13fb..153a6f8 100644 --- a/tests/test_docs_site.py +++ b/tests/test_docs_site.py @@ -21,6 +21,7 @@ 'manifests/workflow_coverage/imported_sources.json', 'manifests/community_recipes/recipes.json', 'manifests/app_guides/en.json', + 'webui/docs/demo-compute.json', ) @@ -359,8 +360,10 @@ def test_docs_adapter_rejects_mutations_and_never_fetches_unknown_or_local_urls( const fs = require('node:fs'); const vm = require('node:vm'); const calls = [], listeners = {}; -const password = {value: 'synthetic-old-value', disabled: false}; -const app = {studios: [], features: [], guides: []}; +const password = {type: 'password', value: 'synthetic-old-value', disabled: false}; +const app = {studios: [], features: [], guides: [], computeDemo: { + '/api/compute/capabilities': {status: 200, body: {features: [{id: 'synthetic-feature'}]}} +}}; const library = {items: []}; const window = {addEventListener() {}, fetch: async (url, options) => { calls.push({url: String(url), options}); @@ -371,7 +374,7 @@ def test_docs_adapter_rejects_mutations_and_never_fetches_unknown_or_local_urls( }); const context = {window, URL, Request, Response, console, setTimeout, location: {href: 'https://example.test/Web_Comfyui/demo/', origin: 'https://example.test', hash: '#/studio/text2img'}, - document: {documentElement: {}, querySelectorAll: () => [password], getElementById: () => null, + document: {documentElement: {}, querySelectorAll: selector => selector === 'input' ? [password] : [], getElementById: () => null, addEventListener: (name, callback) => {listeners[name] = callback;}}, history: {replaceState() {}}, navigator: {sendBeacon() {throw Error('Native beacon must not run');}}, MutationObserver: class {observe() {}} @@ -392,6 +395,12 @@ def test_docs_adapter_rejects_mutations_and_never_fetches_unknown_or_local_urls( assert.equal((await window.fetch('http://127.0.0.1:8188/object_info')).status, 405); assert.equal((await window.fetch('https://external.example/api')).status, 405); assert.equal((await window.fetch('/api/characters')).status, 200); + const capabilities = await window.fetch('/api/compute/capabilities'); + assert.equal(capabilities.status, 200); + assert.equal((await capabilities.json()).features[0].id, 'synthetic-feature'); + const history = await (await window.fetch('/api/history?max_items=500&scope=own')).json(); + for (const key of ['images', 'jobs', 'recent_errors']) assert.deepEqual(history[key], []); + assert.equal(window.WebComfyDocs.unknownRequests.join(','), '/api/unrecognized-private-api'); assert.equal(calls.length, 2); assert.equal(context.navigator.sendBeacon('/api/write', 'data'), false); assert.throws(() => new window.WebSocket('ws://127.0.0.1:8188')); @@ -410,3 +419,50 @@ def test_docs_adapter_rejects_mutations_and_never_fetches_unknown_or_local_urls( result = subprocess.run(['node', '-e', script, str(source / 'webui/docs/docs.js')], capture_output=True, text=True, timeout=20) assert result.returncode == 0, result.stderr + + +def test_compute_demo_is_embedded_without_extra_native_requests(source, tmp_path): + from scripts.record_demo_compute import ENDPOINTS, validate + recorded = read_json(ROOT / 'webui/docs/demo-compute.json') + assert set(recorded) == set(ENDPOINTS) + validate(recorded) + assert '/home/' not in json.dumps(recorded) + assert recorded['/api/compute/connections']['body']['owner'] == 'demo@example.invalid' + assert [row['provider'] for row in recorded['/api/compute/connections']['body']['connections']] == [ + 'local', 'colab', 'autoip', 'comfy_cloud', 'runninghub'] + output = tmp_path / 'compute-site' + build_docs.build(source, output) + assert read_json(output / 'app-guide.json')['computeDemo'] == recorded + assert (ROOT / 'webui/docs/docs.js').read_text().count('nativeFetch(') == 2 + + +@pytest.mark.parametrize('value', [ + 'person@outside.invalid', '/home/synthetic/data.json', '/tmp/synthetic', + r'C:\synthetic\data.json', 'sk-' + 'synthetic' * 5, + 'a' * 64, {'access_token': 'synthetic-test-token-1'}, +]) +def test_compute_recorder_rejects_unsafe_responses_without_echo(value): + from scripts.record_demo_compute import validate + with pytest.raises(ValueError) as caught: + validate({'response': value}) + assert str(value) not in str(caught.value) + + +def test_compute_recorder_normalization_preserves_evidence_and_only_maps_builtin_identity(): + from scripts.record_demo_compute import normalize, validate + identity = {'email': 'built-in@example.invalid', 'displayName': 'Built in'} + original = {'owner': identity['email'], 'displayName': identity['displayName'], + 'created_at': 1794614400, 'updated_at': '2026-11-15T01:02:03Z', + 'id': '00000000-0000-4000-8000-000000000001', + 'feature': 'character-angles', 'other': 'person@outside.invalid'} + normalized = normalize(original, identity) + assert normalized['owner'] == 'demo@example.invalid' + assert normalized['displayName'] == 'Demo' + assert normalized['created_at'] == 0 + assert normalized['updated_at'] == '2026-11-14T00:00:00Z' + assert normalized['id'] == 'demo-id-1' + assert normalized['feature'] == original['feature'] + assert normalized['other'] == original['other'] + assert normalize('prefix' + identity['email'], identity) == 'prefix' + identity['email'] + with pytest.raises(ValueError, match='Non-example'): + validate(normalized) From 22dfc887a58c1d6a13782fe4cd0dbae96d289ecc Mon Sep 17 00:00:00 2001 From: Ted H Date: Sat, 14 Nov 2026 20:12:36 -0500 Subject: [PATCH 6/7] Serve the demo compute screens from recorded data The documentation runtime answers read requests from the recorded file, refuses every write and disables key fields. Add the recorded responses and a section in the site notes that says what the demo shows and what it cannot do. Co-Authored-By: Claude Fable 5.2 --- docs/site.md | 17 + webui/docs/demo-compute.json | 3616 ++++++++++++++++++++++++++++++++++ webui/docs/docs.js | 61 +- 3 files changed, 3686 insertions(+), 8 deletions(-) create mode 100644 webui/docs/demo-compute.json diff --git a/docs/site.md b/docs/site.md index 686bc49..780e1cb 100644 --- a/docs/site.md +++ b/docs/site.md @@ -94,3 +94,20 @@ python3 scripts/replay_recorded_demo.py --run --input-dir ~/comfyui/inp ``` 預設連線為 `http://127.0.0.1:8188`;`--comfy-url` 只接受數字形式的 HTTP loopback 位址,不接受帳密、外部位址或重新導向。核准素材會複製至指定目錄中的 `web-demo-replay/`,遇到同名但不同內容的檔案會停止。腳本只回報提交取得的 `prompt_id`,完成與否請在 ComfyUI 查看;它不宣稱佇列提交就是生成成功。重跑前會確認輸入雜湊與原始執行一致;成果可能轉成公開用格式,與 ComfyUI 原始輸出分別記錄雜湊。即使使用同一份輸入,重跑結果也不保證逐像素相同。模型與節點版本、執行硬體也可能影響結果。 + +## Demo compute screens / 示範運算畫面 + +`/demo/` also displays the per-form execution chooser, all five compute lanes and their available-feature conditions, multi-step production, Google Colab accounts, and the resource provider console. These are read-only screens with canned empty-state responses: nothing connects, credential inputs are disabled, and settings are never saved. Action buttons explain that the operation requires your own installed WebUI. This is interface coverage, not a verified compute or GPU run. + +`/demo/` 也展示表單的執行位置、五個運算平台與可用條件、多步製作、Google Colab 帳號及資源平台管理畫面。畫面使用固定的空白狀態資料,不連線、不接受金鑰,也不保存設定;操作按鈕會提示改用自行安裝的 WebUI。這是介面展示,不代表已驗證運算或 GPU 生成。 + +Regenerate with the WebUI Python dependencies installed / 安裝 WebUI Python 相依套件後重新產生: + +```bash +python3 scripts/record_demo_compute.py +python3 scripts/build_docs.py +``` + +The recorder starts the public server on `127.0.0.1` in a fresh temporary state under a temporary home directory, ignores `.env` and inherited provider configuration, completes local password setup and login, and blocks outgoing server connections. It replaces only the server's built-in local identity with `demo@example.invalid` (display name `Demo`), normalizes volatile timestamps/IDs, and rejects other e-mails, filesystem paths and credential-shaped values before writing `webui/docs/demo-compute.json`. Review that file before committing it. The build embeds it in `app-guide.json`; opening compute screens adds no native API requests. + +錄製器只啟動全新暫存狀態與暫存家目錄的本機服務,不讀取 `.env` 或繼承平台設定,完成本機密碼設定與登入後擷取回應,並阻止服務對外連線。僅將內建本機身份替換為 `demo@example.invalid`(名稱 `Demo`),固定時間與產生的識別碼;其他信箱、檔案絕對路徑或憑證樣式內容都會使錄製失敗。提交前請審查 `webui/docs/demo-compute.json`。建置時資料嵌入 `app-guide.json`,開啟運算畫面不會增加原生 API 請求。 diff --git a/webui/docs/demo-compute.json b/webui/docs/demo-compute.json new file mode 100644 index 0000000..0c33e74 --- /dev/null +++ b/webui/docs/demo-compute.json @@ -0,0 +1,3616 @@ +{ + "/api/assets?kind=image": { + "body": { + "assets": [], + "credits_spent": 0, + "filters": { + "catalogRole": null, + "characterId": null, + "kind": "image", + "origin": null, + "visualClass": null + }, + "next_cursor": null, + "provider_transport_performed": false, + "schema_version": 1 + }, + "status": 200 + }, + "/api/colab": { + "body": { + "accounts": [], + "installed": false, + "jobs": [], + "ok": true, + "session": { + "phase": "closed", + "status_label": "未開啟" + }, + "session_ledger": [], + "settings": { + "hard_hours": 6, + "idle_minutes": 20, + "max_units": 120 + } + }, + "status": 200 + }, + "/api/colab/session": { + "body": { + "ok": true, + "session": { + "phase": "closed", + "status_label": "未開啟" + }, + "session_ledger": [], + "settings": { + "hard_hours": 6, + "idle_minutes": 20, + "max_units": 120 + } + }, + "status": 200 + }, + "/api/compute/capabilities": { + "body": { + "features": [ + { + "id": "text2img", + "providers": { + "autoip": { + "reason": "已提供服務轉接;需帳號、報價與相容參數,角色綁定另行檢查", + "status": "implemented" + }, + "colab": { + "reason": "已提供 PRISM / P-H3 轉接;仍需可用帳號與相容參數", + "status": "implemented" + }, + "comfy_cloud": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + } + }, + "title": "文生圖" + }, + { + "id": "img2img", + "providers": { + "autoip": { + "reason": "已提供服務轉接;需帳號、報價與相容參數,角色綁定另行檢查", + "status": "implemented" + }, + "colab": { + "reason": "已提供 PRISM / P-H3 轉接;仍需可用帳號與相容參數", + "status": "implemented" + }, + "comfy_cloud": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + } + }, + "title": "AI 指令改圖" + }, + { + "id": "anime-scene-card", + "providers": { + "autoip": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "colab": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "需要伺服器綁定的透明角色與核准場景版位;尚未提供完整的版位/遮罩語意映射。", + "status": "unsupported" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "需要伺服器綁定的透明角色與核准場景版位;尚未提供完整的版位/遮罩語意映射。", + "status": "unsupported" + } + }, + "title": "動漫場景寫真" + }, + { + "id": "image-blend", + "providers": { + "autoip": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "colab": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "去背模型、遮罩與合成版位有專屬處理;尚未建立逐項保留其參數的託管配方。", + "status": "unsupported" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "去背模型、遮罩與合成版位有專屬處理;尚未建立逐項保留其參數的託管配方。", + "status": "unsupported" + } + }, + "title": "AI 參考圖融合" + }, + { + "id": "character-angles", + "providers": { + "autoip": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "colab": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "需要 InsightFace 模型目錄與多角度身分處理;不能只用一般 prompt 映射替代。", + "status": "unsupported" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "需要 InsightFace 模型目錄與多角度身分處理;不能只用一般 prompt 映射替代。", + "status": "unsupported" + } + }, + "title": "真人臉參考肖像" + }, + { + "id": "clipmode-character-photoshoot", + "providers": { + "autoip": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "colab": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "需要私有角色 LoRA/InstantID 身分檔案、觸發詞與生成後身分檢查;不能僅搬移圖或上傳任意臉圖。", + "status": "unsupported" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "需要私有角色 LoRA/InstantID 身分檔案、觸發詞與生成後身分檢查;不能僅搬移圖或上傳任意臉圖。", + "status": "unsupported" + } + }, + "title": "角色身份寫真" + }, + { + "id": "img2video", + "providers": { + "autoip": { + "reason": "已提供服務轉接;需帳號、報價與相容參數,角色綁定另行檢查", + "status": "implemented" + }, + "colab": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + } + }, + "title": "AI 圖生影片" + }, + { + "id": "first-last-frame", + "providers": { + "autoip": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "colab": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "local": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "runninghub": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + } + }, + "title": "首尾幀影片" + }, + { + "id": "dance", + "providers": { + "autoip": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "colab": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + } + }, + "title": "AI 跳舞影片" + }, + { + "id": "lipsync", + "providers": { + "autoip": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "colab": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + } + }, + "title": "真人對嘴工具" + }, + { + "id": "face-swap", + "providers": { + "autoip": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "colab": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "local": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "runninghub": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + } + }, + "title": "AI 換人" + }, + { + "id": "video-loop", + "providers": { + "autoip": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "colab": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + } + }, + "title": "影片循環接龍" + }, + { + "id": "voice-speak", + "providers": { + "autoip": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "colab": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "聲音庫與角色人格授權、語音生成後處理仍由原本的服務流程管理;沒有已審查的遠端節點契約。", + "status": "unsupported" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "聲音庫與角色人格授權、語音生成後處理仍由原本的服務流程管理;沒有已審查的遠端節點契約。", + "status": "unsupported" + } + }, + "title": "聲音生成" + }, + { + "id": "voice-batch", + "providers": { + "autoip": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "colab": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "local": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "runninghub": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + } + }, + "title": "簡報配音" + }, + { + "id": "voice-clone", + "providers": { + "autoip": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "colab": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "聲音擁有權與模型載入流程尚未建立託管契約,不能自動傳送聲音資料。", + "status": "unsupported" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "聲音擁有權與模型載入流程尚未建立託管契約,不能自動傳送聲音資料。", + "status": "unsupported" + } + }, + "title": "聲音克隆" + }, + { + "id": "voxcpm-tts", + "providers": { + "autoip": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "colab": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "依賴本機語音模型、角色聲音設定與服務程序;沒有可直接移植的純 Comfy API 圖。", + "status": "unsupported" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "依賴本機語音模型、角色聲音設定與服務程序;沒有可直接移植的純 Comfy API 圖。", + "status": "unsupported" + } + }, + "title": "整合語音生成" + }, + { + "id": "voice-library", + "providers": { + "autoip": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "colab": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "local": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "runninghub": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + } + }, + "title": "聲音庫" + }, + { + "id": "post-generator", + "providers": { + "autoip": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "colab": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "comfy_cloud": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "local": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + }, + "runninghub": { + "reason": "此功能尚未開放生成", + "status": "unsupported" + } + }, + "title": "貼文生成器" + }, + { + "id": "h3-text-video", + "providers": { + "autoip": { + "reason": "已提供服務轉接;需帳號、報價與相容參數,角色綁定另行檢查", + "status": "implemented" + }, + "colab": { + "reason": "已提供 PRISM / P-H3 轉接;仍需可用帳號與相容參數", + "status": "implemented" + }, + "comfy_cloud": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + } + }, + "title": "文字生成有聲影片" + }, + { + "id": "h3-image-video", + "providers": { + "autoip": { + "reason": "已提供服務轉接;需帳號、報價與相容參數,角色綁定另行檢查", + "status": "implemented" + }, + "colab": { + "reason": "已提供 PRISM / P-H3 轉接;仍需可用帳號與相容參數", + "status": "implemented" + }, + "comfy_cloud": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + } + }, + "title": "首/尾格有聲影片" + }, + { + "id": "h3-reference-video", + "providers": { + "autoip": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "colab": { + "reason": "已提供 PRISM / P-H3 轉接;仍需可用帳號與相容參數", + "status": "implemented" + }, + "comfy_cloud": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + } + }, + "title": "多參考有聲影片" + }, + { + "id": "qwen21-text2img", + "providers": { + "autoip": { + "reason": "已提供服務轉接;需帳號、報價與相容參數,角色綁定另行檢查", + "status": "implemented" + }, + "colab": { + "reason": "已提供 PRISM / P-H3 轉接;仍需可用帳號與相容參數", + "status": "implemented" + }, + "comfy_cloud": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + } + }, + "title": "Qwen 2.1 文生圖" + }, + { + "id": "qwen21-edit", + "providers": { + "autoip": { + "reason": "已提供服務轉接;需帳號、報價與相容參數,角色綁定另行檢查", + "status": "implemented" + }, + "colab": { + "reason": "已提供 PRISM / P-H3 轉接;仍需可用帳號與相容參數", + "status": "implemented" + }, + "comfy_cloud": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + } + }, + "title": "AI 指令改圖" + }, + { + "id": "character-photoshoot", + "providers": { + "autoip": { + "reason": "尚未提供相容的執行契約", + "status": "unsupported" + }, + "colab": { + "reason": "已提供 PRISM / P-H3 轉接;仍需可用帳號與相容參數", + "status": "implemented" + }, + "comfy_cloud": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + }, + "local": { + "reason": "已接上既有執行流程;模型與節點會在送出前檢查", + "status": "implemented" + }, + "runninghub": { + "reason": "已有內建配方可選,尚需設定金鑰與遠端工作流", + "status": "unconfigured" + } + }, + "title": "角色搭配寫真" + } + ], + "ok": true, + "readiness_checked": false + }, + "status": 200 + }, + "/api/compute/connections": { + "body": { + "connections": [ + { + "account_type": null, + "balances": [], + "can_enable": true, + "checked_at": null, + "connection_state": "ready", + "credential_present": false, + "credential_saved_at": null, + "credential_version": 0, + "disabled_code": null, + "disabled_reason": "", + "legacy_modified_at": null, + "provider": "local", + "readiness": "ready", + "revision": 0, + "safe_reason": "", + "status_message": "本機使用權已開放", + "test_available": true, + "test_disabled_reason": "", + "use_enabled": true + }, + { + "account_type": null, + "balances": [], + "can_enable": false, + "checked_at": null, + "connection_state": "not_configured", + "credential_present": false, + "credential_saved_at": null, + "credential_version": 0, + "disabled_code": "login_required", + "disabled_reason": "請先使用 Google 登入", + "legacy_modified_at": null, + "provider": "colab", + "readiness": "unavailable", + "revision": 0, + "safe_reason": "", + "status_message": "尚未登入", + "test_available": false, + "test_disabled_reason": "請先使用 Google 登入", + "use_enabled": false + }, + { + "account_type": null, + "balances": [], + "can_enable": false, + "checked_at": null, + "connection_state": "not_configured", + "credential_present": false, + "credential_saved_at": null, + "credential_version": 0, + "disabled_code": "credential_required", + "disabled_reason": "請先儲存金鑰", + "legacy_modified_at": null, + "provider": "autoip", + "readiness": "unavailable", + "revision": 0, + "safe_reason": "", + "status_message": "未設定", + "test_available": false, + "test_disabled_reason": "請先儲存金鑰", + "use_enabled": false + }, + { + "account_type": null, + "balances": [], + "can_enable": false, + "checked_at": null, + "connection_state": "not_configured", + "credential_present": false, + "credential_saved_at": null, + "credential_version": 0, + "disabled_code": "credential_required", + "disabled_reason": "請先儲存金鑰", + "legacy_modified_at": null, + "provider": "comfy_cloud", + "readiness": "unavailable", + "revision": 0, + "safe_reason": "", + "status_message": "未設定", + "test_available": false, + "test_disabled_reason": "連線檢查尚未開放", + "use_enabled": false, + "verification_note": "" + }, + { + "account_type": null, + "balances": [], + "can_enable": false, + "checked_at": null, + "connection_state": "not_configured", + "credential_present": false, + "credential_saved_at": null, + "credential_version": 0, + "disabled_code": "credential_required", + "disabled_reason": "請先儲存金鑰", + "key_type_label": "尚未確認金鑰類型", + "legacy_modified_at": null, + "provider": "runninghub", + "readiness": "unavailable", + "revision": 0, + "safe_reason": "", + "status_message": "未設定", + "test_available": false, + "test_disabled_reason": "請先儲存金鑰", + "use_enabled": false, + "verification_note": "" + } + ], + "ok": true, + "owner": "demo@example.invalid", + "preferences": { + "auto_order": [ + "local" + ], + "auto_policy": "user_order", + "default_placement": "local", + "feature_placements": {}, + "revision": 0 + } + }, + "status": 200 + }, + "/api/compute/jobs": { + "body": { + "jobs": [], + "next_cursor": null, + "ok": true + }, + "status": 200 + }, + "/api/compute/parity/cases": { + "body": { + "cases": [] + }, + "status": 200 + }, + "/api/compute/pipeline-features": { + "body": { + "features": [ + { + "characterOnly": false, + "description": "Z-Image Turbo", + "fields": [ + { + "default": "", + "hint": "提示詞建議使用英文,畫面模型對英文較敏感。", + "id": "positive", + "label": "想生成什麼?", + "placeholder": "例如:午後窗邊的一杯咖啡,溫暖自然光,生活攝影", + "rows": 4, + "type": "textarea" + }, + { + "default": "文字、水印、logo、过度磨皮、塑料皮肤、畸形手指、多余手指、断指、严重解剖错误、脸部崩坏", + "id": "negative", + "label": "負向提示詞", + "rows": 2, + "type": "textarea" + }, + { + "default": "1088x1920", + "id": "aspect", + "label": "畫面比例", + "options": [ + { + "height": 1920, + "label": "直 9:16", + "width": 1088 + }, + { + "height": 1536, + "label": "直 3:4", + "width": 1152 + }, + { + "height": 1408, + "label": "方 1:1", + "width": 1408 + }, + { + "height": 1152, + "label": "橫 4:3", + "width": 1536 + }, + { + "height": 1088, + "label": "橫 16:9", + "width": 1920 + }, + { + "height": 1024, + "label": "方 1K · 1024×1024", + "width": 1024 + }, + { + "height": 768, + "label": "橫 1K · 1024×768", + "width": 1024 + }, + { + "height": 1024, + "label": "直 1K · 768×1024", + "width": 768 + } + ], + "type": "aspect" + }, + { + "default": 8, + "id": "steps", + "label": "步數", + "max": 40, + "min": 1, + "step": 1, + "type": "slider" + }, + { + "default": 1.0, + "id": "cfg", + "label": "CFG", + "max": 10, + "min": 0, + "step": 0.1, + "type": "slider" + }, + { + "default": 1, + "id": "batchSize", + "label": "張數", + "max": 8, + "min": 1, + "step": 1, + "type": "number" + }, + { + "default": false, + "id": "useDopsd", + "label": "DOPSD 白幕風格", + "type": "checkbox" + }, + { + "default": -1, + "id": "seed", + "label": "種子(-1 隨機)", + "max": 2147483647, + "min": -1, + "step": 1, + "type": "number" + } + ], + "id": "text2img", + "label": "文生圖", + "operatorOnly": false, + "output_kind": "image", + "studio": "image", + "uploads": [] + }, + { + "characterOnly": false, + "description": "Flux Kontext 重新生成式編輯", + "fields": [ + { + "default": "", + "hint": "提示詞建議使用英文,畫面模型對英文較敏感。", + "id": "instruction", + "label": "修改指令(英文最佳)", + "placeholder": "Replace the background with a tropical beach at sunset", + "required": true, + "rows": 4, + "type": "textarea" + }, + { + "default": 20, + "id": "steps", + "label": "步數", + "max": 50, + "min": 1, + "step": 1, + "type": "slider" + }, + { + "default": 2.5, + "id": "guidance", + "label": "Guidance", + "max": 10, + "min": 0, + "step": 0.1, + "type": "slider" + }, + { + "default": 1.0, + "id": "denoise", + "label": "Denoise", + "max": 1, + "min": 0, + "step": 0.05, + "type": "slider" + }, + { + "default": -1, + "id": "seed", + "label": "種子(-1 隨機)", + "max": 2147483647, + "min": -1, + "step": 1, + "type": "number" + } + ], + "id": "img2img", + "label": "AI 指令改圖", + "operatorOnly": false, + "output_kind": "image", + "studio": "image", + "uploads": [ + { + "accept": "image/*", + "id": "image", + "label": "參考圖片", + "media_kinds": [ + "image" + ], + "required": true + } + ] + }, + { + "characterOnly": true, + "description": "角色原圖合成 · 不會轉成真人", + "fields": [], + "id": "anime-scene-card", + "label": "動漫場景寫真", + "operatorOnly": false, + "output_kind": "image", + "studio": "image", + "uploads": [ + { + "accept": "image/*", + "id": "image", + "label": "核准角色造型", + "media_kinds": [ + "image" + ], + "required": true + }, + { + "accept": "image/*", + "id": "scene", + "label": "核准動漫場景", + "media_kinds": [ + "image" + ], + "required": true + } + ] + }, + { + "characterOnly": false, + "description": "保留人物原貌 · AI 去背合成", + "fields": [ + { + "default": "person", + "id": "positive", + "label": "保留的主體", + "type": "text" + }, + { + "default": 0.5, + "id": "threshold", + "label": "主體偵測門檻", + "max": 1, + "min": 0, + "step": 0.01, + "type": "slider" + }, + { + "default": 0, + "id": "feather", + "label": "邊緣羽化(像素,0 為關閉)", + "max": 16, + "min": 0, + "step": 1, + "type": "slider" + } + ], + "id": "image-blend", + "label": "AI 參考圖融合", + "operatorOnly": false, + "output_kind": "image", + "studio": "image", + "uploads": [ + { + "accept": "image/*", + "id": "image1", + "label": "人物原圖", + "media_kinds": [ + "image" + ], + "required": true + }, + { + "accept": "image/*", + "id": "image2", + "label": "背景參考圖", + "media_kinds": [ + "image" + ], + "required": true + } + ] + }, + { + "characterOnly": false, + "description": "Qwen 2.1 · 保留原圖身份與色彩的多角度肖像", + "fields": [ + { + "default": "自然棚拍半身肖像,輕微轉頭,保留原本的髮型、眼鏡與服裝。", + "hint": "提示詞建議使用英文,畫面模型對英文較敏感。", + "id": "positive", + "label": "場景/角度描述", + "rows": 3, + "type": "textarea" + }, + { + "default": "black and white, monochrome, grayscale, different person, deformed face, watermark, text", + "id": "negative", + "label": "負向提示詞", + "rows": 2, + "type": "textarea" + }, + { + "default": 25, + "id": "steps", + "label": "步數", + "max": 50, + "min": 1, + "step": 1, + "type": "slider" + }, + { + "default": 1.0, + "id": "cfg", + "label": "CFG", + "max": 5, + "min": 1, + "step": 0.1, + "type": "slider" + }, + { + "default": 2, + "id": "batchSize", + "label": "候選張數", + "max": 6, + "min": 1, + "step": 1, + "type": "number" + }, + { + "default": -1, + "id": "seed", + "label": "種子(-1 隨機)", + "max": 2147483647, + "min": -1, + "step": 1, + "type": "number" + } + ], + "id": "character-angles", + "label": "真人臉參考肖像", + "operatorOnly": false, + "output_kind": "image", + "studio": "image", + "uploads": [ + { + "accept": "image/*", + "id": "face", + "label": "角色臉部參考", + "media_kinds": [ + "image" + ], + "required": true + } + ] + }, + { + "characterOnly": true, + "description": "角色卡原圖雙重身份鎖定 · SDXL Beta", + "fields": [ + { + "default": "professional portrait, natural expression, soft studio lighting, highly detailed", + "hint": "提示詞建議使用英文,畫面模型對英文較敏感。", + "id": "prompt", + "label": "想拍什麼場景?", + "required": true, + "rows": 4, + "type": "textarea" + }, + { + "default": "lowres, blurry, bad anatomy, deformed hands, extra fingers, watermark, text", + "id": "negative_prompt", + "label": "負向提示詞", + "rows": 2, + "type": "textarea" + }, + { + "default": "768x1024", + "id": "aspect_ratio", + "label": "畫面比例", + "options": [ + { + "label": "直 3:4", + "value": "768x1024" + }, + { + "label": "方 1:1", + "value": "1024x1024" + }, + { + "label": "橫 4:3", + "value": "1024x768" + } + ], + "type": "select" + }, + { + "default": -1, + "id": "seed", + "label": "種子(-1 隨機)", + "max": 2147483647, + "min": -1, + "step": 1, + "type": "number" + } + ], + "id": "clipmode-character-photoshoot", + "label": "角色身份寫真", + "operatorOnly": false, + "output_kind": "image", + "studio": "image", + "uploads": [ + { + "accept": "image/*", + "id": "image", + "label": "角色原圖", + "media_kinds": [ + "image" + ], + "required": false + } + ] + }, + { + "characterOnly": false, + "description": "Wan 2.1 Image-to-Video", + "fields": [ + { + "default": "", + "hint": "提示詞建議使用英文,影片模型對英文較敏感。", + "id": "positive", + "label": "動態描述", + "placeholder": "the woman slowly turns her head and smiles, gentle camera push-in", + "rows": 3, + "type": "textarea" + }, + { + "default": "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,杂乱的背景,三条腿,背景人很多,倒着走", + "id": "negative", + "label": "負向提示詞", + "rows": 2, + "type": "textarea" + }, + { + "default": "480x832", + "id": "aspect", + "label": "畫面比例", + "options": [ + { + "height": 832, + "label": "直 480×832", + "width": 480 + }, + { + "height": 512, + "label": "方 512×512", + "width": 512 + }, + { + "height": 480, + "label": "橫 832×480", + "width": 832 + } + ], + "type": "aspect" + }, + { + "default": 81, + "id": "length", + "label": "影格數", + "max": 161, + "min": 9, + "step": 4, + "type": "slider" + }, + { + "default": 16, + "id": "fps", + "label": "FPS", + "max": 60, + "min": 1, + "step": 1, + "type": "number" + }, + { + "default": 6, + "id": "steps", + "label": "步數", + "max": 30, + "min": 1, + "step": 1, + "type": "slider" + }, + { + "default": 8.0, + "id": "shift", + "label": "Shift", + "max": 20, + "min": 0, + "step": 0.5, + "type": "slider" + }, + { + "default": -1, + "id": "seed", + "label": "種子(-1 隨機)", + "max": 2147483647, + "min": -1, + "step": 1, + "type": "number" + } + ], + "id": "img2video", + "label": "AI 圖生影片", + "operatorOnly": false, + "output_kind": "video", + "studio": "video", + "uploads": [ + { + "accept": "image/*", + "id": "image", + "label": "起始圖片", + "media_kinds": [ + "image" + ], + "required": true + } + ] + }, + { + "characterOnly": false, + "description": "SCAIL 姿態驅動", + "fields": [ + { + "default": "animate", + "id": "mode", + "label": "模式", + "options": [ + { + "label": "動畫模式(AI 生成背景,比例跟參考圖)", + "value": "animate" + } + ], + "type": "select" + }, + { + "default": "", + "hint": "提示詞建議使用英文,影片模型對英文較敏感。", + "id": "positive", + "label": "角色描述", + "placeholder": "a person dancing, full body, natural motion", + "rows": 3, + "type": "textarea" + }, + { + "default": "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,杂乱的背景,三条腿,背景人很多,倒着走", + "id": "negative", + "label": "負向提示詞", + "rows": 2, + "type": "textarea" + }, + { + "default": 1.0, + "id": "poseStrength", + "label": "姿態強度", + "max": 2, + "min": 0, + "step": 0.05, + "type": "slider" + }, + { + "default": 133, + "id": "length", + "label": "影格數", + "max": 161, + "min": 81, + "step": 4, + "type": "slider" + }, + { + "default": 16, + "id": "fps", + "label": "FPS", + "max": 60, + "min": 1, + "step": 1, + "type": "number" + }, + { + "default": 6, + "id": "steps", + "label": "步數", + "max": 30, + "min": 1, + "step": 1, + "type": "slider" + }, + { + "default": -1, + "id": "seed", + "label": "種子(-1 隨機)", + "max": 2147483647, + "min": -1, + "step": 1, + "type": "number" + } + ], + "id": "dance", + "label": "AI 跳舞影片", + "operatorOnly": false, + "output_kind": "video", + "studio": "video", + "uploads": [ + { + "accept": "image/*", + "id": "reference", + "label": "角色參考圖", + "media_kinds": [ + "image" + ], + "required": true + }, + { + "accept": "video/*", + "id": "video", + "label": "動作驅動影片", + "media_kinds": [ + "video" + ], + "required": true + } + ] + }, + { + "characterOnly": false, + "description": "非角色綁定 · Wav2Lip 真人臉口型同步", + "fields": [ + { + "id": "voiceId", + "label": "聲音庫語音", + "type": "voiceSelect" + }, + { + "default": "sequential", + "display": "cards", + "id": "mode", + "label": "影格對應", + "options": [ + { + "label": "順序對應", + "sub": "影片隨語音長度伸縮", + "value": "sequential" + }, + { + "label": "循環播放", + "sub": "影片重複到語音結束", + "value": "repetitive" + } + ], + "type": "select" + }, + { + "default": 300, + "id": "maxFrames", + "label": "最多讀取影格數", + "max": 1200, + "min": 1, + "step": 1, + "type": "number" + }, + { + "default": 8, + "id": "faceBatch", + "label": "臉部偵測批次", + "max": 100, + "min": 1, + "step": 1, + "type": "number" + } + ], + "id": "lipsync", + "label": "真人對嘴工具", + "operatorOnly": false, + "output_kind": "video", + "studio": "video", + "uploads": [ + { + "accept": "video/*", + "id": "video", + "label": "人物影片", + "media_kinds": [ + "video" + ], + "required": true + }, + { + "accept": "audio/*", + "id": "voice", + "label": "上傳語音(未選聲音庫時使用)", + "media_kinds": [ + "audio" + ], + "required": false + } + ] + }, + { + "characterOnly": false, + "description": "重複或正反播放短片(輸出不含原音訊)", + "fields": [ + { + "default": 4, + "id": "repeat", + "label": "重複次數", + "max": 30, + "min": 1, + "step": 1, + "type": "slider" + }, + { + "default": false, + "id": "pingpong", + "label": "正反來回(正放後倒放,減少接點跳動)", + "type": "checkbox" + }, + { + "default": 600, + "id": "maxFrames", + "label": "最多讀取影格數", + "max": 1800, + "min": 1, + "step": 1, + "type": "number" + } + ], + "id": "video-loop", + "label": "影片循環接龍", + "operatorOnly": false, + "output_kind": "video", + "studio": "video", + "uploads": [ + { + "accept": "video/*", + "id": "video", + "label": "短影片", + "media_kinds": [ + "video" + ], + "required": true + } + ] + }, + { + "characterOnly": false, + "description": "依目前入口提供角色聲音或聲音庫克隆", + "fields": [ + { + "default": "persona", + "display": "cards", + "id": "voiceSource", + "label": "聲音路徑", + "options": [ + { + "label": "角色聲音", + "sub": "已訓練的角色聲音(台灣國語),選人即說", + "value": "persona" + }, + { + "label": "聲音庫克隆", + "sub": "用 聲音庫 的參考音克隆音色,逐字稿自動帶入", + "value": "library" + } + ], + "type": "select" + }, + { + "id": "persona", + "label": "角色聲音", + "type": "personaSelect" + }, + { + "id": "voiceId", + "label": "聲音庫參考音訊", + "type": "voiceSelect" + }, + { + "id": "sampleText", + "label": "參考音訊逐字稿(最多 180 字)", + "maxLength": 180, + "placeholder": "參考音訊實際說的那段話;聲音庫有 metadata 時會自動帶入", + "required": true, + "rows": 2, + "type": "textarea" + }, + { + "default": "taiwan", + "display": "cards", + "id": "cloneEngine", + "label": "聲音庫引擎", + "options": [ + { + "label": "台灣腔", + "sub": "BreezyVoice reference clone", + "value": "taiwan" + }, + { + "label": "多語 F5", + "sub": "要說英日等外語選這個", + "value": "f5" + } + ], + "type": "select" + }, + { + "id": "text", + "label": "要說的話(最多 2400 字,自動分段合併)", + "maxLength": 2400, + "placeholder": "打字,讓她用這個聲音說出來;長文會自動切段後合併", + "rows": 4, + "type": "textarea" + }, + { + "default": false, + "id": "qualityGate", + "label": "高品質 ASR Gate(較慢,會等 GPU,逐段檢查失敗重跑)", + "type": "checkbox" + } + ], + "id": "voice-speak", + "label": "聲音生成", + "operatorOnly": false, + "output_kind": "audio", + "studio": "voice", + "uploads": [] + }, + { + "characterOnly": false, + "description": "舊入口:請改用「聲音生成」的聲音庫 Clone", + "fields": [ + { + "default": "f5", + "display": "cards", + "id": "engine", + "label": "語音版本", + "options": [ + { + "label": "國語通用", + "sub": "F5-TTS・多語音色克隆", + "value": "f5" + }, + { + "label": "國語台灣口音", + "sub": "BreezyVoice・道地台灣腔", + "value": "taiwan" + } + ], + "type": "select" + }, + { + "id": "voiceId", + "label": "聲音庫參考音訊", + "type": "voiceSelect" + }, + { + "id": "sampleText", + "label": "參考音訊逐字稿(最多 180 字)", + "maxLength": 180, + "placeholder": "參考音訊實際說的那段話", + "required": true, + "rows": 2, + "type": "textarea" + }, + { + "id": "speech", + "label": "要生成的文字(最多 2400 字,自動分段合併)", + "maxLength": 2400, + "placeholder": "想用這個音色說的內容;長文會自動切段後合併", + "rows": 4, + "type": "textarea" + }, + { + "default": "F5v1", + "id": "model", + "label": "模型", + "options": [ + { + "label": "F5v1(多語 / 中英)", + "value": "F5v1" + }, + { + "label": "F5 Base(英文)", + "value": "F5" + }, + { + "label": "日文", + "value": "F5-JP" + }, + { + "label": "西班牙文", + "value": "F5-ES" + }, + { + "label": "法文", + "value": "F5-FR" + }, + { + "label": "德文", + "value": "F5-DE" + }, + { + "label": "義大利文", + "value": "F5-IT" + }, + { + "label": "印地文", + "value": "F5-HI" + }, + { + "label": "泰文", + "value": "F5-TH" + }, + { + "label": "E2-TTS(英文)", + "value": "E2" + } + ], + "type": "select" + }, + { + "default": 1, + "id": "seed", + "label": "種子(-1 隨機)", + "min": -1, + "step": 1, + "type": "number" + } + ], + "id": "voice-clone", + "label": "聲音克隆", + "operatorOnly": false, + "output_kind": null, + "studio": "voice", + "uploads": [ + { + "accept": "audio/*", + "id": "voice", + "label": "上傳參考音訊(未選聲音庫時使用)", + "media_kinds": [ + "audio" + ], + "required": false + } + ] + }, + { + "characterOnly": false, + "description": "BreezyVoice 台灣國語 · VoxCPM Custom English / 多語", + "fields": [ + { + "default": "breezy", + "display": "cards", + "id": "voiceEngine", + "label": "語音引擎", + "options": [ + { + "label": "台灣國語", + "sub": "BreezyVoice · operator / AI-Sister 本機聲音", + "value": "breezy" + }, + { + "label": "Custom English / 多語", + "sub": "VoxCPM2 · 口音 / LoRA / reference clone", + "value": "voxcpm" + } + ], + "type": "select" + }, + { + "id": "persona", + "label": "BreezyVoice 聲音", + "type": "personaSelect" + }, + { + "default": false, + "id": "qualityGate", + "label": "高品質 ASR Gate(較慢,會等 GPU,逐段檢查失敗重跑)", + "type": "checkbox" + }, + { + "default": "lora", + "display": "cards", + "id": "mode", + "label": "VoxCPM 模式", + "options": [ + { + "label": "Custom English Clone", + "sub": "LoRA + 乾淨 reference,不讓模型自由猜聲音", + "value": "lora" + }, + { + "label": "Voice Design", + "sub": "不用參考音,靠描述生成聲音", + "value": "design" + }, + { + "label": "Reference Clone", + "sub": "只用參考音(免逐字稿)", + "value": "reference" + }, + { + "label": "Ultimate Clone", + "sub": "真人參考音 + 逐字稿(最像本人)", + "value": "ultimate" + } + ], + "type": "select" + }, + { + "default": "English", + "id": "language", + "label": "語言", + "options": [ + { + "label": "自動(依文字內容)", + "value": "" + }, + { + "label": "English", + "value": "English" + }, + { + "label": "中文 / Mandarin", + "value": "Chinese Mandarin" + }, + { + "label": "日本語", + "value": "Japanese" + }, + { + "label": "한국어", + "value": "Korean" + }, + { + "label": "Français", + "value": "French" + }, + { + "label": "Deutsch", + "value": "German" + }, + { + "label": "Español", + "value": "Spanish" + }, + { + "label": "Português", + "value": "Portuguese" + }, + { + "label": "Italiano", + "value": "Italian" + }, + { + "label": "Nederlands", + "value": "Dutch" + }, + { + "label": "Dansk", + "value": "Danish" + }, + { + "label": "Suomi", + "value": "Finnish" + }, + { + "label": "Ελληνικά", + "value": "Greek" + }, + { + "label": "עברית", + "value": "Hebrew" + }, + { + "label": "हिन्दी", + "value": "Hindi" + }, + { + "label": "Bahasa Indonesia", + "value": "Indonesian" + }, + { + "label": "Bahasa Melayu", + "value": "Malay" + }, + { + "label": "Norsk", + "value": "Norwegian" + }, + { + "label": "Polski", + "value": "Polish" + }, + { + "label": "Русский", + "value": "Russian" + }, + { + "label": "Kiswahili", + "value": "Swahili" + }, + { + "label": "Svenska", + "value": "Swedish" + }, + { + "label": "Tagalog", + "value": "Tagalog" + }, + { + "label": "ไทย", + "value": "Thai" + }, + { + "label": "Türkçe", + "value": "Turkish" + }, + { + "label": "Tiếng Việt", + "value": "Vietnamese" + }, + { + "label": "العربية", + "value": "Arabic" + }, + { + "label": "မြန်မာ", + "value": "Burmese" + }, + { + "label": "ភាសាខ្មែរ", + "value": "Khmer" + }, + { + "label": "ລາວ", + "value": "Lao" + } + ], + "type": "select" + }, + { + "default": "standard American English accent", + "id": "accent", + "label": "口音 / 方言", + "options": [ + { + "label": "自動 / 保持文字自然口音", + "value": "" + }, + { + "label": "美式標準英文", + "value": "standard American English accent" + }, + { + "label": "國際清晰英文", + "value": "clear standard English with a neutral international accent" + }, + { + "label": "英式英文", + "value": "British English accent" + }, + { + "label": "澳洲英文", + "value": "Australian English accent" + }, + { + "label": "印度英文", + "value": "Indian English accent" + }, + { + "label": "台灣國語", + "value": "Taiwanese Mandarin accent" + }, + { + "label": "普通話", + "value": "Mainland Mandarin accent" + }, + { + "label": "粵語 / Cantonese", + "value": "Cantonese accent" + }, + { + "label": "閩南語 / 台語風格", + "value": "Taiwanese Hokkien accent" + }, + { + "label": "四川話", + "value": "Sichuan dialect accent" + }, + { + "label": "吳語", + "value": "Wu dialect accent" + }, + { + "label": "東北話", + "value": "Northeastern Chinese accent" + }, + { + "label": "河南話", + "value": "Henan dialect accent" + }, + { + "label": "陝西話", + "value": "Shaanxi dialect accent" + }, + { + "label": "山東話", + "value": "Shandong dialect accent" + }, + { + "label": "天津話", + "value": "Tianjin dialect accent" + } + ], + "type": "select" + }, + { + "default": "custom_english", + "id": "voiceProfile", + "label": "LoRA Profile", + "options": [ + { + "label": "Custom English LoRA (configure locally)", + "value": "custom_english" + } + ], + "type": "select" + }, + { + "default": true, + "id": "speakerGate", + "label": "聲紋 Gate(有 reference 時低於相似度會自動重跑)", + "type": "checkbox" + }, + { + "id": "voiceId", + "label": "聲音庫參考音訊", + "type": "voiceSelect" + }, + { + "id": "style", + "label": "語氣 / 風格控制", + "placeholder": "例如:calm, confident, standard American English, natural meeting voice", + "rows": 2, + "type": "textarea" + }, + { + "id": "promptText", + "label": "參考音訊逐字稿(Ultimate Clone 才需要)", + "maxLength": 500, + "placeholder": "參考音訊實際講的英文逐字稿", + "rows": 2, + "type": "textarea" + }, + { + "id": "text", + "label": "要生成的文字", + "maxLength": 2400, + "placeholder": "輸入要用 VoxCPM 說出的文字", + "rows": 4, + "type": "textarea" + }, + { + "default": 2.0, + "id": "cfg", + "label": "CFG", + "max": 3.0, + "min": 1.0, + "step": 0.1, + "type": "slider" + }, + { + "default": 10, + "id": "steps", + "label": "推理步數", + "max": 30, + "min": 4, + "step": 1, + "type": "slider" + }, + { + "default": -1, + "id": "seed", + "label": "種子(-1 隨機)", + "min": -1, + "step": 1, + "type": "number" + } + ], + "id": "voxcpm-tts", + "label": "整合語音生成", + "operatorOnly": false, + "output_kind": "audio", + "studio": "voice", + "uploads": [ + { + "accept": "audio/*", + "id": "voice", + "label": "參考音訊(Reference / Ultimate 模式使用)", + "media_kinds": [ + "audio" + ], + "required": false + } + ] + }, + { + "characterOnly": false, + "description": "MiniMax H3 FL2VA · 三欄原生提示詞", + "fields": [ + { + "id": "integrated_multimodal_description", + "label": "integrated_multimodal_description", + "maxLength": 4000, + "placeholder": "依時間順序描述畫面、動作、鏡頭、對白與可見文字。", + "required": true, + "rows": 6, + "type": "textarea" + }, + { + "id": "overall_soundscape", + "label": "overall_soundscape", + "maxLength": 4000, + "placeholder": "環境音、物理聲響、對白以外的場景聲音;沒有可填 N/A。", + "required": true, + "rows": 3, + "type": "textarea" + }, + { + "id": "non_diegetic_music", + "label": "non_diegetic_music", + "maxLength": 4000, + "placeholder": "觀眾聽見、場景內角色聽不見的配樂;不要配樂可填 None.", + "required": true, + "rows": 3, + "type": "textarea" + }, + { + "default": "landscape", + "id": "aspect", + "label": "畫布", + "options": [ + { + "height": 1344, + "label": "原生直式 9:16", + "value": "portrait", + "width": 768 + }, + { + "height": 768, + "label": "原生橫式 16:9", + "value": "landscape", + "width": 1344 + }, + { + "height": 992, + "label": "原生方形 1:1", + "value": "square", + "width": 992 + }, + { + "height": 864, + "label": "預覽直式 9:16", + "value": "portrait-preview", + "width": 480 + }, + { + "height": 480, + "label": "預覽橫式 16:9", + "value": "landscape-preview", + "width": 864 + }, + { + "height": 640, + "label": "預覽方形 1:1", + "value": "square-preview", + "width": 640 + } + ], + "type": "select" + }, + { + "default": "124", + "id": "frames", + "label": "幀數(17k+5)", + "options": [ + { + "label": "124 幀 · 5.17 秒", + "value": "124" + }, + { + "label": "141 幀 · 5.88 秒", + "value": "141" + }, + { + "label": "158 幀 · 6.58 秒", + "value": "158" + }, + { + "label": "175 幀 · 7.29 秒", + "value": "175" + }, + { + "label": "192 幀 · 8.00 秒", + "value": "192" + }, + { + "label": "209 幀 · 8.71 秒", + "value": "209" + }, + { + "label": "226 幀 · 9.42 秒", + "value": "226" + }, + { + "label": "243 幀 · 10.12 秒", + "value": "243" + }, + { + "label": "260 幀 · 10.83 秒", + "value": "260" + }, + { + "label": "277 幀 · 11.54 秒", + "value": "277" + }, + { + "label": "294 幀 · 12.25 秒", + "value": "294" + }, + { + "label": "311 幀 · 12.96 秒", + "value": "311" + }, + { + "label": "328 幀 · 13.67 秒", + "value": "328" + }, + { + "label": "345 幀 · 14.38 秒", + "value": "345" + }, + { + "label": "362 幀 · 15.08 秒", + "value": "362" + } + ], + "type": "select" + }, + { + "default": "stock", + "id": "acceleration", + "label": "加速模式", + "options": [ + { + "label": "Stock · 官方 20 步", + "value": "stock" + }, + { + "label": "SageAttention · 20 步", + "value": "sage" + }, + { + "label": "Sage + EasyCache 0.1", + "value": "easycache" + }, + { + "label": "Sage + TeaCache 0.15", + "value": "teacache" + } + ], + "type": "select" + }, + { + "default": "-1", + "id": "seed", + "label": "種子(-1 隨機)", + "maxLength": 20, + "type": "integer-string" + } + ], + "id": "h3-text-video", + "label": "文字生成有聲影片", + "operatorOnly": false, + "output_kind": "video", + "studio": "video", + "uploads": [] + }, + { + "characterOnly": false, + "description": "MiniMax H3 FL2VA · I2V / FLF", + "fields": [ + { + "id": "integrated_multimodal_description", + "label": "integrated_multimodal_description", + "maxLength": 4000, + "required": true, + "rows": 6, + "type": "textarea" + }, + { + "id": "overall_soundscape", + "label": "overall_soundscape", + "maxLength": 4000, + "required": true, + "rows": 3, + "type": "textarea" + }, + { + "id": "non_diegetic_music", + "label": "non_diegetic_music", + "maxLength": 4000, + "required": true, + "rows": 3, + "type": "textarea" + }, + { + "default": "landscape", + "id": "aspect", + "label": "畫布", + "options": [ + { + "height": 1344, + "label": "原生直式 9:16", + "value": "portrait", + "width": 768 + }, + { + "height": 768, + "label": "原生橫式 16:9", + "value": "landscape", + "width": 1344 + }, + { + "height": 992, + "label": "原生方形 1:1", + "value": "square", + "width": 992 + }, + { + "height": 864, + "label": "預覽直式 9:16", + "value": "portrait-preview", + "width": 480 + }, + { + "height": 480, + "label": "預覽橫式 16:9", + "value": "landscape-preview", + "width": 864 + }, + { + "height": 640, + "label": "預覽方形 1:1", + "value": "square-preview", + "width": 640 + } + ], + "type": "select" + }, + { + "default": "124", + "id": "frames", + "label": "幀數(17k+5)", + "options": [ + { + "label": "124 幀 · 5.17 秒", + "value": "124" + }, + { + "label": "141 幀 · 5.88 秒", + "value": "141" + }, + { + "label": "158 幀 · 6.58 秒", + "value": "158" + }, + { + "label": "175 幀 · 7.29 秒", + "value": "175" + }, + { + "label": "192 幀 · 8.00 秒", + "value": "192" + }, + { + "label": "209 幀 · 8.71 秒", + "value": "209" + }, + { + "label": "226 幀 · 9.42 秒", + "value": "226" + }, + { + "label": "243 幀 · 10.12 秒", + "value": "243" + }, + { + "label": "260 幀 · 10.83 秒", + "value": "260" + }, + { + "label": "277 幀 · 11.54 秒", + "value": "277" + }, + { + "label": "294 幀 · 12.25 秒", + "value": "294" + }, + { + "label": "311 幀 · 12.96 秒", + "value": "311" + }, + { + "label": "328 幀 · 13.67 秒", + "value": "328" + }, + { + "label": "345 幀 · 14.38 秒", + "value": "345" + }, + { + "label": "362 幀 · 15.08 秒", + "value": "362" + } + ], + "type": "select" + }, + { + "default": "stock", + "id": "acceleration", + "label": "加速模式", + "options": [ + { + "label": "Stock · 官方 20 步", + "value": "stock" + }, + { + "label": "SageAttention · 20 步", + "value": "sage" + }, + { + "label": "Sage + EasyCache 0.1", + "value": "easycache" + }, + { + "label": "Sage + TeaCache 0.15", + "value": "teacache" + } + ], + "type": "select" + }, + { + "default": "-1", + "id": "seed", + "label": "種子(-1 隨機)", + "maxLength": 20, + "type": "integer-string" + } + ], + "id": "h3-image-video", + "label": "首/尾格有聲影片", + "minimumUploads": 1, + "operatorOnly": false, + "output_kind": "video", + "studio": "video", + "uploads": [ + { + "accept": "image/*", + "id": "image", + "label": "首格圖片", + "media_kinds": [ + "image" + ], + "required": false + }, + { + "accept": "image/*", + "id": "last_frame", + "label": "尾格圖片", + "media_kinds": [ + "image" + ], + "required": false + } + ] + }, + { + "characterOnly": false, + "description": "MiniMax H3 Ref2VA · 圖片/影片/音訊", + "fields": [ + { + "id": "subject_definitions", + "label": "subject_definitions", + "maxLength": 4000, + "required": true, + "rows": 5, + "type": "textarea" + }, + { + "id": "summary", + "label": "summary", + "maxLength": 4000, + "required": true, + "rows": 3, + "type": "textarea" + }, + { + "id": "retention_analysis", + "label": "retention_analysis", + "maxLength": 4000, + "required": true, + "rows": 4, + "type": "textarea" + }, + { + "id": "detailed_description", + "label": "detailed_description", + "maxLength": 4000, + "required": true, + "rows": 7, + "type": "textarea" + }, + { + "id": "overall_soundscape", + "label": "overall_soundscape", + "maxLength": 4000, + "required": true, + "rows": 3, + "type": "textarea" + }, + { + "id": "non_diegetic_music", + "label": "non_diegetic_music", + "maxLength": 4000, + "required": true, + "rows": 3, + "type": "textarea" + }, + { + "default": "landscape", + "id": "aspect", + "label": "畫布", + "options": [ + { + "height": 1344, + "label": "原生直式 9:16", + "value": "portrait", + "width": 768 + }, + { + "height": 768, + "label": "原生橫式 16:9", + "value": "landscape", + "width": 1344 + }, + { + "height": 992, + "label": "原生方形 1:1", + "value": "square", + "width": 992 + }, + { + "height": 864, + "label": "預覽直式 9:16", + "value": "portrait-preview", + "width": 480 + }, + { + "height": 480, + "label": "預覽橫式 16:9", + "value": "landscape-preview", + "width": 864 + }, + { + "height": 640, + "label": "預覽方形 1:1", + "value": "square-preview", + "width": 640 + } + ], + "type": "select" + }, + { + "default": "124", + "id": "frames", + "label": "幀數(17k+5)", + "options": [ + { + "label": "124 幀 · 5.17 秒", + "value": "124" + }, + { + "label": "141 幀 · 5.88 秒", + "value": "141" + }, + { + "label": "158 幀 · 6.58 秒", + "value": "158" + }, + { + "label": "175 幀 · 7.29 秒", + "value": "175" + }, + { + "label": "192 幀 · 8.00 秒", + "value": "192" + }, + { + "label": "209 幀 · 8.71 秒", + "value": "209" + }, + { + "label": "226 幀 · 9.42 秒", + "value": "226" + }, + { + "label": "243 幀 · 10.12 秒", + "value": "243" + }, + { + "label": "260 幀 · 10.83 秒", + "value": "260" + }, + { + "label": "277 幀 · 11.54 秒", + "value": "277" + }, + { + "label": "294 幀 · 12.25 秒", + "value": "294" + }, + { + "label": "311 幀 · 12.96 秒", + "value": "311" + }, + { + "label": "328 幀 · 13.67 秒", + "value": "328" + }, + { + "label": "345 幀 · 14.38 秒", + "value": "345" + }, + { + "label": "362 幀 · 15.08 秒", + "value": "362" + } + ], + "type": "select" + }, + { + "default": "stock", + "id": "acceleration", + "label": "加速模式", + "options": [ + { + "label": "Stock · 官方 20 步", + "value": "stock" + }, + { + "label": "SageAttention · 20 步", + "value": "sage" + }, + { + "label": "Sage + EasyCache 0.1", + "value": "easycache" + }, + { + "label": "Sage + TeaCache 0.15", + "value": "teacache" + } + ], + "type": "select" + }, + { + "default": "-1", + "id": "seed", + "label": "種子(-1 隨機)", + "maxLength": 20, + "type": "integer-string" + } + ], + "id": "h3-reference-video", + "label": "多參考有聲影片", + "minimumUploads": 1, + "operatorOnly": false, + "output_kind": "video", + "studio": "video", + "uploads": [ + { + "accept": "image/*", + "id": "reference", + "label": "參考圖片 1", + "media_kinds": [ + "image" + ], + "required": false + }, + { + "accept": "image/*", + "id": "reference2", + "label": "參考圖片 2", + "media_kinds": [ + "image" + ], + "required": false + }, + { + "accept": "image/*", + "id": "reference3", + "label": "參考圖片 3", + "media_kinds": [ + "image" + ], + "required": false + }, + { + "accept": "image/*", + "id": "reference4", + "label": "參考圖片 4", + "media_kinds": [ + "image" + ], + "required": false + }, + { + "accept": "image/*", + "id": "reference5", + "label": "參考圖片 5", + "media_kinds": [ + "image" + ], + "required": false + }, + { + "accept": "image/*", + "id": "reference6", + "label": "參考圖片 6", + "media_kinds": [ + "image" + ], + "required": false + }, + { + "accept": "image/*", + "id": "reference7", + "label": "參考圖片 7", + "media_kinds": [ + "image" + ], + "required": false + }, + { + "accept": "image/*", + "id": "reference8", + "label": "參考圖片 8", + "media_kinds": [ + "image" + ], + "required": false + }, + { + "accept": "image/*", + "id": "reference9", + "label": "參考圖片 9", + "media_kinds": [ + "image" + ], + "required": false + }, + { + "accept": "video/*", + "id": "video1", + "label": "參考影片 1", + "media_kinds": [ + "video" + ], + "required": false + }, + { + "accept": "video/*", + "id": "video2", + "label": "參考影片 2", + "media_kinds": [ + "video" + ], + "required": false + }, + { + "accept": "video/*", + "id": "video3", + "label": "參考影片 3", + "media_kinds": [ + "video" + ], + "required": false + }, + { + "accept": "audio/*", + "id": "audio1", + "label": "參考音訊 1", + "media_kinds": [ + "audio" + ], + "required": false + }, + { + "accept": "audio/*", + "id": "audio2", + "label": "參考音訊 2", + "media_kinds": [ + "audio" + ], + "required": false + }, + { + "accept": "audio/*", + "id": "audio3", + "label": "參考音訊 3", + "media_kinds": [ + "audio" + ], + "required": false + } + ] + }, + { + "characterOnly": false, + "description": "Qwen-Image-2.1 · 中文排版與原生 2K", + "fields": [ + { + "default": "", + "hint": "支援中文與英文;要呈現的文字請用引號標明。", + "id": "positive", + "label": "想生成什麼?", + "placeholder": "例如:一座雲海中的城堡,晨光照亮塔樓,海報標題為「雲上之城」。", + "required": true, + "rows": 4, + "type": "textarea" + }, + { + "default": "1:1", + "id": "aspectRatio", + "label": "畫面比例", + "options": [ + { + "label": "1:1", + "value": "1:1" + }, + { + "label": "16:9", + "value": "16:9" + }, + { + "label": "9:16", + "value": "9:16" + }, + { + "label": "3:2", + "value": "3:2" + }, + { + "label": "2:3", + "value": "2:3" + }, + { + "label": "4:3", + "value": "4:3" + }, + { + "label": "3:4", + "value": "3:4" + }, + { + "label": "21:9", + "value": "21:9" + } + ], + "type": "select" + }, + { + "default": "1", + "id": "megapixels", + "label": "輸出大小", + "options": [ + { + "label": "1 MP · 正方形 1024 × 1024", + "value": "1" + }, + { + "label": "2 MP · 更多細節", + "value": "2" + }, + { + "label": "4 MP · 正方形 2048 × 2048", + "value": "4" + } + ], + "type": "select" + }, + { + "default": "", + "id": "negative", + "label": "負向提示詞", + "rows": 2, + "type": "textarea" + }, + { + "default": 25, + "id": "steps", + "label": "步數", + "max": 50, + "min": 1, + "step": 1, + "type": "slider" + }, + { + "default": 1.0, + "id": "cfg", + "label": "CFG", + "max": 5, + "min": 1, + "step": 0.1, + "type": "slider" + }, + { + "default": -1, + "id": "seed", + "label": "種子(-1 隨機)", + "max": 9007199254740991, + "min": -1, + "step": 1, + "type": "number" + } + ], + "id": "qwen21-text2img", + "label": "Qwen 2.1 文生圖", + "operatorOnly": false, + "output_kind": "image", + "studio": "image", + "uploads": [] + }, + { + "characterOnly": false, + "description": "Qwen-Image-2.1 · 多圖參考", + "fields": [ + { + "default": "", + "hint": "支援中文與英文;要呈現的文字請用引號標明。", + "id": "instruction", + "label": "修改指令", + "placeholder": "保留 的構圖,把背景改成黃昏的海邊;可用 指定參考風格。", + "required": true, + "rows": 4, + "type": "textarea" + }, + { + "default": "1024", + "id": "resolution", + "label": "輸出大小", + "options": [ + { + "label": "約 1 MP · 依原圖比例", + "value": "1024" + }, + { + "label": "約 2.25 MP · 依原圖比例", + "value": "1536" + }, + { + "label": "約 4 MP · 依原圖比例", + "value": "2048" + } + ], + "type": "select" + }, + { + "default": "", + "id": "negative", + "label": "負向提示詞", + "rows": 2, + "type": "textarea" + }, + { + "default": 25, + "id": "steps", + "label": "步數", + "max": 50, + "min": 1, + "step": 1, + "type": "slider" + }, + { + "default": 1.0, + "id": "cfg", + "label": "CFG", + "max": 5, + "min": 1, + "step": 0.1, + "type": "slider" + }, + { + "default": -1, + "id": "seed", + "label": "種子(-1 隨機)", + "max": 9007199254740991, + "min": -1, + "step": 1, + "type": "number" + } + ], + "id": "qwen21-edit", + "label": "AI 指令改圖", + "operatorOnly": false, + "output_kind": "image", + "studio": "image", + "uploads": [ + { + "accept": "image/*", + "id": "image", + "label": "圖片 1 · (原圖)", + "media_kinds": [ + "image" + ], + "required": true + }, + { + "accept": "image/*", + "id": "image2", + "label": "圖片 2 · (可選參考)", + "media_kinds": [ + "image" + ], + "required": false + }, + { + "accept": "image/*", + "id": "image3", + "label": "圖片 3 · (可選參考)", + "media_kinds": [ + "image" + ], + "required": false + }, + { + "accept": "image/*", + "id": "image4", + "label": "圖片 4 · (可選參考)", + "media_kinds": [ + "image" + ], + "required": false + } + ] + }, + { + "characterOnly": false, + "description": "角色原圖 × 場景、穿著與姿勢", + "fields": [ + { + "default": "realistic", + "hint": "服裝依畫風分開;人物、衣服與背景使用同一畫風。選角色時依角色分類套用。", + "id": "visualStyle", + "label": "畫風", + "options": [ + { + "label": "動畫", + "value": "anime" + }, + { + "label": "寫實", + "value": "realistic" + } + ], + "type": "select" + }, + { + "default": "", + "hint": "保持角色外觀,依描述重新安排畫面。", + "id": "instruction", + "label": "畫面描述", + "placeholder": "選擇下方搭配,或描述想要的場景、服裝與動作。", + "required": true, + "rows": 4, + "type": "textarea" + }, + { + "default": "1024", + "id": "resolution", + "label": "輸出大小", + "options": [ + { + "label": "約 1 MP · 依原圖比例", + "value": "1024" + }, + { + "label": "約 2.25 MP · 依原圖比例", + "value": "1536" + }, + { + "label": "約 4 MP · 依原圖比例", + "value": "2048" + } + ], + "type": "select" + }, + { + "default": "", + "id": "negative", + "label": "負向提示詞", + "rows": 2, + "type": "textarea" + }, + { + "default": 25, + "id": "steps", + "label": "步數", + "max": 50, + "min": 1, + "step": 1, + "type": "slider" + }, + { + "default": 1.0, + "id": "cfg", + "label": "CFG", + "max": 5, + "min": 1, + "step": 0.1, + "type": "slider" + }, + { + "default": -1, + "id": "seed", + "label": "種子(-1 隨機)", + "max": 9007199254740991, + "min": -1, + "step": 1, + "type": "number" + } + ], + "id": "character-photoshoot", + "label": "角色搭配寫真", + "minimumUploads": 1, + "operatorOnly": false, + "output_kind": "image", + "studio": "image", + "uploads": [ + { + "accept": "image/*", + "id": "image", + "label": "角色原圖", + "media_kinds": [ + "image" + ], + "required": true + } + ] + } + ], + "ok": true + }, + "status": 200 + }, + "/api/compute/pipeline-recipes": { + "body": { + "ok": true, + "recipes": [ + { + "description": "先生成一張圖片,驗證完成後交給下一步製作影片。", + "fields": [ + { + "id": "image_prompt", + "label": "圖片描述", + "required": true, + "type": "textarea" + }, + { + "default": "anime", + "id": "visual_class", + "label": "畫面風格", + "options": [ + { + "label": "動畫", + "value": "anime" + }, + { + "label": "寫實", + "value": "realistic" + } + ], + "required": true, + "type": "select" + }, + { + "id": "motion_prompt", + "label": "影片動作與場景", + "required": true, + "type": "textarea" + }, + { + "default": "124", + "description": "本機、Colab 與依此工作流部署的平台使用此長度。", + "id": "native_frames", + "label": "工作流影片長度", + "options": [ + { + "label": "約 5.2 秒", + "value": "124" + }, + { + "label": "約 9.4 秒", + "value": "226" + }, + { + "label": "約 15.1 秒", + "value": "362" + } + ], + "type": "select" + }, + { + "default": 8, + "description": "僅選到 AutoIP 時,改用此服務支援的影片規格。", + "id": "autoip_seconds", + "label": "AutoIP 影片秒數", + "max": 15, + "min": 2, + "show_when": { + "placements": [ + "auto", + "autoip" + ], + "step_id": "video" + }, + "type": "number" + }, + { + "default": "480p", + "id": "autoip_resolution", + "label": "AutoIP 影片解析度", + "options": [ + { + "label": "480p", + "value": "480p" + }, + { + "label": "768p", + "value": "768p" + }, + { + "label": "2K", + "value": "2k" + } + ], + "show_when": { + "placements": [ + "auto", + "autoip" + ], + "step_id": "video" + }, + "type": "select" + } + ], + "id": "text-image-video", + "label": "文字生圖 → 影片", + "steps": [ + { + "depends_on": [], + "feature_id": "text2img", + "id": "image", + "label": "文字生圖" + }, + { + "depends_on": [ + "image" + ], + "feature_id": "h3-image-video", + "id": "video", + "label": "圖片製作影片" + } + ] + }, + { + "description": "先依指令修改圖片,再將確認完成的成果交給影片步驟。", + "fields": [ + { + "accept": "image/*", + "id": "image", + "label": "參考圖片", + "required": true, + "type": "file" + }, + { + "id": "instruction", + "label": "修改指令", + "required": true, + "type": "textarea" + }, + { + "default": "anime", + "id": "visual_class", + "label": "畫面風格", + "options": [ + { + "label": "動畫", + "value": "anime" + }, + { + "label": "寫實", + "value": "realistic" + } + ], + "required": true, + "type": "select" + }, + { + "id": "motion_prompt", + "label": "影片動作與場景", + "required": true, + "type": "textarea" + }, + { + "default": "124", + "description": "本機、Colab 與依此工作流部署的平台使用此長度。", + "id": "native_frames", + "label": "工作流影片長度", + "options": [ + { + "label": "約 5.2 秒", + "value": "124" + }, + { + "label": "約 9.4 秒", + "value": "226" + }, + { + "label": "約 15.1 秒", + "value": "362" + } + ], + "type": "select" + }, + { + "default": 8, + "description": "僅選到 AutoIP 時,改用此服務支援的影片規格。", + "id": "autoip_seconds", + "label": "AutoIP 影片秒數", + "max": 15, + "min": 2, + "show_when": { + "placements": [ + "auto", + "autoip" + ], + "step_id": "video" + }, + "type": "number" + }, + { + "default": "480p", + "id": "autoip_resolution", + "label": "AutoIP 影片解析度", + "options": [ + { + "label": "480p", + "value": "480p" + }, + { + "label": "768p", + "value": "768p" + }, + { + "label": "2K", + "value": "2k" + } + ], + "show_when": { + "placements": [ + "auto", + "autoip" + ], + "step_id": "video" + }, + "type": "select" + } + ], + "id": "edit-image-video", + "label": "指令改圖 → 影片", + "steps": [ + { + "depends_on": [], + "feature_id": "img2img", + "id": "image", + "label": "指令改圖" + }, + { + "depends_on": [ + "image" + ], + "feature_id": "h3-image-video", + "id": "video", + "label": "圖片製作影片" + } + ] + }, + { + "description": "依描述生成合成聲音,驗證音訊後交給真人影片對嘴;不綁定或驗證任何角色身份。", + "fields": [ + { + "accept": "video/*", + "id": "video", + "label": "可清楚辨識臉部的真人影片", + "required": true, + "type": "file" + }, + { + "id": "speech_text", + "label": "要說的話", + "maxLength": 2400, + "required": true, + "type": "textarea" + }, + { + "description": "例如:溫和、清晰的中性聲線;依文字描述設計聲音,不使用真人聲音參考。", + "id": "voice_style", + "label": "聲音描述", + "required": true, + "type": "textarea" + }, + { + "default": "sequential", + "id": "sync_mode", + "label": "影片影格對應", + "options": [ + { + "label": "依語音長度伸縮", + "value": "sequential" + }, + { + "label": "循環播放原影片", + "value": "repetitive" + } + ], + "type": "select" + } + ], + "id": "voice-design-lipsync", + "label": "設計聲音 → 影片對嘴", + "steps": [ + { + "depends_on": [], + "feature_id": "voxcpm-tts", + "id": "voice", + "label": "設計合成聲音" + }, + { + "depends_on": [ + "voice" + ], + "feature_id": "lipsync", + "id": "lipsync", + "label": "影片對嘴" + } + ] + } + ] + }, + "status": 200 + }, + "/api/compute/pipelines": { + "body": { + "ok": true, + "pipelines": [] + }, + "status": 200 + }, + "/api/compute/platform-admin": { + "body": { + "ok": true, + "users": [] + }, + "status": 200 + }, + "/api/compute/preferences": { + "body": { + "auto_order": [ + "local" + ], + "auto_policy": "user_order", + "default_placement": "local", + "feature_placements": {}, + "ok": true, + "revision": 0 + }, + "status": 200 + }, + "/api/history?max_items=500&scope=own": { + "body": { + "error": "", + "ok": false + }, + "status": 502 + }, + "/api/provider-characters": { + "body": { + "characters": [], + "credits_spent": 0, + "filters": { + "visualClass": null + }, + "next_cursor": null, + "provider_transport_performed": false, + "schema_version": 1 + }, + "status": 200 + }, + "/api/providers": { + "body": { + "features": { + "minimax_h3": { + "authorization_recorded": false, + "contracts": { + "h3.i2v.anime.stock.v1": false, + "h3.i2v.realistic.stock.v1": false, + "h3.ref2va-image.anime.stock.v1": false, + "h3.ref2va-image.realistic.stock.v1": false, + "h3.t2v.stock.v1": false + }, + "execution_enabled": false, + "license_blocked": true, + "models_ready": false, + "runtime_ready": false, + "status": "license_blocked" + } + }, + "providers": [ + { + "account_count": 1, + "account_id": "local-main", + "configured": true, + "execution_enabled": true, + "provider_id": "local_comfy", + "runtime": { + "endpoint_scope": "loopback", + "node_count": null, + "ready": true, + "version": null + }, + "status": "ready" + }, + { + "account_count": 0, + "account_id": null, + "compatibility_receipt": null, + "compatibility_receipt_current": false, + "configured": false, + "credential_readback": false, + "execution_enabled": false, + "live_probe_performed": false, + "provider_id": "autoip", + "status": "needs_credential" + }, + { + "account_count": 0, + "account_id": null, + "configured": false, + "execution_enabled": false, + "generation": "disabled", + "import_capabilities": [ + "characters", + "profile_photos", + "media_versions", + "lineage" + ], + "import_contract": "castle.clipmode-export.v1", + "import_mode": "manual_import_only", + "provider_id": "clipmode", + "status": "offline_export_required", + "sync": "disabled" + } + ], + "schema_version": 1, + "transport_dispatched": false + }, + "status": 200 + } +} diff --git a/webui/docs/docs.js b/webui/docs/docs.js index 5009329..44518d7 100644 --- a/webui/docs/docs.js +++ b/webui/docs/docs.js @@ -6,6 +6,23 @@ const demoBase = new URL('./', location.href); const reply = (data, status = 200) => new Response(JSON.stringify(data), {status, headers: {'Content-Type': 'application/json'}}); let registry = null, workflows = null; + const unknownRequests = []; + const computeScreens = '.compute-settings,.compute-placement,.compute-production,.colab-content,castle-provider-fabric'; + const actionMessage = '這是功能說明站;請在自己的 WebUI 執行此操作。'; + const actionMessageEn = 'This is a documentation site; perform this action in your own WebUI.'; + function showComputeAction() { + for (const screen of document.querySelectorAll(computeScreens)) { + let status = screen.querySelector(':scope > .docs-compute-action'); + if (!status) { + status = document.createElement('p');status.className = 'docs-compute-action console-notice';status.setAttribute('role', 'status'); + const notice = screen.querySelector(':scope > .docs-compute-notice'); + if (notice) notice.after(status); else screen.prepend(status); + } + status.dataset.i18nZh = actionMessage;status.dataset.i18nEn = actionMessageEn; + const message = window.WebComfyI18n?.t(actionMessage, actionMessageEn) || actionMessage; + if (status.textContent !== message) status.textContent = message; + } + } const ready = Promise.all(['app-guide.json', 'catalog.json'].map(async path => { const response = await nativeFetch(new URL(path, base), {credentials: 'omit', cache: 'no-cache'}); if (!response.ok) throw Error('說明資料載入失敗,請重新整理頁面。'); @@ -55,22 +72,24 @@ window.WebSocket = class { constructor() {throw Error('說明站不建立即時服務連線');} }; window.XMLHttpRequest = class { open() {throw Error('說明站不建立 API 連線');} }; if (navigator.sendBeacon) navigator.sendBeacon = () => false; - const emptyProvider = {ok: true, provider_transport_performed: false, credits_spent: 0, next_cursor: null}; window.fetch = async (input, options = {}) => { const url = new URL(typeof input === 'string' || input instanceof URL ? input : input.url, location.href); const method = String(options.method || input?.method || 'GET').toUpperCase(); await ready; - if (url.origin !== location.origin || method !== 'GET') return reply({ok: false, error: '這是功能說明站;請在自己的 WebUI 執行此操作。'}, 405); + if (url.origin !== location.origin || method !== 'GET') { + showComputeAction(); + return reply({ok: false, error: window.WebComfyI18n?.t(actionMessage, actionMessageEn) || actionMessage}, 405); + } + // History has a separate empty adapter: the real empty server needs ComfyUI. + if (url.pathname === '/api/history') return reply({images: [], jobs: [], recent_errors: [], items: [], has_more: false}); + const recorded = registry.computeDemo?.[url.pathname + url.search]; + if (recorded) return reply(recorded.body, recorded.status); // No fallthrough to native fetch: unknown calls fail closed in memory. switch (url.pathname) { case '/api/auth/status': return reply({configured: true, authenticated: true, lane: 'local', user: {email: 'documentation@example.invalid', displayName: '說明模式', role: 'admin', operator: true}}); case '/api/features': return reply({studios: registry.studios, features: registry.features.map(feature => ({...feature, ready: true, runnable: !['storage', 'gated'].includes(feature.kind), missingModels: [], missingNodes: [], documentationOnly: true}))}); case '/api/characters': return reply({characters: window.WebComfyCharacterSession?.list() || [], actions: []}); - case '/api/provider-characters': return reply({...emptyProvider, characters: []}); - case '/api/providers': return reply({...emptyProvider, providers: []}); - case '/api/assets': return reply({...emptyProvider, assets: [], items: []}); case '/api/queue': return reply({jobs: [], terminal: [], recent_errors: [], summary: {running: 0, pending: 0, total: 0, external: 0}}); - case '/api/history': return reply({items: [], has_more: false}); case '/api/posts': return reply({posts: [], items: []}); case '/api/voices': return reply({voices: (registry.demos?.['voice-library']?.output?.audio_tracks || []).map((track, index) => ({id: 'docs-voice-' + index, name: track.title, url: track.src, transcript: track.transcript, source: '預製示範音訊 / Prepared voice sample', canDelete: false})), items: []}); case '/api/voiceover/batches': return reply({batches: []}); @@ -81,6 +100,7 @@ if (url.href === new URL('catalog.json', base).href) return reply(workflows); if (url.href === new URL('app-guide.json', base).href) return reply(registry); if (workflows.items.some(item => item.download_url && url.href === new URL(item.download_url, base).href)) return nativeFetch(url, {credentials: 'omit'}); + unknownRequests.push(url.pathname + url.search); return reply({ok: false, error: '此資料由安裝後的本機服務提供;說明站沒有個人資料。'}, 404); }; const el = (tag, text = '', className = '') => { @@ -105,6 +125,7 @@ }}); } window.addEventListener('webcomfy:language', () => { + disableSecrets(); document.querySelectorAll('[data-docs-close-zh]').forEach(node => node.setAttribute('aria-label', window.WebComfyI18n?.t(node.dataset.docsCloseZh, node.dataset.docsCloseEn) || node.dataset.docsCloseZh)); updateDocsIdentity(); }); @@ -227,7 +248,7 @@ const selected = selectedFeature(); return selected ? openFeature(selected.id, opener) : openHelp(opener); } window.WebComfyDocs = { - ready, openFeature, openGraph, openHelp, + ready, openFeature, openGraph, openHelp, unknownRequests, renderCharacterRoute: (route, hooks) => window.WebComfyCharacterSession?.render(route, hooks), completeCharacter: character => window.completeDocumentationCharacter(character), createCharacterDemo() { location.hash = '#/characters'; openFeature('character-create'); }, @@ -240,6 +261,7 @@ libraryOptions(openSheet) {return {openSheet, docsMode: true, catalogUrl: new URL('catalog.json', base).href, onGraph: openLibraryGraph, onSelect(id) {history.replaceState(history.state, '', '#/workflow/' + encodeURIComponent(id));}};}, }; document.addEventListener('submit', event => { + if (event.target.closest(computeScreens)) {event.preventDefault();event.stopImmediatePropagation();showComputeAction();return;} if (event.target.closest('[data-docs-interactive="true"]')) return; event.preventDefault();event.stopImmediatePropagation(); if (event.target.dataset.demoId) window.WebComfyTour.start(event.target); else explainAction(event.submitter); @@ -247,6 +269,7 @@ document.addEventListener('click', event => { const target = event.target.closest('button,input,a'); if (!target || target.closest('[data-docs-interactive="true"],.sheet-layer .workflow-details')) return; + if (target.closest(computeScreens) && !target.matches('input[type=password],input[type=file]')) return; if (target.matches('a[href="/admin"]') || (target.matches('button') && ['登出', 'Sign out', 'Log out'].includes(target.textContent.trim()))) { event.preventDefault();event.stopImmediatePropagation();openHelp(target);return; } @@ -260,7 +283,29 @@ document.addEventListener('drop', event => {event.preventDefault();event.stopImmediatePropagation();if (!window.WebComfyTour?.handleDrop(event)) explainAction(event.target);}, true); document.addEventListener('beforeinput', event => {if(event.target.matches('input[type=password]')) {event.preventDefault();event.stopImmediatePropagation();}}, true); const disableSecrets = () => { - document.querySelectorAll('input[type=password]').forEach(input => {input.disabled = true;input.value = '';input.placeholder = '請在本機 WebUI 設定';}); + const placeholder = window.WebComfyI18n?.t('說明站不接受金鑰', 'Keys are not accepted on the documentation site') || '說明站不接受金鑰'; + for (const input of document.querySelectorAll('input')) { + const credential = input.type === 'password' || (input.closest(computeScreens) && /credential|api.?key|token|secret|授權碼|金鑰/i.test([input.name, input.id, input.getAttribute('aria-label')].join(' '))); + if (credential) {input.disabled = true;input.value = '';if (input.placeholder !== placeholder) input.placeholder = placeholder;} + } + for (const screen of document.querySelectorAll(computeScreens)) { + if (!screen.querySelector(':scope > .docs-compute-notice')) { + const notice = document.createElement('p');notice.className = 'docs-compute-notice panel-note'; + notice.dataset.i18nZh = '說明站只展示畫面:不會連線、不接受金鑰,也不會保存設定。'; + notice.dataset.i18nEn = 'Documentation site: screens only. Nothing connects, no keys are accepted and nothing is saved.'; + notice.textContent = window.WebComfyI18n?.t(notice.dataset.i18nZh, notice.dataset.i18nEn) || notice.dataset.i18nZh; + screen.prepend(notice); + } + // Empty credential fields remain inert; their actions still explain the demo. + for (const button of screen.querySelectorAll('.console-test button')) button.disabled = false; + } + // A rejected live preview must not disable playback of the existing canned tour. + for (const form of document.querySelectorAll('form[data-demo-id]')) { + if (form.querySelector('.app-demo')?.dataset.state === 'running') continue; + const allowed = window.WebComfyHardware?.canUse(form.dataset.demoId); + if (allowed === undefined) continue; + for (const button of form.querySelectorAll('[data-demo-submit]')) button.disabled = !allowed; + } updateDocsIdentity(); }; new MutationObserver(disableSecrets).observe(document.documentElement, {childList: true, subtree: true}); From 4fb1998157fe574013e2eec77147dce167d5f0b5 Mon Sep 17 00:00:00 2001 From: Ted H Date: Sat, 14 Nov 2026 22:15:55 -0500 Subject: [PATCH 7/7] Prove session input containment before reading the file The Colab session worker checked each uploaded input with is_symlink() and resolve() before it knew the path stayed inside the job directory. Resolve the path first, refuse anything outside the directory or reached through a link, and only then read the size and digest. Code scanning reported the earlier order as path injection. Co-Authored-By: Claude Opus 5.5 --- scripts/colab_session_inputs.py | 11 ++++++--- scripts/test_compute_r40v6_robustness.py | 30 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/scripts/colab_session_inputs.py b/scripts/colab_session_inputs.py index 4ae86fa..36c692a 100644 --- a/scripts/colab_session_inputs.py +++ b/scripts/colab_session_inputs.py @@ -1,5 +1,5 @@ """Transport aliases only; frozen bundle, graph and strict runner pins unchanged.""" -import copy,hashlib +import copy,hashlib,os from pathlib import Path SUFFIXES={'.png','.jpg','.jpeg','.webp','.mp4','.mov','.webm','.wav','.mp3','.flac','.m4a'} def validate_native_manifest(manifest,job_dir,check_files=True): @@ -11,12 +11,17 @@ def validate_native_manifest(manifest,job_dir,check_files=True): if not isinstance(actual,list) or len(actual)!=len(expected):raise ValueError('Native transport inventory mismatch') original['input_files']=expected frozen(original,job_dir,check_files=False) + root=os.path.realpath(job_dir) if check_files else None for old,new in zip(expected,actual): name=new.get('path','');suffix=Path(name).suffix.lower() allowed=name==old['path'] or (Path(old['path']).suffix.lower() not in SUFFIXES and suffix in SUFFIXES and name==old['path']+suffix) if not allowed or new.get('size')!=old['size'] or new.get('sha256')!=old['sha256']:raise ValueError('Native transport identity mismatch') - p=Path(job_dir)/name - if check_files and (p.is_symlink() or not p.resolve().is_relative_to(Path(job_dir).resolve()) or p.stat().st_size!=new['size'] or hashlib.sha256(p.read_bytes()).hexdigest()!=new['sha256']):raise ValueError('Native input integrity failure') + if check_files: + # Prove the resolved path stays inside the job directory before any file access; links below it are refused. + lexical=os.path.normpath(os.path.join(root,name)) + target=os.path.realpath(os.path.join(root,name)) + if not target.startswith(root+os.sep):raise ValueError('Native input integrity failure') + if target!=lexical or os.path.islink(target) or os.path.getsize(target)!=new['size'] or hashlib.sha256(Path(target).read_bytes()).hexdigest()!=new['sha256']:raise ValueError('Native input integrity failure') if check_files: for name,item in original['jobs'][0]['bundle'].get('runner_sources',{}).items(): p=Path(job_dir)/'runner'/name diff --git a/scripts/test_compute_r40v6_robustness.py b/scripts/test_compute_r40v6_robustness.py index f6160d3..75ae285 100644 --- a/scripts/test_compute_r40v6_robustness.py +++ b/scripts/test_compute_r40v6_robustness.py @@ -783,3 +783,33 @@ def test_point_monitor_pause_ignores_a_patched_shared_sleep(monkeypatch): assert ticked.wait(2) threading.Event().wait(0.3) assert calls == [] + + +def test_native_input_check_proves_containment_before_reading(tmp_path, monkeypatch): + """Session inputs are read only after their resolved path is proven to stay inside the job directory.""" + import types + import scripts.colab_session_inputs as inputs + monkeypatch.setitem(sys.modules, 'native_schema', types.SimpleNamespace(validate_native_manifest=lambda manifest, job_dir, check_files=True: manifest)) + job = tmp_path / 'job' + (job / 'input').mkdir(parents=True) + data = b'\x89PNG\r\n\x1a\n' + b'0' * 24 + + def manifest(name, payload=data): + entry = {'path': name, 'size': len(payload), 'sha256': hashlib.sha256(payload).hexdigest()} + return {'jobs': [{'bundle': {'inputs': [{'name': name, 'bytes': entry['size'], 'sha256': entry['sha256']}]}}], 'input_files': [entry]} + + (job / 'input' / 'a.png').write_bytes(data) + assert inputs.validate_native_manifest(manifest('input/a.png'), job)['input_files'][0]['path'] == 'input/a.png' + (tmp_path / 'outside.png').write_bytes(data) + (job / 'input' / 'link.png').symlink_to(job / 'input' / 'a.png') + (job / 'linked').symlink_to(job / 'input', target_is_directory=True) + (job / 'loop.png').symlink_to(job / 'loop.png') + (tmp_path / 'outdir').mkdir() + (job / 'linked_out').symlink_to(tmp_path / 'outdir', target_is_directory=True) + for name in ('../outside.png', str(tmp_path / 'outside.png'), 'input/link.png', 'linked/a.png', 'loop.png', 'linked_out/../input/a.png'): + with pytest.raises(ValueError, match='Native input integrity failure'): + inputs.validate_native_manifest(manifest(name), job) + with pytest.raises(ValueError, match='Native input integrity failure'): + inputs.validate_native_manifest(manifest('input/a.png', data[:-1] + b'1'), job) + with pytest.raises(FileNotFoundError): + inputs.validate_native_manifest(manifest('input/missing.png'), job)