EnergyVenom commited on
Commit
13b97c6
·
verified ·
1 Parent(s): 26ada29

Astra: each area runs as its own test user (843f85a)

Browse files
coworker/adapters/remote_runner.py CHANGED
@@ -65,7 +65,7 @@ def _absolutize(report: Path, run_dir: Path) -> None:
65
  report.write_text(json.dumps(data), encoding="utf-8")
66
 
67
 
68
- def _unpack(blob: bytes, out_file: Path, run_dir: Path, log_dir: Path, ledger: str, attempt: int) -> bool:
69
  with zipfile.ZipFile(io.BytesIO(blob)) as z:
70
  for info in z.infolist():
71
  name = info.filename
@@ -81,7 +81,11 @@ def _unpack(blob: bytes, out_file: Path, run_dir: Path, log_dir: Path, ledger: s
81
  if dest is None:
82
  continue
83
  dest.parent.mkdir(parents=True, exist_ok=True)
84
- dest.write_bytes(z.read(info))
 
 
 
 
85
  if out_file.exists():
86
  _absolutize(out_file, run_dir)
87
  return True
@@ -186,12 +190,14 @@ def _pull_live(egress, base: str, hdr: dict, jid: str, live_dir: Path, seen: dic
186
  def run_attempt_remote(egress, base_url: str, token: str, *, run_id: str, ids: list[str], attempt: int, out_file: Path,
187
  cred_env: dict | None, drafts_dir: Path | None, library_dir: Path | None, overrides_file: Path | None,
188
  log_dir: Path, config: str, timeout_s: int = 3600, kill=None, poll_s: float = 5.0,
189
- live_dir: Path | None = None, live_meta: dict | None = None) -> dict:
 
 
190
  from ..platform.cleanup import LEDGER
191
  from ..platform.failures import ExecutionError
192
  base = base_url.rstrip("/")
193
  hdr = {"Authorization": f"Bearer {token}"}
194
- pw_run_id = f"fpt-{run_id}-a{attempt}"
195
  env = {k: str(v) for k, v in (cred_env or {}).items() if k in ENV_KEYS}
196
  if overrides_file and Path(overrides_file).exists():
197
  ov = json.loads(Path(overrides_file).read_text(encoding="utf-8") or "{}")
@@ -242,7 +248,7 @@ def run_attempt_remote(egress, base_url: str, token: str, *, run_id: str, ids: l
242
  if z.status_code != 200:
243
  raise RemoteRunnerError(f"the remote browser runner did not return the results (HTTP {z.status_code})")
244
  run_dir = AUTOMATION / "results" / "runs" / pw_run_id
245
- if not _unpack(z.content, Path(out_file), run_dir, Path(log_dir), LEDGER, attempt):
246
  raise ExecutionError(f"The remote browser run produced no report (exit {st.get('exit_code')}), so no scenario result was recorded.",
247
  exit_code=st.get("exit_code"), timed_out=bool(st.get("timed_out")), minutes=max(1, timeout_s // 60))
248
  return {"file": str(out_file), "pw_run_id": pw_run_id, "run_dir": str(run_dir), "exit_code": st.get("exit_code"),
 
65
  report.write_text(json.dumps(data), encoding="utf-8")
66
 
67
 
68
+ def _unpack(blob: bytes, out_file: Path, run_dir: Path, log_dir: Path, ledger: str, attempt: int | str) -> bool:
69
  with zipfile.ZipFile(io.BytesIO(blob)) as z:
70
  for info in z.infolist():
71
  name = info.filename
 
81
  if dest is None:
82
  continue
83
  dest.parent.mkdir(parents=True, exist_ok=True)
84
+ if name == "created.jsonl" and dest.exists(): # records made by an earlier pass stay listed for cleanup
85
+ with dest.open("ab") as fh:
86
+ fh.write(z.read(info))
87
+ else:
88
+ dest.write_bytes(z.read(info))
89
  if out_file.exists():
90
  _absolutize(out_file, run_dir)
91
  return True
 
190
  def run_attempt_remote(egress, base_url: str, token: str, *, run_id: str, ids: list[str], attempt: int, out_file: Path,
191
  cred_env: dict | None, drafts_dir: Path | None, library_dir: Path | None, overrides_file: Path | None,
192
  log_dir: Path, config: str, timeout_s: int = 3600, kill=None, poll_s: float = 5.0,
193
+ live_dir: Path | None = None, live_meta: dict | None = None, tag: str = "") -> dict:
194
+ """One attempt on the remote runner. `tag` names a pass of the attempt (one per test user) so passes keep their own
195
+ run folder and log."""
196
  from ..platform.cleanup import LEDGER
197
  from ..platform.failures import ExecutionError
198
  base = base_url.rstrip("/")
199
  hdr = {"Authorization": f"Bearer {token}"}
200
+ pw_run_id = f"fpt-{run_id}-a{attempt}{tag}"
201
  env = {k: str(v) for k, v in (cred_env or {}).items() if k in ENV_KEYS}
202
  if overrides_file and Path(overrides_file).exists():
203
  ov = json.loads(Path(overrides_file).read_text(encoding="utf-8") or "{}")
 
248
  if z.status_code != 200:
249
  raise RemoteRunnerError(f"the remote browser runner did not return the results (HTTP {z.status_code})")
250
  run_dir = AUTOMATION / "results" / "runs" / pw_run_id
251
+ if not _unpack(z.content, Path(out_file), run_dir, Path(log_dir), LEDGER, f"{attempt}{tag}"):
252
  raise ExecutionError(f"The remote browser run produced no report (exit {st.get('exit_code')}), so no scenario result was recorded.",
253
  exit_code=st.get("exit_code"), timed_out=bool(st.get("timed_out")), minutes=max(1, timeout_s // 60))
254
  return {"file": str(out_file), "pw_run_id": pw_run_id, "run_dir": str(run_dir), "exit_code": st.get("exit_code"),
coworker/graph/nodes/execute.py CHANGED
@@ -90,22 +90,44 @@ def plan_attempt(state, svc, clean: bool = True) -> dict:
90
  cred_env.update(svc.vault.executor_env(m))
91
  live_on, _why = liveview.availability(svc.cfg, mode=mode, wanted=bool(state.get("live_view")), modules=mods)
92
  fusion_pod = svc.fusion_pod_id(run_id)
93
- config = None
94
  if fusion_pod is not None and mode == "live": # a real Fusion pod: its own test set, its test user from the vault
95
  from ...platform.pods import PodRegistry
96
- cred_env.update(PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).executor_env(fusion_pod, run_id) or {})
 
97
  config = "playwright.fusion.config.ts"
 
98
  return {"run_id": run_id, "attempt": attempt, "ids": ids, "mode": mode, "files": files, "run_dir": str(run_dir), "config": config,
99
  "live_dir": str(liveview.live_dir(svc.cfg, run_id)) if live_on and ids else None,
100
  "out_file": str(run_dir / f"attempt-{attempt}.json"), "stub_knobs": state.get("stub_knobs"),
101
  "drafts_dir": str(svc.cfg.path("staging", "specs", run_id)),
102
  "library_dir": str(ai_scenarios.library_root(svc) / "automation" / "tests" / "fusion" / "steps"),
103
- "overrides": str(run_dir / "heal-overrides.json") if attempt == 1 else None, "cred_env": cred_env,
104
  "run_dirs": list((state.get("run_results") or {}).get("run_dirs") or [])}
105
 
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  def run_planned(plan: dict, svc, **extra) -> dict:
108
- """Default runner: one Playwright invocation for the whole attempt (LangGraph path)."""
 
 
 
109
  remote = (svc.cfg.remote_runner_url or "").strip()
110
  if remote and plan["mode"] == "live" and plan.get("config") == "playwright.fusion.config.ts":
111
  from ...adapters.remote_runner import run_attempt_remote # Oracle's edge refuses this host: the browser runs there
@@ -117,11 +139,13 @@ def run_planned(plan: dict, svc, **extra) -> dict:
117
  library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
118
  overrides_file=Path(plan["overrides"]) if plan["overrides"] else None, log_dir=Path(plan["run_dir"]),
119
  config=plan["config"], kill=lambda: svc.kill.check("executor.remote"),
120
- live_dir=Path(plan["live_dir"]) if plan.get("live_dir") else None)
121
  if plan["mode"] == "live" and not plan.get("config"):
122
  pw.ensure_mock(svc.egress, svc.cfg.pod_base_url, svc.cfg.path("logs"))
123
  if plan.get("config"):
124
  extra.setdefault("config", plan["config"])
 
 
125
  return pw.run_attempt(run_id=plan["run_id"], ids=plan["ids"], attempt=plan["attempt"], mode=plan["mode"],
126
  out_file=Path(plan["out_file"]), stub_knobs=plan["stub_knobs"], drafts_dir=Path(plan["drafts_dir"]),
127
  library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
@@ -130,6 +154,31 @@ def run_planned(plan: dict, svc, **extra) -> dict:
130
  live_dir=Path(plan["live_dir"]) if plan.get("live_dir") else None, **extra)
131
 
132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  def finish_attempt(state, svc, plan: dict, res: dict | None) -> dict:
134
  """Merge attempts (Playwright-shaped; failed-then-passed = flaky), ingest evidence, compute failures."""
135
  run_id, attempt, out_file = plan["run_id"], plan["attempt"], Path(plan["out_file"])
 
90
  cred_env.update(svc.vault.executor_env(m))
91
  live_on, _why = liveview.availability(svc.cfg, mode=mode, wanted=bool(state.get("live_view")), modules=mods)
92
  fusion_pod = svc.fusion_pod_id(run_id)
93
+ config, groups = None, None
94
  if fusion_pod is not None and mode == "live": # a real Fusion pod: its own test set, its test user from the vault
95
  from ...platform.pods import PodRegistry
96
+ reg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)
97
+ cred_env.update(reg.executor_env(fusion_pod, run_id) or {})
98
  config = "playwright.fusion.config.ts"
99
+ groups = user_groups(reg, fusion_pod, run_id, ids, {c["id"]: c["module"] for c in state.get("test_cases") or []}, cred_env)
100
  return {"run_id": run_id, "attempt": attempt, "ids": ids, "mode": mode, "files": files, "run_dir": str(run_dir), "config": config,
101
  "live_dir": str(liveview.live_dir(svc.cfg, run_id)) if live_on and ids else None,
102
  "out_file": str(run_dir / f"attempt-{attempt}.json"), "stub_knobs": state.get("stub_knobs"),
103
  "drafts_dir": str(svc.cfg.path("staging", "specs", run_id)),
104
  "library_dir": str(ai_scenarios.library_root(svc) / "automation" / "tests" / "fusion" / "steps"),
105
+ "overrides": str(run_dir / "heal-overrides.json") if attempt == 1 else None, "cred_env": cred_env, "groups": groups,
106
  "run_dirs": list((state.get("run_results") or {}).get("run_dirs") or [])}
107
 
108
 
109
+ def user_groups(reg, pod_id: int, run_id: str, ids: list[str], module_of: dict[str, str], base_env: dict) -> list[dict] | None:
110
+ """Each area's scenarios signed in as that area's test user (FPT_FUSION_AREA_USERS): one Playwright pass per user,
111
+ in the order the areas come. None when every scenario uses the same user (one pass, as before)."""
112
+ envs: dict[str, dict] = {}
113
+ groups: dict[str, dict] = {}
114
+ for cid in ids:
115
+ area = (module_of.get(cid) or cid.split("-", 1)[0]).upper()
116
+ if area not in envs:
117
+ envs[area] = reg.executor_env(pod_id, run_id, area=area) or {}
118
+ user = envs[area].get("FUSION_USERNAME") or ""
119
+ g = groups.setdefault(user, {"user": user, "areas": [], "ids": [], "cred_env": {**base_env, **envs[area]}})
120
+ if area not in g["areas"]:
121
+ g["areas"].append(area)
122
+ g["ids"].append(cid)
123
+ return list(groups.values()) if len(groups) > 1 else None
124
+
125
+
126
  def run_planned(plan: dict, svc, **extra) -> dict:
127
+ """Default runner: one Playwright invocation for the whole attempt (LangGraph path); one per test user when the
128
+ areas sign in as different users (plan["groups"]), merged into the attempt's one report."""
129
+ if plan.get("groups"):
130
+ return run_groups(plan, svc, **extra)
131
  remote = (svc.cfg.remote_runner_url or "").strip()
132
  if remote and plan["mode"] == "live" and plan.get("config") == "playwright.fusion.config.ts":
133
  from ...adapters.remote_runner import run_attempt_remote # Oracle's edge refuses this host: the browser runs there
 
139
  library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
140
  overrides_file=Path(plan["overrides"]) if plan["overrides"] else None, log_dir=Path(plan["run_dir"]),
141
  config=plan["config"], kill=lambda: svc.kill.check("executor.remote"),
142
+ live_dir=Path(plan["live_dir"]) if plan.get("live_dir") else None, tag=plan.get("tag") or "")
143
  if plan["mode"] == "live" and not plan.get("config"):
144
  pw.ensure_mock(svc.egress, svc.cfg.pod_base_url, svc.cfg.path("logs"))
145
  if plan.get("config"):
146
  extra.setdefault("config", plan["config"])
147
+ if plan.get("tag"):
148
+ extra.setdefault("tag", plan["tag"])
149
  return pw.run_attempt(run_id=plan["run_id"], ids=plan["ids"], attempt=plan["attempt"], mode=plan["mode"],
150
  out_file=Path(plan["out_file"]), stub_knobs=plan["stub_knobs"], drafts_dir=Path(plan["drafts_dir"]),
151
  library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
 
154
  live_dir=Path(plan["live_dir"]) if plan.get("live_dir") else None, **extra)
155
 
156
 
157
+ def run_groups(plan: dict, svc, **extra) -> dict:
158
+ out = Path(plan["out_file"])
159
+ used = pw.testdata_used_file(out)
160
+ files, dirs, lines, code, timed_out = [], [], [], 0, False
161
+ for k, g in enumerate(plan["groups"]):
162
+ svc.db.add_event(plan["run_id"], "executor", "progress", {"attempt": plan["attempt"], "user": g["user"], "areas": g["areas"],
163
+ "scenarios": len(g["ids"]), "pass": k + 1, "of": len(plan["groups"])})
164
+ sub = {**plan, "ids": g["ids"], "cred_env": g["cred_env"], "groups": None, "tag": f"-u{k}",
165
+ "out_file": str(out.with_name(f"{out.stem}.u{k}.json"))}
166
+ res = run_planned(sub, svc, **extra) or {}
167
+ f = Path(sub["out_file"])
168
+ if f.exists():
169
+ files.append(f)
170
+ dirs += res.get("run_dirs") or ([res["run_dir"]] if res.get("run_dir") else [])
171
+ code, timed_out = code or res.get("exit_code") or 0, timed_out or bool(res.get("timed_out"))
172
+ if used.exists(): # each pass writes the values it tried to the same file: keep them all for learn_test_data
173
+ lines.append(used.read_text(encoding="utf-8"))
174
+ used.unlink()
175
+ pw.merge_chunk_reports(files, out)
176
+ if lines:
177
+ used.write_text("".join(x if x.endswith("\n") else x + "\n" for x in lines if x), encoding="utf-8")
178
+ return {"file": str(out), "run_dirs": dirs, "run_dir": dirs[-1] if dirs else None, "exit_code": code, "timed_out": timed_out,
179
+ "mode": plan["mode"]}
180
+
181
+
182
  def finish_attempt(state, svc, plan: dict, res: dict | None) -> dict:
183
  """Merge attempts (Playwright-shaped; failed-then-passed = flaky), ingest evidence, compute failures."""
184
  run_id, attempt, out_file = plan["run_id"], plan["attempt"], Path(plan["out_file"])
coworker/tests/test_area_user_passes.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Each area's scenarios run signed in as that area's test user (FPT_FUSION_AREA_USERS): one Playwright pass per user,
2
+ merged into the attempt's one report; the values Fusion accepted and the records made in every pass are all kept."""
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import json
7
+ import tempfile
8
+ import unittest
9
+ import zipfile
10
+ from pathlib import Path
11
+ from types import SimpleNamespace
12
+ from unittest import mock
13
+
14
+ from coworker.adapters import remote_runner
15
+ from coworker.graph.nodes import execute
16
+
17
+ USERS = {"CM": "fin_impl", "PO": "casey.brown", "INV": "scm_impl", "PPM": "casey.brown"}
18
+
19
+
20
+ class Reg:
21
+ def executor_env(self, pod_id, run_id=None, area=None):
22
+ return {"FUSION_USERNAME": USERS.get(area, "fin_impl"), "FUSION_PASSWORD": "x"}
23
+
24
+
25
+ class TestAreaUserPasses(unittest.TestCase):
26
+ def test_scenarios_are_grouped_by_their_areas_user(self):
27
+ mods = {"CM-FUS-1": "CM", "PO-FUS-1": "PO", "PPM-FUS-1": "PPM", "CM-FUS-2": "CM"}
28
+ g = execute.user_groups(Reg(), 1, "r", list(mods) + ["INV-SMOKE-1"], mods, {"FUSION_BASE_URL": "https://pod"})
29
+ self.assertEqual([(x["user"], x["areas"], x["ids"]) for x in g],
30
+ [("fin_impl", ["CM"], ["CM-FUS-1", "CM-FUS-2"]), ("casey.brown", ["PO", "PPM"], ["PO-FUS-1", "PPM-FUS-1"]),
31
+ ("scm_impl", ["INV"], ["INV-SMOKE-1"])])
32
+ self.assertEqual(g[1]["cred_env"]["FUSION_BASE_URL"], "https://pod")
33
+ self.assertIsNone(execute.user_groups(Reg(), 1, "r", ["CM-FUS-1", "CM-FUS-2"], {}, {})) # one user: one pass, as before
34
+
35
+ def test_one_pass_per_user_merged_into_one_report(self):
36
+ with tempfile.TemporaryDirectory() as tmp:
37
+ out = Path(tmp) / "attempt-0.json"
38
+ calls = []
39
+
40
+ def fake_run(**kw):
41
+ calls.append((kw["cred_env"]["FUSION_USERNAME"], kw["ids"], kw.get("tag")))
42
+ Path(kw["out_file"]).write_text(json.dumps({"suites": [{"title": i} for i in kw["ids"]], "errors": []}), encoding="utf-8")
43
+ execute.pw.testdata_used_file(kw["out_file"]).write_text(json.dumps({"user": kw["cred_env"]["FUSION_USERNAME"]}) + "\n")
44
+ return {"run_dir": f"{tmp}/run{kw.get('tag')}", "exit_code": 0}
45
+
46
+ mods = {"CM-FUS-1": "CM", "PO-FUS-1": "PO"}
47
+ plan = {"run_id": "r", "attempt": 0, "ids": list(mods), "mode": "live", "out_file": str(out), "stub_knobs": None,
48
+ "drafts_dir": tmp, "library_dir": None, "overrides": None, "run_dir": tmp, "live_dir": None,
49
+ "config": "playwright.fusion.config.ts", "cred_env": {},
50
+ "groups": execute.user_groups(Reg(), 1, "r", list(mods), mods, {})}
51
+ events = []
52
+ svc = SimpleNamespace(cfg=SimpleNamespace(remote_runner_url="", executor_backend="local"),
53
+ db=SimpleNamespace(add_event=lambda *a: events.append(a[3])))
54
+ with mock.patch.object(execute.pw, "run_attempt", side_effect=fake_run):
55
+ res = execute.run_planned(plan, svc)
56
+ self.assertEqual(calls, [("fin_impl", ["CM-FUS-1"], "-u0"), ("casey.brown", ["PO-FUS-1"], "-u1")])
57
+ self.assertEqual([s["title"] for s in json.loads(out.read_text())["suites"]], ["CM-FUS-1", "PO-FUS-1"])
58
+ self.assertEqual(len(res["run_dirs"]), 2)
59
+ used = execute.pw.testdata_used_file(out).read_text().splitlines()
60
+ self.assertEqual([json.loads(x)["user"] for x in used], ["fin_impl", "casey.brown"])
61
+ self.assertEqual([(e["user"], e["pass"], e["of"]) for e in events], [("fin_impl", 1, 2), ("casey.brown", 2, 2)])
62
+
63
+ def test_a_later_pass_keeps_the_records_an_earlier_one_made(self):
64
+ def bundle(line: str) -> bytes:
65
+ b = io.BytesIO()
66
+ with zipfile.ZipFile(b, "w") as z:
67
+ z.writestr("report.json", json.dumps({"suites": []}))
68
+ z.writestr("created.jsonl", line)
69
+ return b.getvalue()
70
+
71
+ with tempfile.TemporaryDirectory() as tmp:
72
+ t = Path(tmp)
73
+ for k, line in enumerate(('{"id": 1}\n', '{"id": 2}\n')):
74
+ self.assertTrue(remote_runner._unpack(bundle(line), t / f"a.u{k}.json", t / "run", t, "ledger.jsonl", f"0-u{k}"))
75
+ self.assertEqual((t / "ledger.jsonl").read_text().splitlines(), ['{"id": 1}', '{"id": 2}'])
76
+
77
+
78
+ if __name__ == "__main__":
79
+ unittest.main()