EnergyVenom's picture
Astra 0598704: 26D AP/AR/GL fixes verified live, payments, subledger accounting, edge cases, learned navigation, consultant step import (059870495533)
2d71dc3 verified
Raw History Blame Contribute Delete
40.7 kB
"""Execute phase: executor (Playwright attempt, --retries=0) and self_heal (locator rename proposal from the failure's
ARIA snapshot; applied only as a retry override; the permanent fix needs human approval)."""
from __future__ import annotations
import difflib
import json
import re
from pathlib import Path
from ...adapters import playwright as pw
from ...adapters.legacy import classifier, merge_attempts
from ...config import ROOT
from ...llm.base import LLMRequest, Sensitivity
from ...llm.schemas import HealProposal
from . import ai_scenarios
from ...platform import assisted_signin, canary, healing, liveview
from ...platform.killswitch import KillSwitchEngaged
from ...platform.rundb import now_iso
LOCATOR_RE = re.compile(r"getBy(Role|Label)\(\s*'([^']+)'(?:\s*,\s*\{\s*name:\s*'([^']+)')?")
LOCATOR_FAIL_RE = re.compile(r"strict mode violation|waiting for getBy(Role|Label)|not found|element\(s\) not found|Timeout \d+ms exceeded", re.I)
ARIA_RE = re.compile(r"^\s*-\s+([a-z]+)\s+\"([^\"]+)\"", re.M)
def smoke_ids(modules: list[str]) -> list[str]:
"""Tag ids of automation/tests/smoke/*.spec.ts for these modules (scripts with no YAML case, e.g. P2P-SMOKE-001)."""
out = []
for p in sorted((ROOT / "automation" / "tests" / "smoke").glob("*.spec.ts")):
for tag in re.findall(r"['\"`]@([A-Z][A-Z0-9]{1,5}-[A-Z0-9-]+)['\"`]", p.read_text(encoding="utf-8")):
if tag.split("-", 1)[0] in modules and tag not in out:
out.append(tag)
return out
def failing_ids(report_file: str) -> list[str]:
clf = classifier()
recs = clf.parse_report(clf.load_report(report_file))
return [r.case_id or r.title for r in recs if r.outcome == "failed"]
def outcomes(merged: str) -> tuple[dict, dict]:
clf = classifier()
recs = clf.parse_report(clf.load_report(merged))
out = {}
for r in recs:
cid = r.case_id or r.title
out[cid] = r.outcome
counts = {"total": len(recs), **{k: sum(1 for r in recs if r.outcome == k) for k in ("passed", "failed", "flaky", "skipped")}}
return out, counts
def browser_failure(out_file: str | Path, res: dict | None) -> str | None:
"""A failure of the browser run as a whole: Playwright reported top-level errors (it could not start, a browser or
worker crashed, the config failed) or exited non-zero, AND no scenario result was recorded. Then the attempt says
nothing about the scenarios and must not be read as 'all passed'. Returns the reason in words, or None."""
f = Path(out_file)
try:
rep = json.loads(f.read_text(encoding="utf-8"))
except (OSError, ValueError):
return "Playwright's report could not be read, so no scenario result was recorded."
_, counts = outcomes(str(f))
errs = [str((e or {}).get("message") or "").strip().splitlines()[0][:200] for e in rep.get("errors") or [] if isinstance(e, dict)]
code = (res or {}).get("exit_code") or 0
if counts["total"] or not (errs or code):
return None
why = f"Playwright stopped before any scenario ran (exit {code})" if code else "Playwright stopped before any scenario ran"
return why + (f": {errs[0]}" if errs and errs[0] else "") + "."
def plan_attempt(state, svc, clean: bool | None = None) -> dict:
"""Which cases this attempt runs (attempt 0: in-scope; attempt 1: failed ids only) and the run_attempt arguments.
clean: whether attempt 0 deletes old reports first; None decides it from the run folder (resumed_attempt)."""
run_id = state["run_id"]
run_dir = svc.run_dir(run_id)
files = list(state.get("attempt_files") or [])
attempt = len(files)
mode = state.get("playwright_mode") or svc.cfg.playwright_mode
if attempt == 0:
if clean is None:
clean = not resumed_attempt(run_dir)
if clean: # a fresh attempt 0 never reuses old reports (a resumed one keeps its finished chunks)
for f in run_dir.glob("attempt-*.json"):
f.unlink()
scripts = state.get("scripts") or {}
ids = [c["id"] for c in state.get("test_cases") or []
if c["origin"] == "library" or (scripts.get(c["id"], {}).get("dry_run_ok"))]
if not state.get("case_filter") and mode == "live": # full-module live runs also execute the module's smoke specs (QA C1 counts them)
ids += smoke_ids(sorted({c["module"] for c in state.get("test_cases") or []}))
else:
ids = list(state.get("failures") or [])
mods = sorted({c["module"] for c in state.get("test_cases") or []})
cred_env: dict = {}
for m in mods:
cred_env.update(svc.vault.executor_env(m))
live_on, _why = liveview.availability(svc.cfg, mode=mode, wanted=bool(state.get("live_view")), modules=mods)
fusion_pod = svc.fusion_pod_id(run_id)
config, groups = None, None
if fusion_pod is not None and mode == "live": # a real Fusion pod: its own test set, its test user from the vault
from ...platform.pods import PodRegistry
reg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)
cred_env.update(reg.executor_env(fusion_pod, run_id) or {})
config = "playwright.fusion.config.ts"
groups = user_groups(reg, fusion_pod, run_id, ids, {c["id"]: c["module"] for c in state.get("test_cases") or []}, cred_env)
# assisted sign-in: the tests start from the session a person signed in at the sign_in gate (run_pass hands it over)
assisted = config == FUSION_CONFIG and assisted_signin.assisted_pod(svc, run_id)
return {"run_id": run_id, "attempt": attempt, "ids": ids, "mode": mode, "files": files, "run_dir": str(run_dir), "config": config,
"assisted": assisted,
"live_dir": str(liveview.live_dir(svc.cfg, run_id)) if live_on and ids else None,
"out_file": str(run_dir / f"attempt-{attempt}.json"), "stub_knobs": state.get("stub_knobs"),
"drafts_dir": str(svc.cfg.path("staging", "specs", run_id)),
"library_dir": str(ai_scenarios.library_root(svc) / "automation" / "tests" / "fusion" / "steps"),
"overrides": str(run_dir / "heal-overrides.json") if attempt == 1 else None, "cred_env": cred_env, "groups": groups,
"run_dirs": list((state.get("run_results") or {}).get("run_dirs") or [])}
def user_groups(reg, pod_id: int, run_id: str, ids: list[str], module_of: dict[str, str], base_env: dict) -> list[dict] | None:
"""Each area's scenarios signed in as that area's test user (FPT_FUSION_AREA_USERS): one Playwright pass per user,
in the order the areas come. None when every scenario uses the pod's own test user (one pass, as before); a run whose
scenarios all belong to another user's area is still that user's one pass (a PO-only run went in as the Payables user,
who has no Purchase Orders, seen live)."""
envs: dict[str, dict] = {}
groups: dict[str, dict] = {}
for cid in ids:
area = (module_of.get(cid) or cid.split("-", 1)[0]).upper()
if area not in envs:
envs[area] = reg.executor_env(pod_id, run_id, area=area) or {}
user = envs[area].get("FUSION_USERNAME") or ""
g = groups.setdefault(user, {"user": user, "areas": [], "ids": [], "cred_env": {**base_env, **envs[area]}})
if area not in g["areas"]:
g["areas"].append(area)
g["ids"].append(cid)
base_user = base_env.get("FUSION_USERNAME") or ""
if len(groups) == 1 and (not base_user or base_user in groups):
return None
return list(groups.values()) or None
FUSION_CONFIG = "playwright.fusion.config.ts"
STARTUP_MINUTES = 10 # a pass's own start-up: Playwright, the browser and the test user's one sign-in
def attempt_timeout_s(cfg, scenarios: int, workers=None) -> int:
"""How long a browser pass of this many scenarios on a Fusion pod may take: its scenarios shared over the workers that
run at once (FPT_FUSION_WORKERS), fusion_scenario_minutes each, plus start-up, kept between the floor and the ceiling.
A fixed hour stopped every big pass at its deadline, and a pass stopped that way loses all its results."""
w = max(1, min(4, int(workers or cfg.fusion_workers or 1)))
rounds = -(-max(1, int(scenarios)) // w)
minutes = STARTUP_MINUTES + rounds * max(1, int(cfg.fusion_scenario_minutes))
return 60 * max(int(cfg.fusion_attempt_min_minutes), min(int(cfg.fusion_attempt_max_minutes), minutes))
class RunCancelled(RuntimeError):
pass
def _stop_check(svc, run_id: str) -> None:
"""Called while a remote pass runs: the kill switch, or a person cancelling the run, stops the runner's job too
(nothing else would: the browser is not a process of this server)."""
svc.kill.check("executor.remote")
r = svc.db.get_run(run_id)
if isinstance(r, dict) and r.get("status") == "cancelled":
raise RunCancelled(f"run {run_id} was cancelled")
def progress_file(out_file: str | Path) -> Path:
"""Where a Fusion attempt lists its finished passes (next to its report; a fresh attempt 0 deletes it with the reports)."""
out = Path(out_file)
return out.with_name(f"{out.stem}.chunks.json")
def _finished_passes(prog: Path, ids: list[str], size: int) -> tuple[dict, dict]:
"""(chunk -> report, chunk -> run dir) of the passes an earlier try of this attempt finished, when it planned the
same scenarios in the same passes; nothing otherwise."""
try:
d = json.loads(prog.read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}, {}
if not isinstance(d, dict) or d.get("ids") != ids or d.get("size") != size:
return {}, {}
done = {int(k): v for k, v in (d.get("done") or {}).items() if Path(v).exists()}
return done, {k: v for k, v in ((int(k), v) for k, v in (d.get("dirs") or {}).items()) if k in done and v}
def forget_passes(out_file: str | Path) -> None:
"""A try of the attempt is thrown away (nothing ran): its pass reports and their list go, so the next try runs all."""
out = Path(out_file)
for f in out.parent.glob(f"{out.stem}.*.json"):
f.unlink(missing_ok=True)
def resumed_attempt(run_dir: str | Path) -> bool:
"""Attempt 0 entered again (the run was resumed after a restart or a failure) keeps its finished passes: a list of
them, or the runner job it was following, is still in the run folder. A first entry finds neither."""
from ...adapters.remote_runner import saved_job
job = saved_job(Path(run_dir))
return any(Path(run_dir).glob("attempt-0*.chunks.json")) or bool(job and job.get("attempt") == 0)
def run_planned(plan: dict, svc, **extra) -> dict:
"""Default runner (LangGraph path): one Playwright invocation for the attempt; one per test user when the areas sign
in as different users (plan["groups"]), merged into the attempt's one report. On a Fusion pod an attempt runs in
passes of at most fusion_chunk_scenarios, each with a time budget for its size (run_fusion)."""
if plan.get("groups"):
return run_groups(plan, svc, **extra)
if plan["mode"] == "live" and plan.get("config") == FUSION_CONFIG and plan["ids"]:
return run_fusion(plan, svc, **extra)
return run_pass(plan, svc, **extra)
def run_fusion(plan: dict, svc, **extra) -> dict:
"""A browser attempt on a Fusion pod: passes of at most fusion_chunk_scenarios scenarios (pw.run_attempt_chunked, as
under Temporal), each with its own time budget and report, merged into the attempt's one report. A pass that runs
out of time loses only its own scenarios (recorded as timed out, so the retry runs them), and the finished passes are
listed next to the report so a resumed run skips them. An attempt that fits in one pass keeps its usual names."""
ids, out = list(plan["ids"]), Path(plan["out_file"])
size = int(svc.cfg.fusion_chunk_scenarios or 0)
size = size if 0 < size < len(ids) else len(ids)
prog = progress_file(out)
done, dirs = _finished_passes(prog, ids, size)
workers = (plan.get("cred_env") or {}).get("FPT_FUSION_WORKERS")
if done:
svc.db.add_event(plan["run_id"], "executor", "resumed", {"attempt": plan["attempt"], "skipped_chunks": sorted(done),
"message": f"{len(done)} finished pass(es) of this attempt are kept."})
def one(*, ids: list[str], out_file: Path, tag: str, live_meta: dict, **_):
sub = {**plan, "ids": ids, "out_file": str(out_file), "tag": tag, "live_meta": live_meta, "groups": None,
"timeout_s": attempt_timeout_s(svc.cfg, len(ids), workers)}
return run_pass(sub, svc, **extra)
def on_chunk(k: int, f: str, total: int, run_dir: str | None) -> None:
done[k] = f
if run_dir:
dirs[k] = run_dir
tmp = prog.with_name(f".{prog.name}.tmp")
tmp.write_text(json.dumps({"ids": ids, "size": size, "done": done, "dirs": dirs}), encoding="utf-8")
tmp.replace(prog)
if total > 1:
svc.db.add_event(plan["run_id"], "executor", "progress", {"attempt": plan["attempt"], "chunk": k + 1, "of": total})
res = pw.run_attempt_chunked(ids=ids, out_file=out, chunk_size=size, done=done, done_dirs=dirs, on_chunk=on_chunk, run=one,
tag=plan.get("tag") or "", lost_ok=True, single_as_attempt=True)
if res.get("lost_chunks"):
svc.db.add_event(plan["run_id"], "executor", "execution_error", {
"attempt": plan["attempt"], "lost_chunks": res["lost_chunks"], "retrying": False,
"error": f"{len(res['lost_chunks'])} of {res['chunks']} passes ran out of time before they reported; their "
"scenarios are recorded as timed out and tried again in the retry."})
return {**res, "mode": plan["mode"]}
def run_pass(plan: dict, svc, **extra) -> dict:
"""One Playwright invocation: on the remote runner for a Fusion pod when one is set, else on this server."""
remote = (svc.cfg.remote_runner_url or "").strip()
session = assisted_signin.SessionStore(svc).load(plan["run_id"]) if plan.get("assisted") else None
if remote and plan["mode"] == "live" and plan.get("config") == FUSION_CONFIG:
from ...adapters.remote_runner import run_attempt_remote # Oracle's edge refuses this host: the browser runs there
token = svc.vault.get("remote_runner.token") or ""
if token:
svc.redactor.add_secrets([token])
rid, attempt = plan["run_id"], plan["attempt"]
def note(message: str) -> None:
svc.db.add_event(rid, "executor", "runner", {"message": message, "attempt": attempt, "pass": plan.get("tag") or None})
return run_attempt_remote(svc.egress, remote, token, run_id=rid, ids=plan["ids"], attempt=attempt,
out_file=Path(plan["out_file"]), cred_env=plan["cred_env"], drafts_dir=Path(plan["drafts_dir"]),
library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
overrides_file=Path(plan["overrides"]) if plan["overrides"] else None, log_dir=Path(plan["run_dir"]),
config=plan["config"], kill=lambda: _stop_check(svc, rid),
timeout_s=int(plan.get("timeout_s") or 3600), live_meta=plan.get("live_meta"),
busy_wait_s=60 * int(svc.cfg.remote_runner_busy_wait_minutes), on_event=note,
live_dir=Path(plan["live_dir"]) if plan.get("live_dir") else None, tag=plan.get("tag") or "",
storage_state=session)
if plan["mode"] == "live" and not plan.get("config"):
pw.ensure_mock(svc.egress, svc.cfg.pod_base_url, svc.cfg.path("logs"))
if plan.get("config"):
extra.setdefault("config", plan["config"])
if plan.get("tag"):
extra.setdefault("tag", plan["tag"])
if plan.get("timeout_s"):
extra.setdefault("timeout_s", int(plan["timeout_s"]))
if plan.get("live_meta"):
extra.setdefault("live_meta", plan["live_meta"])
if session is not None:
extra.setdefault("storage_state", session)
return pw.run_attempt(run_id=plan["run_id"], ids=plan["ids"], attempt=plan["attempt"], mode=plan["mode"],
out_file=Path(plan["out_file"]), stub_knobs=plan["stub_knobs"], drafts_dir=Path(plan["drafts_dir"]),
library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
overrides_file=Path(plan["overrides"]) if plan["overrides"] else None, cred_env=plan["cred_env"],
backend=svc.cfg.executor_backend, log_dir=Path(plan["run_dir"]),
live_dir=Path(plan["live_dir"]) if plan.get("live_dir") else None, **extra)
def run_groups(plan: dict, svc, **extra) -> dict:
out = Path(plan["out_file"])
used = pw.testdata_used_file(out)
files, dirs, lines, code, timed_out = [], [], [], 0, False
for k, g in enumerate(plan["groups"]):
svc.db.add_event(plan["run_id"], "executor", "progress", {"attempt": plan["attempt"], "user": g["user"], "areas": g["areas"],
"scenarios": len(g["ids"]), "pass": k + 1, "of": len(plan["groups"])})
sub = {**plan, "ids": g["ids"], "cred_env": g["cred_env"], "groups": None, "tag": f"{plan.get('tag') or ''}-u{k}",
"out_file": str(out.with_name(f"{out.stem}.u{k}.json"))}
res = run_planned(sub, svc, **extra) or {}
f = Path(sub["out_file"])
if f.exists():
files.append(f)
dirs += res.get("run_dirs") or ([res["run_dir"]] if res.get("run_dir") else [])
code, timed_out = code or res.get("exit_code") or 0, timed_out or bool(res.get("timed_out"))
if used.exists(): # each pass writes the values it tried to the same file: keep them all for learn_test_data
lines.append(used.read_text(encoding="utf-8"))
used.unlink()
pw.merge_chunk_reports(files, out)
if lines:
used.write_text("".join(x if x.endswith("\n") else x + "\n" for x in lines if x), encoding="utf-8")
return {"file": str(out), "run_dirs": dirs, "run_dir": dirs[-1] if dirs else None, "exit_code": code, "timed_out": timed_out,
"mode": plan["mode"]}
def finish_attempt(state, svc, plan: dict, res: dict | None) -> dict:
"""Merge attempts (Playwright-shaped; failed-then-passed = flaky), ingest evidence, compute failures. Scenarios the
canary blocked (run_canaries) join attempt 0's report as failed with the reason, and are never retried."""
run_id, attempt, out_file = plan["run_id"], plan["attempt"], Path(plan["out_file"])
liveview.cleanup(plan.get("live_dir")) # the latest frame lives only while the attempt runs
run_dirs = list(plan["run_dirs"])
if not plan["ids"]:
out_file.write_text(json.dumps({"config": {"projects": []}, "suites": [], "errors": [], "stats": {},
"_note": "no cases in scope"}), encoding="utf-8")
can = plan.get("canary") or (state.get("run_results") or {}).get("canary") or {}
blocked = can.get("blocked") or {}
if blocked and attempt == 0:
titles = {c["id"]: c.get("title") or "" for c in state.get("test_cases") or []}
extra = canary.blocked_report(blocked, titles, out_file.with_name(f"{out_file.stem}.blocked.json"))
pw.merge_chunk_reports([f for f in (out_file, extra) if f.exists()], out_file)
new_dirs = list((res or {}).get("run_dirs") or ([res["run_dir"]] if res and res.get("run_dir") else []))
run_dirs += new_dirs
if new_dirs: # every Playwright run dir of this attempt (one per chunk under Temporal), each with its own attachments
amap = pw.attachments_by_case(out_file)
for rd in new_dirs:
root = Path(rd).resolve()
sub = {p_: c for p_, c in amap.items() if Path(p_).resolve().is_relative_to(root)}
try:
svc.evidence.ingest_dir(run_id, attempt, Path(rd), sub)
except Exception as e: # noqa: BLE001
svc.audit.append("evidence.error", actor="system", run_id=run_id, summary=str(e)[:300])
files = plan["files"] + [str(out_file)]
if len(files) > 1: # a scenario recorded as timed out (its pass overran) is matched to its retry's result
pw.adopt_no_result(files)
merged = merge_attempts(files, Path(plan["run_dir"]) / "merged-results.json")
outs, counts = outcomes(str(merged))
fails = [f for f in failing_ids(str(out_file)) if f not in blocked] if plan["ids"] else []
if plan["ids"] and plan["mode"] == "live": # healed steps and controls not found (platform/healing.py); never fails the run
healing.after_attempt(svc, run_id, out_file)
return {"attempt_files": files, "failures": fails, "retry_count": attempt,
"run_results": {"merged_path": str(merged), "attempt_files": files, "counts": counts, "outcomes": outs,
"run_dirs": run_dirs, "mode": plan["mode"], **({"canary": can} if can else {})}}
def executor(state, config, svc) -> dict:
plan = plan_attempt(state, svc)
pending = sign_in_resume(state, plan)
if pending: # after a new sign-in: the scenarios the expired session left, in a pass of their own
plan["ids"] = list(pending["ids"])
plan["tag"] = f"-s{int(pending.get('round') or 1)}"
plan["canary"] = saved_canary(plan)
if plan.get("assisted") and plan["ids"] and not assisted_signin.SessionStore(svc).has(plan["run_id"]):
return park_for_sign_in(svc, plan, None, list(plan["ids"]), pending, "no signed-in session is kept for this run")
if not pending:
preflight_or_stop(state, svc, plan)
plan["canary"] = run_canaries(state, svc, plan)
for tries in (1, 2): # a browser-level failure (nothing ran) is tried once more, then fails the run clearly
try:
res = run_planned(plan, svc) if plan["ids"] else None
except BaseException:
liveview.cleanup(plan.get("live_dir")) # a crashed or cancelled attempt leaves no frame behind
raise
pid = svc.fusion_pod_id(plan["run_id"]) if plan["ids"] and plan["mode"] == "live" else None
if pid is not None: # the pod values Fusion accepted in this attempt are tried first next time
from ...platform.pods import PodRegistry
PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).learn_test_data(pid, pw.testdata_used_file(Path(plan["out_file"])))
why = browser_failure(plan["out_file"], res) if plan["ids"] else None
if why is None:
break
svc.db.add_event(plan["run_id"], "executor", "execution_error", {"error": why, "attempt": plan["attempt"], "try": tries,
"retrying": tries == 1})
svc.audit.append("run.execution_error", actor="system", run_id=plan["run_id"], node="executor", summary=why[:300],
payload={"attempt": plan["attempt"], "try": tries, "exit_code": (res or {}).get("exit_code")})
if tries == 2:
liveview.cleanup(plan.get("live_dir"))
from ...platform.failures import ExecutionError
raise ExecutionError(f"The browser test run failed twice before any scenario ran. {why}", exit_code=(res or {}).get("exit_code"),
timed_out=bool((res or {}).get("timed_out")))
Path(plan["out_file"]).unlink(missing_ok=True)
forget_passes(plan["out_file"]) # the retry runs every pass again: none of them recorded anything
if plan.get("assisted") and plan["ids"]:
expired = pw.sign_in_expired_ids(Path(plan["out_file"]))
if expired:
return park_for_sign_in(svc, plan, res, expired, pending, "the pod no longer accepted the signed-in session")
rest_note(svc, plan)
if pending: # what ran before the session expired joins this pass's results: one report for the attempt
out = Path(plan["out_file"])
pw.merge_chunk_reports([Path(p) for p in pending.get("parts") or [] if Path(p).exists()] + [out], out)
new = list((res or {}).get("run_dirs") or ([res["run_dir"]] if res and res.get("run_dir") else []))
res = {**(res or {}), "run_dirs": list(pending.get("run_dirs") or []) + new, "run_dir": None}
return {**finish_attempt(state, svc, plan, res), **({"sign_in_pending": None} if pending else {})}
# ====================================================================== assisted sign-in (platform/assisted_signin.py)
def sign_in_resume(state, plan: dict) -> dict | None:
"""The scenarios an expired session left for after a new sign-in, when this is the attempt they belong to."""
p = state.get("sign_in_pending")
return p if isinstance(p, dict) and p.get("attempt") == plan["attempt"] and p.get("ids") else None
def saved_canary(plan: dict) -> dict:
"""The canary's answer from earlier in this attempt (it is not run again after a new sign-in)."""
try:
info = json.loads((Path(plan["run_dir"]) / "canary.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
return {}
return info if isinstance(info, dict) else {}
def park_for_sign_in(svc, plan: dict, res: dict | None, expired: list[str], pending: dict | None, why: str) -> dict:
"""The run cannot go on with its session (it expired mid-attempt, or there is none): what ran is kept (its report
without the scenarios that met the sign-in page, and its evidence folders), the session is deleted, and the run goes
back to the sign_in gate. After a new sign-in the executor runs only the scenarios listed here."""
run_id, out = plan["run_id"], Path(plan["out_file"])
n = int((pending or {}).get("round") or 0) + 1
parts = [p for p in (pending or {}).get("parts") or [] if Path(p).exists()]
if out.exists():
part = Path(plan["run_dir"]) / f"sign-in-a{plan['attempt']}-p{n}.json" # not attempt-*: a fresh attempt 0 keeps it
pw.drop_cases(out, expired, part)
parts.append(str(part))
out.unlink(missing_ok=True)
forget_passes(out)
new = list((res or {}).get("run_dirs") or ([res["run_dir"]] if res and res.get("run_dir") else []))
dirs = list((pending or {}).get("run_dirs") or []) + new
liveview.cleanup(plan.get("live_dir"))
assisted_signin.SessionStore(svc).delete(run_id)
left = sorted(set(expired))
words = (f"Sign-in expired: {why}. {len(left)} scenario(s) did not run "
f"({', '.join(left[:10])}{', ...' if len(left) > 10 else ''}); the run waits for a person to sign in again, then runs them.")
svc.db.add_event(run_id, "executor", "sign_in_expired", {"message": words, "remaining": len(left), "attempt": plan["attempt"]})
svc.audit.append("sign_in.expired", actor="system", run_id=run_id, node="executor", summary=words[:300],
payload={"attempt": plan["attempt"], "remaining": left, "round": n})
return {"sign_in_pending": {"attempt": plan["attempt"], "ids": left, "parts": parts, "run_dirs": dirs, "round": n}}
def rest_note(svc, plan: dict) -> None:
"""Scenarios whose Fusion REST checks were skipped (an assisted sign-in pod has no password for REST): one line in the
run's timeline. Their screen results stand."""
skipped = pw.annotated(Path(plan["out_file"]), "rest-skipped")
if skipped:
svc.db.add_event(plan["run_id"], "executor", "message", {"message": (
f"Fusion REST checks were skipped in {len(skipped)} scenario(s) ({', '.join(sorted(skipped)[:10])}): this pod uses "
"assisted sign-in, so there is no password for REST. Their screen results stand; test records they created are "
"not cancelled automatically."), "rest_skipped": sorted(skipped)})
def run_canaries(state, svc, plan: dict) -> dict:
"""Attempt 0 of a live run on a Fusion pod: the canary of each of the run's areas (platform/canary.py) runs first, as
its own pass, and a "canary" event records how each business action did. The scenarios that use an action the
canary found broken are taken out of the attempt (finish_attempt reports them as blocked by the canary: a script/UI
change to maintain, not a product defect); the others run as usual. {} when no canary runs: fusion_canary is off,
another attempt or mode, or none of the run's areas has a canary file. A resumed attempt 0 keeps the canary's
earlier answer (canary.json in the run folder) instead of running it again."""
if (plan["attempt"] != 0 or plan["mode"] != "live" or plan.get("config") != FUSION_CONFIG or not plan["ids"]
or not svc.cfg.fusion_canary):
return {}
saved = Path(plan["run_dir"]) / "canary.json"
try:
info = json.loads(saved.read_text(encoding="utf-8"))
except (OSError, ValueError):
info = None
if not isinstance(info, dict):
info = canary_passes(state, svc, plan)
if not info:
return {}
info["learned"] = learn_from_canary(svc, plan)
saved.write_text(json.dumps(info, indent=1), encoding="utf-8")
svc.db.add_event(plan["run_id"], "executor", "canary", {**info, "message": canary_words(info)})
blocked = info.get("blocked") or {}
if blocked:
plan["ids"] = [i for i in plan["ids"] if i not in blocked]
if plan.get("groups"):
groups = [{**g, "ids": [i for i in g["ids"] if i not in blocked]} for g in plan["groups"]]
plan["groups"] = [g for g in groups if g["ids"]] or None
return info
def canary_passes(state, svc, plan: dict) -> dict:
"""Run the canaries of the attempt's areas (one pass per test user when the areas sign in as different users) and
read each business action's result from their reports. A canary that cannot run blocks nothing (error says why)."""
module_of = {c["id"]: c["module"] for c in state.get("test_cases") or []}
areas = list(dict.fromkeys((module_of.get(i) or i.split("-", 1)[0]).upper() for i in plan["ids"]))
ids = [canary.canary_id(a) for a in areas if canary.canary_file(a)]
if not ids:
return {}
passes = [([canary.canary_id(a) for a in g["areas"] if canary.canary_id(a) in ids], g["cred_env"]) for g in plan.get("groups") or []]
files, error = [], None
for k, (cids, env) in enumerate(x for x in (passes or [(ids, plan["cred_env"])]) if x[0]):
out = Path(plan["run_dir"]) / f"canary-{k}.json"
sub = {**plan, "ids": cids, "cred_env": env, "groups": None, "out_file": str(out), "tag": "-canary" if k == 0 else f"-canary{k}",
"timeout_s": attempt_timeout_s(svc.cfg, len(cids), (env or {}).get("FPT_FUSION_WORKERS"))}
try:
run_pass(sub, svc)
except (RunCancelled, KillSwitchEngaged):
raise
except Exception as e: # noqa: BLE001 (the run goes on as it would without a canary)
error = f"{type(e).__name__}: {e}"[:300]
if out.exists():
files.append(out)
results = canary.action_results(files, ids)
failed = canary.failed_actions(results)
from ...platform import step_writer
dirs = [canary.CASES_DIR, ai_scenarios.library_root(svc) / "tests" / "cases", step_writer.staging_dir(svc)]
return {"canaries": ids, "actions": results, "failed_actions": failed,
"blocked": canary.blocked_scenarios(plan["ids"], failed, dirs), "error": error}
def learn_from_canary(svc, plan: dict) -> int:
"""The pod values the canary found working (its create_invoice tries the pod's data sets in turn and records the set
that saves and validates, FPT_TESTDATA_USED) are learned for the pod at once: the next run tries them first, and so
do this run's scenarios (their test data is refreshed). Returns how many values were learned."""
pid = svc.fusion_pod_id(plan["run_id"])
if pid is None:
return 0
from ...platform.pods import PodRegistry
reg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)
n = reg.learn_test_data(pid, pw.testdata_used_file(Path(plan["out_file"])))
if n:
env = reg.executor_env(pid, plan["run_id"]) or {}
fresh = {k: env[k] for k in ("FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES") if k in env}
plan["cred_env"].update(fresh)
for g in plan.get("groups") or []:
g["cred_env"].update(fresh)
return n
def canary_words(info: dict) -> str:
"""The canary event in one sentence for the run's timeline."""
ok = sorted({a for r in (info.get("actions") or {}).values() if r for a, s in r.items() if s == "passed"})
silent = [c for c, r in (info.get("actions") or {}).items() if r is None]
parts = [f"{len(ok)} business action(s) work on the pod"]
if info.get("failed_actions"):
parts.append(f"broken: {', '.join(info['failed_actions'])}; {len(info.get('blocked') or {})} scenario(s) that use them "
"are blocked (a script/UI change to maintain, not a product defect)")
if silent:
parts.append(f"no result from {', '.join(silent)}" + (f" ({info['error']})" if info.get("error") else ""))
if info.get("learned"):
parts.append(f"{info['learned']} pod test data value(s) that work were learned and are tried first")
return "Canary: " + "; ".join(parts) + "."
def preflight_or_stop(state, svc, plan: dict) -> None:
"""The first attempt of a browser run on a Fusion pod checks its runner, sign-in and test data before any browser
starts (platform/preflight.py): a run that cannot work stops in seconds with the reason."""
pid = svc.fusion_pod_id(plan["run_id"]) if plan["ids"] and plan["mode"] == "live" and plan["attempt"] == 0 else None
if pid is None:
return
from ...platform import preflight
ids = set(plan["ids"]) # the areas this attempt runs, not every area the run designed for
areas = sorted({c["module"] for c in state.get("test_cases") or [] if c["id"] in ids})
results = preflight.check(svc, pid, plan["run_id"], areas)
bad = preflight.problems(results)
svc.db.add_event(plan["run_id"], "executor", "preflight", {"ok": not bad, "checks": results})
if bad:
from ...platform.failures import ExecutionError
raise ExecutionError("Pre-flight check failed, no browser was started: " + " ".join(bad))
# ====================================================================== self_heal
def parse_locator(message: str) -> tuple[str, str] | None:
for m in LOCATOR_RE.finditer(message or ""):
kind, a, b = m.groups()
if kind == "Role" and b:
return a, b
if kind == "Label":
return "label", a
return None
def snapshot_candidates(snapshot: str, role: str) -> list[str]:
names = [n for r, n in ARIA_RE.findall(snapshot or "") if role == "label" or r == role]
return list(dict.fromkeys(names))
def stub_self_heal(payload: dict) -> HealProposal:
old, role = payload["old_name"], payload["role"]
cands = [c for c in payload.get("candidates", []) if c != old]
best, ratio = None, 0.0
for c in cands:
r = difflib.SequenceMatcher(None, old.lower(), c.lower()).ratio()
if old.lower() in c.lower() or c.lower() in old.lower():
r = max(r, 0.75)
if r > ratio:
best, ratio = c, r
if best is None or ratio < 0.6:
return HealProposal(role=role, old_name=old, new_name=old, confidence=0.0, reason="no candidate with similarity >= 0.6")
return HealProposal(role=role, old_name=old, new_name=best, confidence=round(ratio, 3), reason=f"difflib ratio {ratio:.2f} (stub)")
STACK_RE = re.compile(r"([A-Za-z]:[\\/][^\s():]+?\.ts|/[^\s():]+?\.ts):(\d+)")
def find_literal(old: str, case_id: str, stack: str = "") -> tuple[str | None, int | None, str | None]:
"""Source literal for the permanent fix: (1) the failing frames in the error stack (automation/ only), then
(2) the case spec, then automation/src/** skipping other modules' packs."""
pat = re.compile(r"(['\"`])" + re.escape(old) + r"\1")
auto = (ROOT / "automation").resolve()
for m in STACK_RE.finditer(stack or ""):
f, ln = Path(m.group(1)), int(m.group(2))
try:
f = f.resolve()
if not f.is_relative_to(auto) or "node_modules" in f.parts or not f.exists():
continue
lines = f.read_text(encoding="utf-8").splitlines()
except (OSError, ValueError):
continue
if 1 <= ln <= len(lines) and pat.search(lines[ln - 1]):
return f.relative_to(ROOT.resolve()).as_posix(), ln, lines[ln - 1].strip()
spec = next((p for p in (ROOT / "automation" / "tests").rglob(f"{case_id}.spec.ts")), None)
mod = case_id.split("-", 1)[0].lower()
src = [p for p in sorted((ROOT / "automation" / "src").rglob("*.ts"))
if "modules" not in p.relative_to(ROOT / "automation" / "src").parts or f"modules/{mod}/" in p.as_posix()]
for f in ([spec] if spec else []) + src:
for i, line in enumerate(f.read_text(encoding="utf-8").splitlines(), 1):
if pat.search(line):
return f.relative_to(ROOT).as_posix(), i, line.strip()
return None, None, None
def self_heal(state, config, svc) -> dict:
run_id = state["run_id"]
a0 = Path(state["attempt_files"][0])
errs = pw.errors_by_case(a0)
ctxs = pw.error_contexts(a0)
stacks = pw.stacks_by_case(a0)
overrides, refs, calls = {}, [], []
for cid in state.get("failures") or []:
msg = errs.get(cid, "")
if not LOCATOR_FAIL_RE.search(msg):
continue
loc = parse_locator(msg)
if not loc:
continue
role, old = loc
snap = ctxs.get(cid)
file, line, src = find_literal(old, cid, stacks.get(cid, ""))
if not snap:
pid = svc.db.insert_once("heal_proposals", {"run_id": run_id, "case_id": cid, "role": role, "old_name": old, "new_name": None,
"confidence": 0.0, "reason": "no error-context ARIA snapshot attached: plain retry",
"file": file, "line": line, "status": "no_snapshot", "created_at": now_iso()}, ('run_id', 'case_id', 'role', 'old_name'))
refs.append({"proposal_id": pid, "case_id": cid, "role": role, "old_name": old, "new_name": "", "confidence": 0.0,
"file": file, "line": line, "applied_in_retry": False})
continue
cands = snapshot_candidates(snap, role)
payload = {"case_id": cid, "role": role, "old_name": old, "error": msg[:1500], "candidates": cands}
req = LLMRequest("self_heal", Sensitivity.CLIENT, payload, HealProposal, "self_heal", run_id, stub_self_heal(payload))
resp = svc.router.call(req)
calls.append(resp.record)
hp = resp.output
usable = hp.new_name != old and hp.new_name in cands and hp.confidence >= 0.6 # type: ignore[attr-defined]
diff = None
if usable and file:
diff = f"--- a/{file}\n+++ b/{file}\n@@ line {line} @@\n-{src}\n+{src.replace(old, hp.new_name)}" # type: ignore[union-attr,attr-defined]
pid = svc.db.insert_once("heal_proposals", {"run_id": run_id, "case_id": cid, "role": role, "old_name": old,
"new_name": hp.new_name if usable else None, "confidence": hp.confidence, # type: ignore[attr-defined]
"reason": hp.reason, "file": file, "line": line, "diff": diff, # type: ignore[attr-defined]
"status": "pending" if usable else "no_candidate", "created_at": now_iso()}, ('run_id', 'case_id', 'role', 'old_name'))
if usable:
overrides[f"{role}|{old}"] = hp.new_name # type: ignore[attr-defined]
refs.append({"proposal_id": pid, "case_id": cid, "role": role, "old_name": old, "new_name": hp.new_name if usable else "", # type: ignore[attr-defined]
"confidence": hp.confidence, "file": file, "line": line, "applied_in_retry": usable}) # type: ignore[attr-defined]
run_dir = svc.run_dir(run_id)
(run_dir / "heal-overrides.json").write_text(json.dumps(overrides), encoding="utf-8")
return {"heal_proposals": refs, "llm_calls": calls}
STUB_TASKS = {"self_heal": stub_self_heal}