Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions packages/flow/benchmark/repair_every_backend/qualify_linux.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,13 @@

from qualify_macos import ( # noqa: E402
APPROVER,
SELF_REPAIR_MODE,
LaterAgent,
_approver,
_approver_roster,
_find_text,
_rows,
_self_repair_legs,
)

APP_SOURCE = FLOW / "tests" / "native_apps" / "chart_gtk.py"
Expand Down Expand Up @@ -149,6 +151,7 @@ def _point(backend: Any, role: str, name: str) -> tuple[int, int]:

def _record(root: Path, db: Path) -> tuple[Path, dict]:
"""Record the healthy workflow on the old version and compile it."""
from openadapt_flow import sealed_set as _sealed
from openadapt_flow.compiler import compile_recording
from openadapt_flow.ir import Workflow
from openadapt_flow.policy import evaluate_policy, load_policy
Expand All @@ -172,7 +175,9 @@ def _record(root: Path, db: Path) -> tuple[Path, dict]:
finally:
app.close()
events_path = recording / "events.jsonl"
events = [json.loads(line) for line in events_path.read_text().splitlines()]
# Encrypted at rest by default (#2423): the recording is a sealed set, so
# read and rewrite its events through the sealed-set API (in memory).
events = [json.loads(line) for line in _sealed.read_text(events_path).splitlines()]
pad = 6
for event in events:
if event.get("kind") == "click":
Expand All @@ -182,7 +187,7 @@ def _record(root: Path, db: Path) -> tuple[Path, dict]:
banner[2] + 2 * pad,
banner[3] + 2 * pad,
]
events_path.write_text("".join(json.dumps(e) + "\n" for e in events))
_sealed.write_text(events_path, "".join(json.dumps(e) + "\n" for e in events))
bundle = root / "bundle"
workflow = compile_recording(recording, bundle, name="chart-note-linux")
save = workflow.steps[-1]
Expand All @@ -200,7 +205,7 @@ def _record(root: Path, db: Path) -> tuple[Path, dict]:
save.risk = "irreversible"
for step in workflow.steps[:-1]:
step.risk = "reversible"
(bundle / "manifest.json").unlink(missing_ok=True)
_sealed.unlink(bundle / "manifest.json", missing_ok=True)
workflow.save(bundle, encrypt=bool(workflow.encrypted))
workflow = Workflow.load(bundle)
report = evaluate_policy(workflow, load_policy("clinical-write"))
Expand Down Expand Up @@ -371,9 +376,10 @@ def qualify(root: Path) -> dict[str, Any]:
clean = _governed(root, bundle, "clean", None)
other = _governed(root, bundle, "other-patient", "other_patient")
look_alike = _governed(root, bundle, "look-alike", "look_alike")
checked = _repair(root, bundle, "repair-with-record-check")
no_verifier = _repair(root, bundle, "repair-no-verifier", verifier=False)
demo = _repair(root, bundle, "repair-demo-profile", profile="demo")
with _self_repair_legs(bundle, root / "repair-bundle") as plain:
checked = _repair(root, plain, "repair-with-record-check")
no_verifier = _repair(root, plain, "repair-no-verifier", verifier=False)
demo = _repair(root, plain, "repair-demo-profile", profile="demo")
checks = {
"demonstration_saved_one_row": _rows(demo_db) == [(PATIENT[0], DEMO_NOTE)],
"bundle_certified": compiled["certified_clinical_write"],
Expand Down Expand Up @@ -420,6 +426,7 @@ def qualify(root: Path) -> dict[str, Any]:
if "repair_every_backend/results/" not in line
],
"compiled": compiled,
"self_repair_mode": SELF_REPAIR_MODE,
"governed_clean": clean,
"governed_other_patient": other,
"governed_look_alike": look_alike,
Expand Down Expand Up @@ -455,6 +462,7 @@ def main() -> int:
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(report, indent=2) + "\n")
print(f"linux atspi: {'PASSED' if report['passed'] else 'FAILED'} -> {out}")
print(f" self-repair legs ran {report['self_repair_mode']}")
for name, ok in report["checks"].items():
print(f" {'ok ' if ok else 'BAD'} {name}")
return 0 if report["passed"] else 1
Expand Down
55 changes: 48 additions & 7 deletions packages/flow/benchmark/repair_every_backend/qualify_macos.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,10 @@
import sys
import tempfile
import time
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
from typing import Any, Iterator, Optional

FLOW = Path(__file__).resolve().parents[2]
if str(FLOW) not in sys.path:
Expand Down Expand Up @@ -188,6 +189,7 @@ def _rows(db: Path) -> list[tuple[str, str]]:

