Spaces:
Sleeping
Sleeping
Download tools/check_workflow_lifecycle.py from fffiloni/viggle-mine-workflow: direct link, hf CLI and curl.
- Browser
- Download file 7.8 kB
-
https://huggingface.co/spaces/fffiloni/viggle-mine-workflow/resolve/main/tools/check_workflow_lifecycle.py
- Command line
-
hf download hf://spaces/fffiloni/viggle-mine-workflow/tools/check_workflow_lifecycle.py
-
curl -L -o check_workflow_lifecycle.py https://huggingface.co/spaces/fffiloni/viggle-mine-workflow/resolve/main/tools/check_workflow_lifecycle.py
7.8 kB
| """CPU fault injection into the corrected thread bridge and real Gradio Workflow. | |
| No model imports, GPU allocations or inference claims. The blocked worker is | |
| explicitly released by the test, never left running. Test routes exist only in | |
| this disposable local process, not in the production application. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| from pathlib import Path | |
| import subprocess | |
| import sys | |
| import threading | |
| import time | |
| ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(ROOT)) | |
| def serve(port): | |
| import gradio as gr | |
| import workflow_artifacts as artifacts | |
| from types import SimpleNamespace | |
| from gradio.context import LocalContext | |
| from workflow_execution import install | |
| state = {"entered": False, "finished": False, "inner_context": None, | |
| "coordinator_finished": False, "worker_calls": 0} | |
| release = threading.Event() | |
| from contextvars import ContextVar | |
| marker = ContextVar("probe_marker", default="missing") | |
| def worker(*args): | |
| state["worker_calls"] += 1 | |
| state["inner_context"] = marker.get() | |
| state["request_present"] = LocalContext.request.get(None) is not None | |
| state["event_present"] = LocalContext.event_id.get(None) is not None | |
| state["blocks_present"] = LocalContext.blocks.get(None) is not None | |
| if args[0] == "fail": | |
| raise RuntimeError("INJECTED_WORKER_FAILURE") | |
| state["entered"] = True | |
| if not release.wait(15): | |
| raise RuntimeError("Test release deadline reached") | |
| state["finished"] = True | |
| return ["released"] | |
| bridge = install(SimpleNamespace(render_all_segments=worker), lambda *a: 10) | |
| def probe(mode: str, progress=gr.Progress()): | |
| state["coordinator_finished"] = False | |
| marker.set("outer-context") | |
| def compute(): | |
| value = bridge(mode, [], [90], [], [], 32, 32, [], 42, [], [], | |
| str(artifacts.STATE / "nonexistent-progress.json"), progress) | |
| return (value,), [] | |
| try: | |
| return artifacts.cached("lifecycle_probe", [mode], compute)[0] | |
| finally: | |
| state["coordinator_finished"] = True | |
| demo = gr.Workflow(bind={"Probe": probe}) | |
| app = type(demo.app)() | |
| def get_state(): | |
| return {**state, "gpu_call_pending": bridge.pending is not None, | |
| "cache_files": len(list((artifacts.STATE / "cache").glob("*.json")))} | |
| def unblock(): | |
| release.set() | |
| return {"released": True} | |
| demo.queue().launch(server_name="127.0.0.1", server_port=port, | |
| ssr_mode=False, _app=app, show_error=True) | |
| def check(work, port): | |
| import httpx | |
| from gradio_client import Client | |
| work.mkdir(parents=True, exist_ok=True) | |
| env = dict(os.environ, APP_DATA_ROOT=str(work / "data"), | |
| GRADIO_ANALYTICS_ENABLED="False", HF_HUB_OFFLINE="1", | |
| NO_PROXY="127.0.0.1,localhost", no_proxy="127.0.0.1,localhost") | |
| # Client inherits these for its local requests too. | |
| os.environ.update(NO_PROXY=env["NO_PROXY"], no_proxy=env["no_proxy"]) | |
| evidence = {"scope": "CPU fault injection; NOT a ZeroGPU reproduction", "checks": []} | |
| with (work / "server.log").open("w") as log: | |
| process = subprocess.Popen([sys.executable, __file__, "--serve", "--port", str(port)], | |
| cwd=work, env=env, stdout=log, stderr=subprocess.STDOUT) | |
| try: | |
| with httpx.Client(base_url=f"http://127.0.0.1:{port}", trust_env=False, timeout=3) as http: | |
| def until(predicate, seconds=12): | |
| deadline = time.monotonic() + seconds | |
| while time.monotonic() < deadline: | |
| try: | |
| if predicate(): | |
| return | |
| except httpx.ConnectError: | |
| pass | |
| time.sleep(.1) | |
| raise AssertionError("Condition did not become true") | |
| until(lambda: http.get("/config").status_code == 200) | |
| client = Client(f"http://127.0.0.1:{port}", verbose=False) | |
| failed = client.submit(json.dumps(["fail"]), api_name="/predict_fn_Probe") | |
| try: | |
| failed.result(timeout=8) | |
| except Exception as exc: | |
| assert "INJECTED_WORKER_FAILURE" in str(exc), repr(exc) | |
| else: | |
| raise AssertionError("Worker failure was swallowed") | |
| assert http.get("/test/state").json()["cache_files"] == 0 | |
| evidence["checks"].append("worker exception reaches queued Workflow client; no failed result cached") | |
| held = client.submit(json.dumps(["blocked"]), api_name="/predict_fn_Probe") | |
| until(lambda: http.get("/test/state").json()["entered"]) | |
| assert not held.done() | |
| held.cancel() | |
| until(lambda: http.get("/test/state").json()["coordinator_finished"]) | |
| observed = http.get("/test/state").json() | |
| assert observed["entered"] and not observed["finished"] | |
| assert observed["gpu_call_pending"] and observed["cache_files"] == 0 | |
| evidence["checks"].append("client cancellation ends coordinator; unfinished worker stays protected; no completed take") | |
| assert observed["inner_context"] == "outer-context" | |
| assert all(observed[k] for k in ("request_present", "event_present", "blocks_present")) | |
| evidence["checks"].append("real queued Workflow request, event, blocks and ContextVars reach GPU-call thread") | |
| rejected = client.submit(json.dumps(["overlap"]), api_name="/predict_fn_Probe") | |
| try: | |
| rejected.result(timeout=8) | |
| except Exception as exc: | |
| assert "still ending" in str(exc), repr(exc) | |
| else: | |
| raise AssertionError("Overlapping job was allowed") | |
| assert http.get("/test/state").json()["worker_calls"] == 2 | |
| evidence["checks"].append("new backend work rejected while cancelled worker remains active") | |
| http.post("/test/release").raise_for_status() | |
| until(lambda: not http.get("/test/state").json()["gpu_call_pending"]) | |
| assert http.get("/test/state").json()["finished"] | |
| assert http.get("/test/state").json()["cache_files"] == 0 | |
| evidence["checks"].append("late worker completion does not commit cancelled result") | |
| retried = client.submit(json.dumps(["retry"]), api_name="/predict_fn_Probe") | |
| retried.result(timeout=8) | |
| assert http.get("/test/state").json()["cache_files"] == 1 | |
| evidence["checks"].append("new request succeeds after previous worker actually exits") | |
| evidence["passed"] = True | |
| (work / "result.json").write_text(json.dumps(evidence, indent=2) + "\n") | |
| print(json.dumps(evidence, indent=2)) | |
| finally: | |
| process.terminate() | |
| try: | |
| process.wait(timeout=5) | |
| except subprocess.TimeoutExpired: | |
| process.kill() | |
| process.wait() | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--serve", action="store_true") | |
| parser.add_argument("--workdir", default="lifecycle-check") | |
| parser.add_argument("--port", type=int, default=7867) | |
| args = parser.parse_args() | |
| if args.serve: | |
| serve(args.port) | |
| else: | |
| check(Path(args.workdir).resolve(), args.port) | |