def _record(binary: Path, root: Path, kind: str, db: Path) -> tuple[Path, dict]:
"""Record the healthy workflow on the old version and compile it."""
from openadapt_flow import sealed_set as _sealed
from openadapt_flow.compiler import compile_recording
from openadapt_flow.ir import Workflow
from openadapt_flow.policy import evaluate_policy, load_policy
Expand Down Expand Up @@ -215,7 +217,9 @@ def _record(binary: Path, root: Path, kind: str, db: Path) -> tuple[Path, dict]:
app.close()
# The banner is every click's identity band (``--identifier`` in a browser).
events_path = recording / "events.jsonl"
events = [json.loads(line) for line in events_path.read_text().splitlines()]
# Encrypted at rest by default (#2423): the recording is a sealed set, so
# read and rewrite its events through the sealed-set API (in memory).
events = [json.loads(line) for line in _sealed.read_text(events_path).splitlines()]
pad = 6
for event in events:
if event.get("kind") == "click":
Expand All @@ -225,7 +229,7 @@ def _record(binary: Path, root: Path, kind: str, db: Path) -> tuple[Path, dict]:
banner[2] + 2 * pad,
banner[3] + 2 * pad,
]
events_path.write_text("".join(json.dumps(e) + "\n" for e in events))
_sealed.write_text(events_path, "".join(json.dumps(e) + "\n" for e in events))
bundle = root / "bundle"
workflow = compile_recording(recording, bundle, name=f"chart-note-{kind}")
save = workflow.steps[-1]
Expand All @@ -245,7 +249,7 @@ def _record(binary: Path, root: Path, kind: str, db: Path) -> tuple[Path, dict]:
# ``openadapt-flow qualify set-risk`` records for a person).
for step in workflow.steps[:-1]:
step.risk = "reversible"
(bundle / "manifest.json").unlink(missing_ok=True)
_sealed.unlink(bundle / "manifest.json", missing_ok=True)
workflow.save(bundle, encrypt=bool(workflow.encrypted))
workflow = Workflow.load(bundle)
report = evaluate_policy(workflow, load_policy("clinical-write"))
Expand Down Expand Up @@ -339,6 +343,40 @@ def open_session(fault: Optional[str]) -> Any:
)


#: How the self-repair legs run, recorded in the results and printed. Under
#: the encryption-at-rest default an attended approval (a person's decision,
#: which self-repair's probe and resume need) is refused in a sealed run
#: (#2423), so these legs alone run on a plaintext copy of the bundle under
#: the product's documented opt-out. Record, compile and the governed runs
#: stay under the default.
SELF_REPAIR_MODE = (
"plaintext (known limitation: attended approvals are refused in sealed runs, #2423)"
)


@contextmanager
def _self_repair_legs(bundle: Path, dest: Path) -> Iterator[Path]:
"""A plaintext copy of ``bundle`` at ``dest``, with encryption at rest
off (``at_rest.opted_out``, named on stderr and in the ledger) until the
block ends. The copy is decrypted in memory and saved under the same
content digest, so it is the same program."""
from openadapt_flow import at_rest
from openadapt_flow.ir import Workflow

print(f"self-repair legs: {SELF_REPAIR_MODE}", flush=True)
with at_rest.opted_out("qualification: self-repair legs (#2423 limitation)"):
source = Workflow.load(bundle)
source.save(dest)
copy = Workflow.load(dest)
if (
copy.manifest is None
or source.manifest is None
or (copy.manifest.content_digest != source.manifest.content_digest)
):
raise RuntimeError("the plaintext copy is not the same program")
yield dest


def _repair(
binary: Path,
root: Path,
Expand Down Expand Up @@ -431,9 +469,10 @@ def qualify(kind: str, root: Path) -> dict[str, Any]:
binary = _build(root)
demo_db = root / "sor-demo.db"
bundle, compiled = _record(binary, root / "record", kind, demo_db)
checked = _repair(binary, root, bundle, kind, "with-record-check")
no_verifier = _repair(binary, root, bundle, kind, "no-verifier", verifier=False)
demo = _repair(binary, root, bundle, kind, "demo-profile", profile="demo")
with _self_repair_legs(bundle, root / "repair-bundle") as plain:
checked = _repair(binary, root, plain, kind, "with-record-check")
no_verifier = _repair(binary, root, plain, kind, "no-verifier", verifier=False)
demo = _repair(binary, root, plain, kind, "demo-profile", profile="demo")
expected_basis = "element_and_record_check" if kind == "ax" else "record_check"
checks = {
"demonstration_saved_one_row": _rows(demo_db) == [(PATIENT[0], DEMO_NOTE)],
Expand Down Expand Up @@ -485,6 +524,7 @@ def qualify(kind: str, root: Path) -> dict[str, Any]:
if "repair_every_backend/results/" not in line
],
"compiled": compiled,
"self_repair_mode": SELF_REPAIR_MODE,
"repair_with_record_check": checked,
"repair_without_verifier": no_verifier,
"repair_under_demo_profile": demo,
Expand Down Expand Up @@ -540,6 +580,7 @@ def main() -> int:
out = RESULTS / f"macos-{mode}-{datetime.now(timezone.utc):%Y%m%d}.json"
out.write_text(json.dumps(report, indent=2) + "\n")
print(f"{kind}: {'PASSED' if report['passed'] else 'FAILED'} -> {out}")
print(f" self-repair legs ran {report['self_repair_mode']}")
for name, ok in report["checks"].items():
print(f" {'ok ' if ok else 'BAD'} {name}")
failed |= not report["passed"]
Expand Down
37 changes: 37 additions & 0 deletions packages/flow/openadapt_flow/bundle_persistence.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,43 @@ def prepare_derived_assets(
workflow._pending_derived_assets = dict(candidate._pending_derived_assets)


def copy_bundle_files(
source: Path | str, destination: Path | str, *, ignore: Iterable[str] = ()
) -> None:
"""Copy a bundle's files to a new ``destination``, leaving out any path
with a component matching a pattern in ``ignore`` (as
``shutil.ignore_patterns`` does).

A plaintext source is copied as files. A sealed source becomes a new
sealed set written through its own writer: each file is decrypted in
memory and sealed again, so nothing lands in plaintext. A file-by-file copy
of a sealed set that leaves files out would not match the copied index,
and every reader refuses that.
"""
import fnmatch
import shutil

from openadapt_flow import sealed_set as _sealed

patterns = tuple(ignore)
source, destination = Path(source), Path(destination)
if not _sealed.is_sealed(source):
shutil.copytree(source, destination, ignore=shutil.ignore_patterns(*patterns))
return
reader = _sealed.open_set(source)
passphrase = _sealed.output_bundle_key()
if not passphrase:
raise _sealed.SealedSetKeyError(
_sealed.missing_key_message(destination, "bundle")
)
with _sealed.writing(destination, "bundle", passphrase):
for rel in reader.files():
parts = rel.split("/")
if any(fnmatch.fnmatch(part, pat) for part in parts for pat in patterns):
continue
_sealed.write_bytes(destination / rel, reader.read_bytes(rel))


def copy_genesis_template_inputs(
workflow: Workflow, source: Path | str, destination: Path | str
) -> None:
Expand Down
2 changes: 1 addition & 1 deletion packages/flow/openadapt_flow/compiler/compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -2345,7 +2345,7 @@ def _hover_evidence(
return None # nothing answered the pointer: no evidence to keep
crop_rel = f"{HOVER_CROP_DIR}/{step_id}.png"
(bundle / HOVER_CROP_DIR).mkdir(parents=True, exist_ok=True)
(bundle / crop_rel).write_bytes(response.crop)
_sealed.write_bytes(bundle / crop_rel, response.crop)
return HoverEvidence(
response=True,
region=hover_mod.relative(response.region, click),
Expand Down
13 changes: 10 additions & 3 deletions packages/flow/openadapt_flow/repair/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@
load_detached_candidate,
register_bundle_candidate,
)
from openadapt_flow.runtime.heal import (
has_heal_frame,
heal_frame_path,
read_heal_frame,
)

DEFAULT_STORE = "repair-store"

Expand Down Expand Up @@ -202,8 +207,8 @@ def _campaign_inputs(
step = steps.get(step_id)
if step is None or step.anchor is None:
continue
frame_path = run_dir / "heals" / step_id / "screen.png"
if not frame_path.is_file():
frame_path = heal_frame_path(run_dir, step_id)
if not has_heal_frame(run_dir, step_id):
raise RepairLifecycleError(
f"refused (fail closed): no evidence frame for changed step "
f"{step_id!r} at {frame_path}"
Expand All @@ -214,7 +219,9 @@ def _campaign_inputs(
if template is None:
template_path = bundle / step.anchor.template
template = template_path.read_bytes() if template_path.is_file() else None
inputs.append((step_id, step.anchor, frame_path.read_bytes(), template))
inputs.append(
(step_id, step.anchor, read_heal_frame(run_dir, step_id), template)
)
if not inputs:
raise RepairLifecycleError(
"refused (fail closed): the candidate has no changed anchored "
Expand Down
6 changes: 3 additions & 3 deletions packages/flow/openadapt_flow/repair/relabel.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,9 +315,9 @@ def build(
_uncertify_patch(patched)
if out_dir.exists():
shutil.rmtree(out_dir)
shutil.copytree(
bundle_dir, out_dir, ignore=shutil.ignore_patterns("repair", "manifest.json")
)
from openadapt_flow.bundle_persistence import copy_bundle_files

copy_bundle_files(bundle_dir, out_dir, ignore=("repair", "manifest.json"))
patched.save(out_dir, encrypt=bool(workflow.encrypted), key=key)
return out_dir

Expand Down
Loading
Loading