From 98755d1dccb5731c7f1256a82033acf37d16b2a0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 16:13:27 -0500 Subject: [PATCH 1/4] feat(quickstart): replace act 3 with a crash and restart of a batch Act 3 on MockMed no longer makes a save fail silently. It runs a batch of two notes in a worker process, stops it with SIGKILL after note 1 is saved and checked, and restarts the batch with the same on-disk IdempotencyLedger. The replayer sends no save for note 1 and saves note 2; each note's database is read afterwards. --no-restart replaces --no-break (kept hidden). OpenEMR's Act 3 is unchanged. --- README.md | 4 +- ...a-crash-and-a-restart-in-the-quickstart.md | 1 + docs/cli.md | 17 +- docs/getting-started/quickstart.md | 13 +- docs/quickstart/README.md | 37 +- openadapt/cli.py | 38 +- openadapt/quickstart/__init__.py | 14 +- openadapt/quickstart/engine.py | 259 ++------- openadapt/quickstart/openemr.py | 2 +- openadapt/quickstart/restart.py | 491 ++++++++++++++++++ openadapt/quickstart/restart_view.py | 134 +++++ openadapt/quickstart/scene.py | 192 +++---- openadapt/quickstart/story.py | 151 +++--- openadapt/quickstart/view.py | 133 +++-- packages/agent/README.md | 2 +- scripts/capture_quickstart_pty.py | 2 +- scripts/record_quickstart.py | 2 +- tests/fixtures/cli_surface.json | 2 +- .../quickstart_openemr_plain.snapshot | 6 +- tests/snapshots/quickstart_plain.snapshot | 25 +- tests/test_cli_quickstart_polish.py | 7 +- tests/test_quickstart.py | 374 ++++++++----- tests/test_quickstart_command.py | 6 +- tests/test_quickstart_openemr.py | 4 +- tests/test_quickstart_restart.py | 164 ++++++ tests/test_quickstart_robust.py | 22 +- tests/test_seal_publish.py | 14 +- 27 files changed, 1439 insertions(+), 677 deletions(-) create mode 100644 capabilities/04-the-core-a-checked-entry-every-time/0035-see-a-crash-and-a-restart-in-the-quickstart.md create mode 100644 openadapt/quickstart/restart.py create mode 100644 openadapt/quickstart/restart_view.py create mode 100644 tests/test_quickstart_restart.py diff --git a/README.md b/README.md index 5c30f58ee7..eb74cd4f08 100644 --- a/README.md +++ b/README.md @@ -52,10 +52,10 @@ print(safe_save.last_receipt["outcome"], safe_save.last_receipt["checked_how"]) ### Try It in 30 Seconds -Run the local smoke test against a bundled demo server (no account or API key required), or trigger a deliberate drift to inspect a halted run and its signed receipt: +Run the quickstart against a bundled demo app (no account or API key required). It shows a task once, runs the compiled program and checks the save in the app's database, then stops the runner partway through a batch and restarts it: the restart skips the note that was already saved and saves only the next one. ```bash -uvx --python 3.12 openadapt@latest quickstart --break-it +uvx --python 3.12 openadapt@latest quickstart ``` ### Wrap an Agent or Serve Compiled Workflows over MCP diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0035-see-a-crash-and-a-restart-in-the-quickstart.md b/capabilities/04-the-core-a-checked-entry-every-time/0035-see-a-crash-and-a-restart-in-the-quickstart.md new file mode 100644 index 0000000000..5b7b26c160 --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0035-see-a-crash-and-a-restart-in-the-quickstart.md @@ -0,0 +1 @@ +| See a crash and a restart in the quickstart: on MockMed, Act 3 runs a batch of two new notes in a separate worker process, stops it with SIGKILL after note 1's save is checked, and restarts the batch with the same on-disk write ledger (`IdempotencyLedger`); the replayer finds note 1's key and sends no save for it (its report: idempotent replay, 0 actions), then saves note 2; each note's database is read afterwards. Each note has its own copy of the clinic's database, as in Act 2 | On main | Synthetic (MockMed; real headless runs on macOS, unit tests with fakes) | `openadapt quickstart`; [restart.py](openadapt/quickstart/restart.py) | diff --git a/docs/cli.md b/docs/cli.md index 1802bc0f84..338c364710 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -17,7 +17,7 @@ installed `openadapt-flow` engine. Run ` --help` to see its arguments or related operations. For example: ```bash -openadapt quickstart --break-it +openadapt quickstart openadapt verify effect --help openadapt inspect lint bundle openadapt run --replay bundle --run-dir run @@ -57,13 +57,14 @@ uv fetches Python 3.12 for the run. With `openadapt` installed, run `openadapt demo tutorial` is the command that writes a `VERIFIED` receipt. It runs the bundled synthetic MockMed workflow from recording through an -independently verified Standard-profile result. `openadapt quickstart --break-it` -(also `openadapt demo quickstart --break-it`; with uv, `uvx --python 3.12 -openadapt@latest quickstart --break-it`) is the halt demo. It reruns the same certified bundle against a backend that -rejects the write after the app shows success. The independent read finds no -saved record, and the run halts with transaction outcome -`RECONCILIATION_REQUIRED`, so nothing is retried until a person checks the -record. +independently verified Standard-profile result. `openadapt quickstart` +(also `openadapt demo quickstart`; with uv, `uvx --python 3.12 +openadapt@latest quickstart`) runs the same tutorial program, then a batch of +two notes in a separate worker process. It stops that process with SIGKILL +after note 1 is saved and checked, and restarts the batch with the same write +ledger on disk. The restart finds note 1 in the ledger, sends no save for it, +and saves note 2. The quickstart then reads each note's database and shows the +note there once. The engine runs on Python 3.11 and 3.12. On Python 3.13 or newer, pip installs only the launcher and every engine command prints the fix: diff --git a/docs/getting-started/quickstart.md b/docs/getting-started/quickstart.md index fbfdd38f23..838f53473d 100644 --- a/docs/getting-started/quickstart.md +++ b/docs/getting-started/quickstart.md @@ -31,14 +31,17 @@ openadapt flow visualize /bundle --out graph.html openadapt flow lint /bundle ``` -Run the same certified bundle against a fault-injecting backend: +See what a crash does to a batch: ```bash -openadapt quickstart --break-it --out openadapt-quickstart-broken +openadapt quickstart --out openadapt-quickstart-restart ``` -The application displays success, but the backend does not save the record. -The independent effect verifier detects the mismatch and returns `HALTED`. +After the tutorial run, the quickstart starts a batch of two notes in a +separate worker process and stops that process with SIGKILL after note 1 is +saved and checked. It restarts the batch with the same write ledger on disk. +The restart finds note 1 in the ledger and sends no save for it, then saves +note 2. Each note is in its database once. ## Run the manual demo lifecycle @@ -58,7 +61,7 @@ an unarmed irreversible click. The permissive certification is only a smoke gate. The Demo replay returns `COMPLETED_UNVERIFIED`, not `VERIFIED`. Use `openadapt flow tutorial` for the effect-verified first run. -`openadapt quickstart --break-it` is the halt demo. For a real workflow, add +`openadapt quickstart` shows the crash and restart. For a real workflow, add the application boundary, action risks, identity requirements, effect verifier, fault cases, and deployment policy before production use. diff --git a/docs/quickstart/README.md b/docs/quickstart/README.md index d6ed5501b3..735899145a 100644 --- a/docs/quickstart/README.md +++ b/docs/quickstart/README.md @@ -11,11 +11,36 @@ Re-record with `python scripts/record_quickstart.py --out docs/quickstart/story`. `quickstart.gif` predates the five-step story and needs a fresh `vhs` take. -- `inline-screenshot.png`: the third act on a terminal that draws images - (WezTerm), with the halted run's screenshot beside the database's answer. +- `inline-screenshot.png`: an earlier third act, which MockMed no longer + runs, on a terminal that draws images (WezTerm). - `timing-2026-10-20.json`: the engine tutorial with `--break-it` (what - `openadapt quickstart --break-it` ran before) against the new quickstart, - three rounds each, interleaved, from `scripts/quickstart_timing.py`. + the quickstart ran before) against the new quickstart, three rounds each, + interleaved, from `scripts/quickstart_timing.py`. + +## The three acts on MockMed + +```bash +uvx --python 3.12 openadapt@latest quickstart +``` + +- **Act 1, show it once.** A demonstration in MockMed, a synthetic clinic + app, compiled into a program. +- **Act 2, run it.** The program on a new note, checked in the app's + database. +- **Act 3, stop it mid-batch, then restart.** A batch of two new notes runs + in a separate worker process. Each note's run reserves its key in the + engine's write ledger (`IdempotencyLedger`, in `restart/ledger/` under the + output folder) before its first action and records the outcome after the + record check. When note 1 is saved and checked, the quickstart stops the + worker with SIGKILL, before note 2 starts. It then runs the batch again in + its own process with the same ledger: the replayer finds note 1's key and + sends no save for it (its report shows an idempotent replay with 0 + actions), and note 2 runs and saves. Last, it reads each note's database + and counts the note there. That count alone would not catch a resend: + MockMed's demo save carries a fixed key the app de-duplicates on. The + evidence that no second save was sent is note 1's restart report. Each note has its own copy of the + clinic's database, as in Act 2, because the tutorial program writes one + record per patient. `--no-restart` skips this act. ## On a real app: `--app openemr` @@ -25,7 +50,7 @@ openadapt quickstart --app openemr The same three acts on OpenEMR 8.0.0.3, a real open-source EHR, instead of the bundled MockMed. The default stays MockMed: it needs no Docker and finishes in -about 22 seconds. +about 30 seconds. - **Needs** Docker (Docker Desktop, or Podman with `DOCKER_HOST` pointed at its socket) and a clone of this repository, because the OpenEMR fixture is @@ -57,7 +82,7 @@ about 22 seconds. account and browser. Each runs through the certified run path (the Standard run gate, then the REST record check) and is read back from OpenEMR's database with SQL: "✓ checked in OpenEMR's record". -- **Act 3, break it.** The quickstart adds an existing chart (Rosa Delgado, +- **Act 3, a referral that matches a chart.** The quickstart adds an existing chart (Rosa Delgado, born 1958-03-27), then runs a referral for a Rosa Delgado born 1958-03-22. OpenEMR's duplicate check lists the match, and the program stops before saving ("Stopped before saving: possible duplicate"). SQL finds 0 new charts. diff --git a/openadapt/cli.py b/openadapt/cli.py index 714ddf8072..d2ac105003 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -693,6 +693,7 @@ def _is_externally_managed_error(error: BaseException) -> bool: "--watch", "--open", "--headless", + "--no-restart", "--no-break", "--verbose", "--headed", @@ -823,7 +824,7 @@ def ask(prompt: str) -> str: default="mockmed", show_default=True, help=( - "The app to run it in. mockmed is bundled (about 22 seconds, no Docker). " + "The app to run it in. mockmed is bundled (about 30 seconds, no Docker). " "openemr runs OpenEMR 8.0.0.3 in Docker from a clone of the repository; " "the first run downloads and installs it, later runs reuse it." ), @@ -846,11 +847,16 @@ def ask(prompt: str) -> str: ), ) @click.option( - "--no-break", - "no_break", + "--no-restart", + "no_restart", is_flag=True, - help="Skip the last part, where one save fails silently.", + help=( + "Skip the last part, where the runner is stopped partway through a " + "batch and restarted." + ), ) +# The old name of --no-restart, kept so existing scripts still work. +@click.option("--no-break", "no_break", is_flag=True, hidden=True) @click.option( "--verbose", is_flag=True, @@ -963,6 +969,7 @@ def quickstart( app: str, watch: bool, open_seal: bool, + no_restart: bool, no_break: bool, verbose: bool, more: bool, @@ -982,13 +989,15 @@ def quickstart( headless: bool, break_it: bool, ) -> None: - """Show a task once, run it, then watch it catch a save that didn't happen. + """Show a task once, run it, then stop it mid-batch and restart it. - About 25 seconds, in a synthetic clinic app on this computer. OpenAdapt + About 30 seconds, in a synthetic clinic app on this computer. OpenAdapt turns one demonstration into a program, runs it on a new note and checks - the save in the app's database, then makes one save fail silently: the - screen says saved, the database has nothing, and OpenAdapt stops. The - program makes no AI calls. Nothing in the output directory is overwritten. + the save in the app's database. Then it starts a batch of two notes, + stops the runner process hard after note 1 saves, and starts it again: + the restart reads the write ledger on disk, skips note 1, and saves only + note 2. The program makes no AI calls. Nothing in the output directory is + overwritten. With --app openemr, the same three acts run on OpenEMR 8.0.0.3 in Docker, with the certified referral program: referrals registered at once and @@ -1092,7 +1101,7 @@ def quickstart( outcome = run_quickstart( root, visible=visible, - break_it=not no_break, + last_act=not (no_restart or no_break), verbose=verbose, steps=steps, interactive=False if yes else None, @@ -1115,8 +1124,13 @@ def quickstart( f"The quickstart stopped: {error}\nAnything it wrote is in {root}" ) from error raise - if outcome.checked != len(outcome.runs) or ( - outcome.broken is not None and not outcome.broken.stopped + restart = outcome.restart + if ( + outcome.checked != len(outcome.runs) + or (outcome.broken is not None and not outcome.broken.stopped) + # A restart that ran and went another way; one that couldn't start + # (no second process) was skipped, not failed. + or (restart is not None and not restart.error and not restart.held) ): raise click.exceptions.Exit(1) diff --git a/openadapt/quickstart/__init__.py b/openadapt/quickstart/__init__.py index dba73c039f..ff44e9c6ec 100644 --- a/openadapt/quickstart/__init__.py +++ b/openadapt/quickstart/__init__.py @@ -1,10 +1,10 @@ -"""``openadapt quickstart``: show a task once, run it, break it. +"""``openadapt quickstart``: show a task once, run it, stop and restart it. The first command anyone runs. It demonstrates one task in a synthetic clinic app (MockMed), compiles it into a program, runs the program on a new note and -checks the save in the app's database, then makes one save fail -silently: the screen says saved, the database has nothing, and -OpenAdapt stops instead of reporting success. +checks the save in the app's database. Then it starts a batch of two notes, +stops the runner process hard after note 1 saves, and restarts it: the +restart reads the write ledger on disk, skips note 1, and saves only note 2. """ from __future__ import annotations @@ -41,7 +41,7 @@ def next_steps( check (run once, at the finale) for an older ``openadapt`` on PATH. ``offer_publish`` is given only in a terminal outside CI, with an engine that can build public Seals. At the finale it asks once whether to put - the checked and stopped runs' Seals online. The offer appears only + the checked run's Seal online. The offer appears only when Cloud accepts hosted Seals. """ @@ -72,7 +72,7 @@ def run_quickstart( root: Path, *, visible: bool, - break_it: bool, + last_act: bool, verbose: bool, steps: Callable[[Outcome], NextSteps], stream: Optional[IO[str]] = None, @@ -115,7 +115,7 @@ def run_quickstart( engine, view, next_steps=steps, - break_it=break_it, + last_act=last_act, interactive=interactive, verbose=verbose, # Only on request (--open), and only when this output is the diff --git a/openadapt/quickstart/engine.py b/openadapt/quickstart/engine.py index 2bcb9cb0b4..afda903c96 100644 --- a/openadapt/quickstart/engine.py +++ b/openadapt/quickstart/engine.py @@ -3,8 +3,8 @@ Every number the quickstart prints comes from here, and everything here comes from the engine's own artifacts: the recorder's ``events.jsonl``, the compiled workflow, each run's report, the demo app's database (read out of band, at a -path the app never calls), and the halted run's screenshot. Nothing is -scripted output. +path the app never calls), and Act 3's write ledger. Nothing is scripted +output. The stages are the tutorial's own (:mod:`openadapt_flow.tutorial`): record against MockMed's database-backed server, compile with mined record checks, @@ -12,6 +12,7 @@ the unchanged fail-closed run gate. The quickstart adds two things: the program runs on a new note (the demonstration typed another), and the record checks read that run's note (``bind_effect_params``) so a new note can be checked. +Act 3 (stop the runner mid-batch, restart it) is :mod:`openadapt.quickstart.restart`. """ from __future__ import annotations @@ -23,10 +24,13 @@ import time from dataclasses import dataclass, field from pathlib import Path -from typing import Any, Callable, Optional, Sequence +from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence from openadapt.quickstart.scene import MOCKMED +if TYPE_CHECKING: + from openadapt.quickstart.restart import RestartFacts + #: Synthetic notes for the five runs. None of them is clinical advice. RUN_NOTES = ( "Follow-up in two weeks", @@ -36,10 +40,6 @@ "No change to the care plan", ) -#: The part of the 1280x800 screenshot that holds the patient banner and the -#: saved message (the same crop the side-by-side page shows). -SCREEN_CROP = (0, 0, 640, 320) - #: How often the step ticker reads the recorder's event log, in seconds. _TICK_S = 0.05 @@ -126,7 +126,7 @@ def not_ready_explanation(visible: bool) -> str: @dataclass class BreakFacts: - """The rerun against a database that rejects the write.""" + """OpenEMR's Act 3: the run on a referral that matches an existing chart.""" run_dir: Path fault: str @@ -173,12 +173,10 @@ class SealFacts: @dataclass class SealPages: - """The offline Seal pages the finale wrote (``seal.html`` in a run folder).""" + """The offline Seal page the finale wrote (``seal.html`` in a run folder).""" #: The first checked run's page: the one the finale opens. verified: Optional[Path] = None - #: The stopped run's page, when Act 3 ran. - broken: Optional[Path] = None def demo_step_label(event: dict[str, Any]) -> Optional[str]: @@ -270,27 +268,6 @@ def _effect_counts(report: Any) -> tuple[int, int]: ) -def read_screen_text(screenshot: Path) -> Optional[str]: - """Read the saved message off the halted run's screenshot. - - The engine's halt record keeps the on-screen text as its OCR read it at - screen scale, which can run words together. Reading the same pixels at - twice the scale gives the words back. Returns the line that says - "saved", or None when no line does. - """ - - from openadapt_flow.vision.ocr import ocr, upscale_png - - from openadapt.quickstart.images import crop_png - - try: - png = upscale_png(crop_png(screenshot, SCREEN_CROP), 2) - lines = [str(line.text).strip() for line in ocr(png)] - except Exception: # noqa: BLE001 - the screenshot itself still shows it - return None - return next((line for line in lines if "saved" in line.lower()), None) - - def run_program( *, base_url: str, @@ -375,52 +352,6 @@ def run_program( return facts -class EarlyScreenRead: - """Read a screenshot on a thread as soon as it appears on disk. - - :meth:`text_for` returns the text only for the same file with the same - bytes as were read; anything else is read again by the caller. - """ - - def __init__(self, path: Path) -> None: - self._path = path - self._stop = threading.Event() - self._digest: Optional[str] = None - self._text: Optional[str] = None - self._thread = threading.Thread(target=self._loop, name="quickstart-screen") - self._thread.daemon = True - self._thread.start() - - def _loop(self) -> None: - while not self._stop.wait(_TICK_S): - if _artifact_is_file(self._path): - time.sleep(_TICK_S) # let the writer finish the file - digest = _sha256(self._path) - self._text = read_screen_text(self._path) - self._digest = digest - return - - def stop(self) -> None: - self._stop.set() - - def text_for(self, path: Path) -> Optional[str]: - self._thread.join(timeout=10) - if self._digest is None or Path(path).resolve() != self._path.resolve(): - return None - return self._text if _sha256(Path(path)) == self._digest else None - - -def _sha256(path: Path) -> Optional[str]: - import hashlib - - from openadapt_flow import sealed_set - - try: - return hashlib.sha256(sealed_set.read_bytes(path)).hexdigest() - except (OSError, sealed_set.SealedSetError): - return None - - def _artifact_is_file(path: Path) -> bool: """Whether a run file exists, encrypted or not.""" from openadapt_flow import sealed_set @@ -451,6 +382,7 @@ def __init__(self, root: Path, *, visible: bool, pace_s: float = 0.0) -> None: self._base_url: Optional[str] = None self._pool: Any = None self._starter: Any = None + self._restart_worker: Any = None self._progress: Callable[[str, bool], None] = lambda _text, _milestone: None # -- lifetime --------------------------------------------------------- @@ -672,91 +604,44 @@ def before_prompt(self) -> None: return_focus_to_terminal(visible=self.visible) - def break_it(self) -> BreakFacts: - """Rerun the same program while the database rejects the save. - - A run that never got a ready screen (it stopped before its first - action and wrote nothing) runs once more in ``run-broken-retry``. - """ - - broken = self._break_once(self.root / "run-broken") - if broken.not_ready: - again = self._break_once(self.root / "run-broken-retry") - again.seconds += broken.seconds - return again - return broken + def prepare_restart(self) -> None: + """Start Act 3's batch worker now, so it is ready when Act 3 begins.""" - def _break_once(self, run_dir: Path) -> BreakFacts: - from openadapt_flow.demo_proof import _final_frame, _load_report - from openadapt_flow.tutorial import _run_break_it, consequential_step + from openadapt.quickstart.restart import BatchWorker + from openadapt.quickstart.workers import worker_browser - assert self.workflow is not None - save = consequential_step(self.workflow).id - # The save step's screenshot lands before the engine's wait on the - # database, so it can be read during that wait. - self._early = EarlyScreenRead(run_dir / "steps" / f"{save}_after.png") - started = time.monotonic() + if self._restart_worker is not None: + return try: - result = _run_break_it( - workflow=self.workflow, - bundle_dir=self.bundle_dir, - run_dir=run_dir, - headed=self.visible, - say=lambda message: None, - ) - finally: - self._early.stop() - seconds = time.monotonic() - started - report = _load_report(Path(result.run_dir)) - screenshot = _final_frame(Path(result.run_dir), report) if report else None - screen_text = None # read by read_screen(), alongside the page - broken = BreakFacts( - run_dir=Path(result.run_dir), - fault=result.fault, - execution_outcome=str(result.execution_outcome), - transaction_outcome=result.transaction_outcome, - screen_showed_success=bool(result.screen_claimed_success), - screen_text=screen_text, - screenshot=screenshot, - new_records=int(result.system_of_record_records), - effects_required=int(result.effects_required), - effects_refuted=int(result.effects_refuted), - halt_reason=str(result.halt_reason), - model_calls=int(getattr(report, "model_calls", 0) or 0), - seconds=seconds, - # The record check read the save back and refuted it: the - # silent failure this act injects, not some other refusal. - stop_attributed=int(result.effects_refuted) > 0, - not_ready=starting_state_not_ready( - result.execution_outcome, - result.transaction_outcome, - result.halt_reason, - ), - result=result, - ) - if broken.not_ready: - broken.explanation = not_ready_explanation(self.visible) - return broken + browser = worker_browser(self.visible) or "" + self._restart_worker = BatchWorker(visible=self.visible, browser=browser) + except Exception: # noqa: BLE001 - Act 3 then says it was skipped + self._restart_worker = None + return + self._stack.callback(self._restart_worker.close) - def read_screen(self, broken: BreakFacts) -> Optional[str]: - """What the halted run's screen said. + def crash_restart(self) -> "RestartFacts": + """Act 3: stop the runner hard after note 1 of a batch, then restart it. - The saved message read off its screenshot (:func:`read_screen_text`), - else the success text the engine itself observed on screen when it - checked the step, else None. + See :mod:`openadapt.quickstart.restart`. """ - text = None - if broken.screenshot is not None: - early = getattr(self, "_early", None) - if early is not None: - text = early.text_for(broken.screenshot) - if text is None: - text = read_screen_text(broken.screenshot) - if text is None: - claim = getattr(broken.result, "screen_claim_text", None) - text = str(claim).strip() if claim else None - return text + from openadapt_flow.mockmed.fault_server import serve + + from openadapt.quickstart.restart import crash_and_restart + + assert self.workflow is not None + if self._restart_worker is None: + self.prepare_restart() + worker, self._restart_worker = self._restart_worker, None + return crash_and_restart( + root=self.root, + workflow=self.workflow, + bundle_dir=self.bundle_dir, + visible=self.visible, + worker=worker, + serve=serve, + ) # -- finale ----------------------------------------------------------- @@ -769,28 +654,12 @@ def seal(self, runs: list[RunFacts]) -> Optional[SealFacts]: return seal_runs(runs) - def seal_broken(self, broken: BreakFacts) -> bool: - """Sign the stopped run's report too; True once its Seal is written. - - Its Seal says the report is the one the run wrote, stop and all. - Engines without offline Seals sign nothing. - """ - - try: - from openadapt_flow.offline_seal import seal_home, seal_run - except ImportError: - return False - seal_run(broken.run_dir, home=seal_home(), enqueue=False) - write_run_receipts([broken.run_dir]) - return (broken.run_dir / "seal.json").is_file() - def seal_pages( self, runs: list[RunFacts], - broken: Optional[BreakFacts], command: Optional[Callable[[Path], str]] = None, ) -> SealPages: - """Write the Seal pages: the first checked run's and the stopped run's. + """Write the Seal page of the first checked run. Only a sealed run gets a page. Each page is the offline viewer with that run's files in it (:mod:`openadapt.seal_view`); nothing leaves @@ -827,51 +696,8 @@ def page(run_dir: Path, kicker: str) -> Path: ) if first is not None and (first.run_dir / "seal.json").is_file(): pages.verified = page(first.run_dir, f"Run {first.index} of {len(runs)}") - if broken is not None and (broken.run_dir / "seal.json").is_file(): - pages.broken = page(broken.run_dir, "The run with the failed save") return pages - def write_page(self, first: RunFacts, broken: BreakFacts) -> Optional[Path]: - """Write the side-by-side page (``openadapt flow demo``'s page).""" - - from openadapt_flow import demo_proof - from openadapt_flow.tutorial import TutorialResult - - report = demo_proof._load_report(first.run_dir) - tier: Optional[int] = None - for step in getattr(report, "results", []) or []: - for evidence in step.effect_evidence: - if ( - evidence.final_verdict == "confirmed" - and evidence.verification_tier is not None - ): - value = int(evidence.verification_tier) - tier = value if tier is None else min(tier, value) - receipts = { - kind: first.run_dir / f"receipt.{kind}" - for kind in ("json", "md", "png") - if _artifact_is_file(first.run_dir / f"receipt.{kind}") - } - result = TutorialResult( - recording_dir=self.recording_dir, - bundle_dir=self.bundle_dir, - run_dir=first.run_dir, - execution_outcome=first.execution_outcome, - transaction_outcome=first.transaction_outcome, - execution_profile=getattr(report, "execution_profile", None), - transaction_billable=getattr(report, "transaction_billable", None), - model_calls=first.model_calls, - effects_required=first.effects_required, - effects_confirmed=first.effects_confirmed, - effect_tier=tier, - bundle_digest=getattr(report, "bundle_content_digest", None), - system_of_record_records=first.records, - receipt_paths=receipts, - break_it=broken.result, - ) - evidence = demo_proof.collect_evidence(result, self.root) - return demo_proof.write_demo_page(evidence) - def seal_runs(runs: list[RunFacts]) -> Optional[SealFacts]: """Sign each checked run's report with this computer's Seal key.""" @@ -1008,7 +834,6 @@ def open_page(page: Path) -> bool: "demo_step_label", "display_available", "open_page", - "read_screen_text", "readback_fields", "return_focus_to_terminal", ] diff --git a/openadapt/quickstart/openemr.py b/openadapt/quickstart/openemr.py index 651b8a0383..48da646341 100644 --- a/openadapt/quickstart/openemr.py +++ b/openadapt/quickstart/openemr.py @@ -1,6 +1,6 @@ """``openadapt quickstart --app openemr``: the three acts on a real OpenEMR. -The default quickstart uses the bundled MockMed: no Docker, about 22 seconds. +The default quickstart uses the bundled MockMed: no Docker, about 30 seconds. This mode runs the same story on OpenEMR 8.0.0.3 in Docker, with the certified referral program behind the site's OpenEMR Seals: diff --git a/openadapt/quickstart/restart.py b/openadapt/quickstart/restart.py new file mode 100644 index 0000000000..67f8110ca3 --- /dev/null +++ b/openadapt/quickstart/restart.py @@ -0,0 +1,491 @@ +"""Act 3 on MockMed: stop the runner partway through a batch, then restart it. + +A batch of two new notes runs in a separate worker process. Each note's run +goes through the same governed path as Act 2 (the Standard run gate, the +record check against the app's database) and, in addition, through the +engine's at-most-once write ledger (``IdempotencyLedger``, kept on disk in the +output folder): the replayer reserves the note's key in the ledger before its +first action and records the outcome after the record check. + +When note 1's run has returned, the worker is stopped with ``SIGKILL`` +before it starts note 2. The batch then starts again in this process with the +same ledger. The replayer finds note 1's key already reserved and does not run +it (``idempotent_replay``); note 2 runs and saves. Last, each note's database +is read out of band and the note is counted there. + +Each note has its own copy of the clinic's database, as each run in Act 2 +does: the tutorial program writes one logical record per patient, so two +notes can't both be checked in one database. Every number shown comes from +the run reports, the ledger and the databases; nothing is scripted output. +""" + +from __future__ import annotations + +import multiprocessing +import os +import signal +import time +from dataclasses import asdict, dataclass, field +from multiprocessing.connection import Connection +from pathlib import Path +from typing import Any, Callable, Optional, Sequence + +from openadapt.quickstart.engine import RUN_NOTES + +#: The batch: two new notes, not ones Act 2 used. +RESTART_NOTES = RUN_NOTES[2:4] + +#: How long the worker may take to get ready, and to run note 1. +READY_TIMEOUT_S = 120.0 +RUN_TIMEOUT_S = 60.0 + +#: Where Act 3 writes, under the quickstart's output folder. +RESTART_DIR = "restart" + + +@dataclass +class NoteRun: + """One note's run, read from its report, the ledger and its database.""" + + index: int + note: str + run_dir: Path + execution_outcome: str + transaction_outcome: Optional[str] + #: Saved, and the record check confirmed it in the database. + checked: bool + #: The replayer found this note's key in the ledger and did not run it. + skipped: bool + #: The outcome the ledger holds for this note's key after the run. + ledger_outcome: Optional[str] + #: Program actions this run performed (0 for a skipped note). + actions: int + model_calls: int + seconds: float + + @property + def report_md(self) -> Path: + return self.run_dir / "REPORT.md" + + +@dataclass +class RestartFacts: + """What Act 3 showed.""" + + notes: list[str] + ledger: Path + #: The runs the first worker finished before it was stopped. + before: list[NoteRun] = field(default_factory=list) + #: True once the worker was stopped by SIGKILL (or, on Windows, killed). + killed: bool = False + #: The signal that stopped it ("SIGKILL"), or "" where there are none. + signal: str = "" + #: The runs after the restart, one per note. + after: list[NoteRun] = field(default_factory=list) + #: How many records hold each note, in that note's database. + copies: list[int] = field(default_factory=list) + seconds: float = 0.0 + #: Why the act couldn't run (no second process, for example), if so. + error: Optional[str] = None + #: What went wrong after the worker was stopped, if anything did. + restart_error: Optional[str] = None + + @property + def model_calls(self) -> int: + return sum(run.model_calls for run in self.before + self.after) + + @property + def held(self) -> bool: + """Note 1 saved, the worker stopped, note 1 skipped, note 2 saved, + and each note in its database exactly once.""" + + if self.error or self.restart_error or not self.killed: + return False + if len(self.notes) != 2: + return False + if len(self.before) != 1 or len(self.after) != 2: + return False + first, (again, second) = self.before[0], self.after + return ( + first.checked + and again.skipped + and again.actions == 0 + and second.checked + and not second.skipped + and self.copies == [1, 1] + ) + + @property + def report_md(self) -> Path: + runs = self.after or self.before + return runs[-1].report_md if runs else self.ledger.parent + + +def ledger_key(batch: str, index: int) -> str: + """The ledger key of one note in one batch.""" + + return f"quickstart-batch/{batch}/note-{index}" + + +def _verifier(base_url: str) -> Any: + """The tutorial's record check: it reads the app's database over HTTP.""" + + from openadapt_flow import tutorial + + build = getattr(tutorial, "_build_demo_effect_verifier", None) + if build is not None: + return build(base_url) + from openadapt_flow.deployment import EffectsConfig, build_effect_verifier + from openadapt_flow.mockmed.fault_server import MOCKMED_RECORDS_READ_CONTRACT + + verifier = build_effect_verifier( + EffectsConfig.model_validate( + { + **MOCKMED_RECORDS_READ_CONTRACT, + "base_url": base_url, + "timeout_s": 2.0, + "poll_interval_s": 0.05, + } + ) + ) + if verifier is None: + raise RuntimeError("the record contract built no verifier") + return verifier + + +def note_count(base_url: str, note: str) -> int: + """How many records in the database at ``base_url`` hold ``note``.""" + + from openadapt_flow.tutorial import _records + + return sum(1 for record in _records(base_url) if record.get("note") == note) + + +def run_note( + *, + base_url: str, + workflow: Any, + bundle_dir: Path, + run_dir: Path, + index: int, + note: str, + ledger_path: Path, + key: str, + visible: bool, +) -> NoteRun: + """Run the program once for ``note`` under the ledger key ``key``. + + The tutorial's own run (the Standard run gate, the record check), with + the engine's at-most-once ledger attached, and without resetting the + database first. + """ + + from openadapt_flow.backends.playwright_backend import PlaywrightBackend + from openadapt_flow.deployment import DeploymentConfig, PolicySection + from openadapt_flow.execution_profiles import ( + ExecutionProfile, + execution_profile_contract, + ) + from openadapt_flow.run_gate import build_runtime_authorization, evaluate_run_gate + from openadapt_flow.runtime import Replayer + from openadapt_flow.transaction import IdempotencyLedger + from openadapt_flow.tutorial import TUTORIAL_ENTRY_QUERY, TUTORIAL_POLICY + + base = base_url.rstrip("/") + entry_url = f"{base}/{TUTORIAL_ENTRY_QUERY}" + verifier = _verifier(base_url) + gate = evaluate_run_gate( + workflow, + bundle_dir=bundle_dir, + deployment=DeploymentConfig(policy=PolicySection(policy=TUTORIAL_POLICY)), + effect_verifier=verifier, + profile_contract=execution_profile_contract(ExecutionProfile.STANDARD), + effective_durable=True, + effective_require_settled=True, + ) + if not gate.passed: + raise RuntimeError( + f"the standard run gate refused the program:\n{gate.render()}" + ) + params = {"note": note} + authorization = build_runtime_authorization( + workflow, gate, approval_source="openadapt-quickstart", params=params + ) + ledger = IdempotencyLedger(ledger_path) + started = time.monotonic() + backend, close = PlaywrightBackend.launch(entry_url, headless=not visible) + try: + report = Replayer( + backend, + effect_verifier=verifier, + governed_authorization=authorization, + durable=True, + require_settled=True, + idempotency_ledger=ledger, + ).run( + workflow.model_copy(deep=True), + params=params, + bundle_dir=bundle_dir, + run_dir=run_dir, + execution_target_kind="web", + execution_origin=base, + execution_entry_url=entry_url, + idempotency_key=key, + ) + finally: + close() + seconds = time.monotonic() - started + try: + from openadapt_flow.report import render_run_report + + render_run_report(run_dir) + except Exception: # noqa: BLE001 - report.json is the record either way + pass + record = ledger.lookup(key) + ledger.close() + envelope = getattr(report, "outcome_envelope", None) + required = int(envelope.required_contracts.effect) if envelope else 0 + confirmed = int(envelope.passed_contracts.effect) if envelope else 0 + skipped = bool(getattr(report, "idempotent_replay", False)) + actions = sum( + 1 + for result in getattr(report, "results", []) or [] + if not str(getattr(result, "step_id", "")).startswith("<") + ) + checked = ( + not skipped + and str(report.execution_outcome) == "VERIFIED" + and report.transaction_outcome == "VERIFIED" + and required > 0 + and confirmed == required + and note_count(base_url, note) >= 1 + ) + return NoteRun( + index=index, + note=note, + run_dir=run_dir, + execution_outcome=str(report.execution_outcome), + transaction_outcome=report.transaction_outcome, + checked=checked, + skipped=skipped, + ledger_outcome=(record or {}).get("outcome"), + actions=actions, + model_calls=int(getattr(report, "model_calls", 0) or 0), + seconds=seconds, + ) + + +def _worker_main(conn: Connection, visible: bool, browser: str = "") -> None: + """The batch worker: get ready, run the batch's notes in order. + + After each note it reports the run and waits for the parent's word before + the next one, so the parent can stop it between notes. + """ + + from openadapt.quickstart.workers import OCR_THREADS_ENV, WORKER_NICENESS + + # Its own process group, so one SIGKILL stops the worker together with + # the browser driver and browser it starts. + if hasattr(os, "setpgrp"): + os.setpgrp() + os.environ.setdefault(OCR_THREADS_ENV, "2") + if browser: + os.environ["OPENADAPT_FLOW_BROWSER"] = browser + from openadapt.quickstart.notices import quiet_in_worker + + quiet_in_worker() + if hasattr(os, "nice"): + try: + os.nice(WORKER_NICENESS) + except OSError: + pass + try: + from openadapt_flow import _prewarm + from openadapt_flow.backends._browser_process import shared_browser + from openadapt_flow.ir import Workflow + + _prewarm.start() + with shared_browser(headless=not visible): + conn.send(("ready",)) + message = conn.recv() + if message[0] != "batch": + return + _, jobs, bundle_dir, ledger_path = message + workflow = Workflow.load(Path(bundle_dir)) + for index, note, base_url, run_dir, key in jobs: + run = run_note( + base_url=base_url, + workflow=workflow, + bundle_dir=Path(bundle_dir), + run_dir=Path(run_dir), + index=index, + note=note, + ledger_path=Path(ledger_path), + key=key, + visible=visible, + ) + payload = asdict(run) + payload["run_dir"] = str(run.run_dir) + conn.send(("ran", payload)) + if conn.recv()[0] != "next": + return + except (EOFError, KeyboardInterrupt, BrokenPipeError): + return + except Exception as exc: # noqa: BLE001 - reported to the parent + try: + conn.send(("broken", f"{type(exc).__name__}: {exc}")) + except (BrokenPipeError, OSError): + pass + finally: + conn.close() + + +class BatchWorker: + """One worker process, started early so it is ready when Act 3 begins.""" + + def __init__(self, *, visible: bool, browser: str = "") -> None: + context = multiprocessing.get_context("spawn") + self._conn, child = context.Pipe() + self.process = context.Process( + target=_worker_main, args=(child, visible, browser), daemon=True + ) + self.process.start() + child.close() + + def _recv(self, timeout: float) -> tuple[Any, ...]: + if not self._conn.poll(timeout): + return ("broken", f"no answer from the worker in {timeout:.0f}s") + try: + return tuple(self._conn.recv()) + except (EOFError, OSError): + return ("broken", "the worker process exited") + + def first_note( + self, jobs: Sequence[tuple[Any, ...]], bundle_dir: Path, ledger_path: Path + ) -> NoteRun: + """Send the batch and wait for its first note's run.""" + + ready = self._recv(READY_TIMEOUT_S) + if ready[0] != "ready": + raise RuntimeError(str(ready[1]) if len(ready) > 1 else "not ready") + self._conn.send(("batch", list(jobs), str(bundle_dir), str(ledger_path))) + message = self._recv(RUN_TIMEOUT_S) + if message[0] != "ran": + raise RuntimeError(str(message[1])) + fields = dict(message[1]) + fields["run_dir"] = Path(fields["run_dir"]) + return NoteRun(**fields) + + def kill(self) -> bool: + """Stop the worker at once: SIGKILL where there is one.""" + + if not self.process.is_alive(): + return False + self._hard_stop() + self.process.join(timeout=10) + self._conn.close() + return not self.process.is_alive() + + def _hard_stop(self) -> None: + pid = self.process.pid + if pid is None: + return + if hasattr(os, "killpg") and hasattr(signal, "SIGKILL"): + try: + os.killpg(pid, signal.SIGKILL) + return + except (ProcessLookupError, PermissionError): + pass + self.process.kill() # SIGKILL, or TerminateProcess on Windows + + def close(self) -> None: + # Also after kill(): anything left in the worker's group goes too. + self._hard_stop() + self.process.join(timeout=5) + try: + self._conn.close() + except OSError: + pass + + +def crash_and_restart( + *, + root: Path, + workflow: Any, + bundle_dir: Path, + visible: bool, + worker: Optional[BatchWorker], + serve: Callable[[], tuple[str, Any, Callable[[], None]]], + notes: Sequence[str] = RESTART_NOTES, + clock: Callable[[], float] = time.monotonic, +) -> RestartFacts: + """Run Act 3: the batch, the hard stop after note 1, the restart.""" + + folder = root / RESTART_DIR + ledger_path = folder / "ledger" / "writes.sqlite" + facts = RestartFacts(notes=list(notes), ledger=ledger_path) + started = clock() + if worker is None: + facts.error = "the second runner process didn't start" + return facts + stops: list[Callable[[], None]] = [] + try: + urls = [] + for _ in notes: + base_url, _db, stop = serve() + stops.append(stop) + urls.append(base_url) + jobs = [ + ( + index, + note, + urls[index - 1], + str(folder / f"note-{index}"), + ledger_key(root.name, index), + ) + for index, note in enumerate(notes, 1) + ] + try: + facts.before.append(worker.first_note(jobs, bundle_dir, ledger_path)) + except RuntimeError as error: + facts.error = f"the runner process stopped early: {error}" + return facts + facts.killed = worker.kill() + facts.signal = "SIGKILL" if hasattr(signal, "SIGKILL") else "" + # The restart: the same batch, the same ledger, in this process. + try: + for index, note, base_url, _run_dir, key in jobs: + facts.after.append( + run_note( + base_url=base_url, + workflow=workflow, + bundle_dir=bundle_dir, + run_dir=folder / f"note-{index}-restart", + index=index, + note=note, + ledger_path=ledger_path, + key=key, + visible=visible, + ) + ) + except Exception as error: # noqa: BLE001 - shown, and the act fails + facts.restart_error = f"{type(error).__name__}: {error}" + facts.copies = [note_count(url, note) for url, note in zip(urls, notes)] + finally: + worker.close() + for stop in stops: + stop() + facts.seconds = clock() - started + return facts + + +__all__ = [ + "RESTART_NOTES", + "BatchWorker", + "NoteRun", + "RestartFacts", + "crash_and_restart", + "ledger_key", + "note_count", + "run_note", +] diff --git a/openadapt/quickstart/restart_view.py b/openadapt/quickstart/restart_view.py new file mode 100644 index 0000000000..a7e582f5f1 --- /dev/null +++ b/openadapt/quickstart/restart_view.py @@ -0,0 +1,134 @@ +"""The words for Act 3 on MockMed (stop mid-batch, restart), for both views. + +Every line is built from :class:`~openadapt.quickstart.restart.RestartFacts`, +so a run that goes another way prints what happened, not the plan. +""" + +from __future__ import annotations + +from typing import Any, Optional + +from openadapt.quickstart.restart import NoteRun, RestartFacts + +#: Width of the note column, so the statuses line up. +NOTE_WIDTH = 34 + + +def _seconds(value: float) -> str: + return f"{value:.1f}s" + + +def note_status(run: NoteRun, marks: Any) -> str: + """One note's result: checked, skipped by the ledger, or what stopped it.""" + + if run.skipped: + done = run.ledger_outcome == "VERIFIED" + why = "the ledger has it as done" if done else "the ledger has it as started" + return f"{marks.dot} Skipped: {why}, no save sent" + if run.checked: + return f"{marks.ok} checked in the database" + return f"{marks.stop} {run.transaction_outcome or run.execution_outcome}" + + +def note_row(run: NoteRun, total: int, marks: Any) -> str: + return ( + f"{run.index}/{total} {run.note:<{NOTE_WIDTH}} " + f"{note_status(run, marks)} {_seconds(run.seconds)}" + ) + + +def stop_line(facts: RestartFacts, marks: Any) -> str: + if not facts.killed: + return f"{marks.no} The runner was still running; it was not stopped" + count = len(facts.before) + after = f"after note {count}" if count else "before any note" + how = "with SIGKILL" if facts.signal else "hard" + return f"{marks.stop} Runner process stopped {how} {after}, before note {count + 1}" + + +def copies_line(facts: RestartFacts) -> str: + """How many records hold each note, read from the database after the restart.""" + + if not facts.copies: + return "not read" + parts = [] + for index, count in enumerate(facts.copies, 1): + noun = "record" if count == 1 else "records" + parts.append(f"note {index}: {count} {noun}") + if facts.copies and all(count == 1 for count in facts.copies): + return "each note saved once (" + ", ".join(parts) + ")" + return ", ".join(parts) + + +def why_line(facts: RestartFacts) -> str: + if facts.held: + return ( + "OpenAdapt records each note in a ledger on disk before it saves " + "it, and records the outcome after the record check. On restart it " + "found note 1 marked done, so it sent no save for note 1 and saved " + "only note 2." + ) + if facts.restart_error: + return ( + f"The restart stopped with an error ({facts.restart_error}). The " + "reports say what each run did." + ) + return "The restart didn't go as expected. The reports say what each run did." + + +def summary_line(facts: RestartFacts) -> Optional[str]: + """The one-line summary, only when the run showed all of it.""" + + if not facts.held: + return None + return ( + "The runner was killed partway through the batch. On restart, " + "OpenAdapt sent no save for note 1 and saved note 2." + ) + + +def skipped_line(facts: RestartFacts) -> str: + return f"Skipped this part: {facts.error}." + + +def detail_lines(facts: RestartFacts) -> list[str]: + """Act 3's engine detail, for ``--verbose``.""" + + lines = [f"ledger {facts.ledger}"] + for label, runs in (("before the stop", facts.before), ("restart", facts.after)): + for run in runs: + lines.append( + f"{label}, note {run.index}: execution {run.execution_outcome}, " + f"transaction {run.transaction_outcome}, idempotent replay " + f"{run.skipped}, ledger outcome {run.ledger_outcome}, " + f"{run.actions} actions; report {run.report_md}" + ) + return lines + + +def plain_lines(facts: RestartFacts, marks: Any) -> list[str]: + """Act 3's result as plain lines (the plain view indents them).""" + + if facts.error: + return [skipped_line(facts)] + total = len(facts.notes) + lines = [note_row(run, total, marks) for run in facts.before] + lines.append(stop_line(facts, marks)) + lines.append("Restarted with the same ledger:") + lines.extend(note_row(run, total, marks) for run in facts.after) + lines.append(f"The database: {copies_line(facts)}") + lines.append(f"Why: {why_line(facts)}") + return lines + + +__all__ = [ + "copies_line", + "detail_lines", + "note_row", + "note_status", + "plain_lines", + "skipped_line", + "stop_line", + "summary_line", + "why_line", +] diff --git a/openadapt/quickstart/scene.py b/openadapt/quickstart/scene.py index 421c849796..6fced1d9d0 100644 --- a/openadapt/quickstart/scene.py +++ b/openadapt/quickstart/scene.py @@ -1,9 +1,10 @@ """The words that differ between the quickstart's apps. -MockMed (the default) breaks a save silently: the screen says saved and the -database has nothing. OpenEMR's Act 3 is a referral that matches an existing -chart: the program stops before saving. Everything else in the story and the -views is shared; a :class:`Scene` holds what is not. +MockMed (the default) ends with a crash and a restart: the runner is stopped +partway through a batch of two notes and started again, and it saves neither +note twice. OpenEMR's Act 3 is a referral that matches an existing chart: the +program stops before saving. Everything else in the story and the views is +shared; a :class:`Scene` holds what is not. """ from __future__ import annotations @@ -12,7 +13,7 @@ from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: - from openadapt.quickstart.engine import BreakFacts + from openadapt.quickstart.engine import BreakFacts, RunFacts @dataclass(frozen=True) @@ -29,80 +30,83 @@ class Scene: inputs_noun: str #: Where each run is checked ("checked in the database"). checked_in: str + #: Act 3's step line. + act3_title: str #: Act 3's subtitle. act3_subtitle: str #: The line before Act 3 runs. - break_setup: str + act3_setup: str #: The prompt before Act 3 runs, on a terminal. confirm_prompt: str #: What the spinner says while Act 3 runs. - breaking: str - #: The record's label in Act 3 ("What the database showed"). - record_label: str + act3_running: str + #: One run's engine detail for ``--verbose``; formatted with the run's + #: fields (see :meth:`run_detail`). + run_detail_template: str = ( + "run {index}: execution {execution}, transaction {transaction}, profile " + "standard, record checks {confirmed}/{required} confirmed by an " + "independent read of the database, {records} record(s) after the run; " + "report {report}" + ) #: What one record is called ("record": "0 new records"). - record_noun: str - #: OpenAdapt's verdict when Act 3 stopped. - stopped: str - #: The record check's subject in the receipt ("in the database"). - receipt_where: str + record_noun: str = "record" + #: True when Act 1 demonstrates in a browser now; False when it shows the + #: recorded demonstration a certified program was compiled from. + act1_live: bool = True + #: How Act 1 ends, given the program's step count. + compiled_template: str = "Compiled into a program: {steps} steps." + #: The first step's line once the app is up, and its dim detail. + ready: str = "Clinic app ready" + ready_detail: str = "synthetic data, on this computer" + #: The record's name in the read-back card ("The database"). + record_title: str = "The database" + + # The rest is for an Act 3 that stops before a save (OpenEMR's). + + #: OpenAdapt's verdict when Act 3 stopped at the check it sets off. + stopped: str = "Stopped" #: What Act 3's screen showed when its text couldn't be read, said only #: when the run observed it (see :meth:`screen_line`). - screen_default: str = "a saved message" - #: What the screen row says when the run observed neither the text nor - #: the screen this act expects. + screen_default: str = "" + #: What the screen row says when the run didn't observe what this act + #: expects. screen_unread: str = "not read (see the screenshot in the report)" #: The part of the 1280x800 screenshot Act 3 shows (left, top, right, #: bottom). screen_crop: tuple[int, int, int, int] = (0, 0, 640, 320) - #: True when Act 3's screen claims success (MockMed's silent failure), so - #: a screen-trusting bot's "Done" and the one-line summary apply. - screen_claims_success: bool = True - #: True when Act 1 demonstrates in a browser now; False when it shows the - #: recorded demonstration a certified program was compiled from. - act1_live: bool = True - #: How Act 1 ends, given the program's step count. - compiled_template: str = "Compiled into a program: {steps} steps." #: Why OpenAdapt stopped, when the run shows it stopped at this act's #: check and nothing was saved. - why_stopped: str = ( - "OpenAdapt reads the record back from the database after each save. " - "It found nothing, so it stopped." - ) + why_stopped: str = "" #: Why, when it stopped at this act's check but a record was saved. - why_saved_anyway: str = ( - "OpenAdapt read the record back, and it didn't match, so it stopped." - ) - #: The one-line summary for a screen that doesn't claim success. + why_saved_anyway: str = "" + #: The one-line summary when the run showed all of it. aha_stopped: str = "" - #: The first step's line once the app is up, and its dim detail. - ready: str = "Clinic app ready" - ready_detail: str = "synthetic data, on this computer" - #: Act 3's step line. - break_title: str = "Break the next save" - #: The record's side in Act 3's side-by-side ("The database"). - record_title: str = "The database" def compiled_line(self, steps: int) -> str: return self.compiled_template.format(steps=steps) + def run_detail(self, run: "RunFacts") -> str: + return self.run_detail_template.format( + index=run.index, + execution=run.execution_outcome, + transaction=run.transaction_outcome, + confirmed=run.effects_confirmed, + required=run.effects_required, + records=run.records, + report=run.report_md, + ) + def database_line(self, broken: "BreakFacts") -> str: count = broken.new_records return f"{count} new {self.record_noun}" + ("" if count == 1 else "s") - def screen_observed(self, broken: "BreakFacts") -> bool: - """True when the run observed the screen this act describes.""" - - if self.screen_claims_success: - return broken.screen_showed_success - return broken.stop_attributed - def screen_words(self, broken: "BreakFacts") -> str: """What the screen showed: the text read off it, else only what the run observed, else that it wasn't read.""" if broken.screen_text: return broken.screen_text - if self.screen_observed(broken): + if broken.stop_attributed and self.screen_default: return self.screen_default if getattr(broken, "not_ready", False): return "never reached: the run stopped before its first click" @@ -118,9 +122,7 @@ def screen_line(self, broken: "BreakFacts") -> str: def verdict(self, broken: "BreakFacts") -> str: """OpenAdapt's verdict when it stopped (``stopped`` only if attributed).""" - if broken.stop_attributed and ( - self.screen_claims_success or broken.new_records == 0 - ): + if broken.stop_attributed and broken.new_records == 0: return self.stopped return "Stopped" @@ -154,73 +156,49 @@ def aha_line(self, broken: "BreakFacts") -> Optional[str]: if not (broken.stopped and broken.stop_attributed and broken.new_records == 0): return None - if not self.screen_claims_success: - return self.aha_stopped or None - if not broken.screen_showed_success: - return None - text = broken.screen_text - end = text.lower().find("saved") if text else -1 - if text and end >= 0: - screen = f'The screen said "{text[: end + len("saved")]}".' - else: - screen = "The screen showed its saved message." - return ( - f"{screen} The database had nothing. A bot that trusts the screen " - "reports Done. OpenAdapt stopped." - ) + return self.aha_stopped or None def break_detail(self, broken: "BreakFacts") -> list[str]: """Act 3's engine detail, for ``--verbose``.""" - if not self.screen_claims_success: - first = ( - f"case {broken.fault!r}: OpenEMR already has a chart with this name" - + ( - ", and its duplicate check listed a match" - if broken.stop_attributed - else "; the halt doesn't show the duplicate check listing it" - ) - ) - ran = ( - " (the save step never ran)" - if broken.transaction_outcome == "HALTED_BEFORE_EFFECT" - else "" - ) - checks = f"record checks {broken.effects_required} declared{ran}" - else: - first = ( - f"fault mode {broken.fault!r}: the server rejects the write after " - "the app shows its saved message" - ) - checks = ( - f"record checks refuted " - f"{broken.effects_refuted}/{broken.effects_required}" - ) + first = f"case {broken.fault!r}: OpenEMR already has a chart with this name" + ( + ", and its duplicate check listed a match" + if broken.stop_attributed + else "; the halt doesn't show the duplicate check listing it" + ) + ran = ( + " (the save step never ran)" + if broken.transaction_outcome == "HALTED_BEFORE_EFFECT" + else "" + ) return [ first, f"execution {broken.execution_outcome}, transaction " - f"{broken.transaction_outcome}, {checks}", + f"{broken.transaction_outcome}, record checks " + f"{broken.effects_required} declared{ran}", f"engine: {broken.halt_reason}", f"report {broken.report_md}", ] MOCKMED = Scene( - intro=("show a task once, run it, then watch it catch a save that didn't happen."), + intro=( + "show a task once, run it, then stop it mid-batch and watch the " + "restart skip what was already saved." + ), starting="Starting the synthetic clinic app", act1_where="a demonstration in a synthetic clinic app", inputs_noun="notes", checked_in="checked in the database", - act3_subtitle="the next save fails silently", - break_setup=( - "The app will show its saved message. The database will reject the save." + act3_title="Stop it mid-batch, then restart", + act3_subtitle="the runner is stopped after note 1 of 2 and started again", + act3_setup=( + "A batch of 2 new notes, each in its own copy of the clinic's database. " + "The runner process is stopped hard after note 1 saves, then started " + "again." ), - confirm_prompt="Press Enter to make the next save fail silently", - breaking="Running the program once more, checking the database", - record_label="What the database showed", - record_noun="record", - stopped="Stopped. Not marked done.", - receipt_where="in the database", + confirm_prompt="Press Enter to start the batch", + act3_running="Running the batch, stopping the runner, restarting it", ) OPENEMR = Scene( @@ -232,18 +210,21 @@ def break_detail(self, broken: "BreakFacts") -> list[str]: act1_where="a referral as it was demonstrated once in OpenEMR 8.0.0.3", inputs_noun="referrals", checked_in="checked in OpenEMR's record", + act3_title="Try a referral that matches a chart", act3_subtitle="a referral that matches an existing chart", - break_setup=( + act3_setup=( "OpenEMR already has a chart for Rosa Delgado. The next referral is a " "Rosa Delgado with another birth date." ), confirm_prompt="Press Enter to run the program on that referral", - breaking="Running the program on the referral, then reading OpenEMR's charts", - record_label="What OpenEMR's record showed", + act3_running="Running the program on the referral, then reading OpenEMR's charts", + run_detail_template=( + "run {index}: execution {execution}, transaction {transaction}, record " + "checks {confirmed}/{required} confirmed through OpenEMR's REST API, " + "{records} chart(s) for this referral in OpenEMR's database; report {report}" + ), record_noun="chart", stopped="Stopped before saving: possible duplicate", - receipt_where="in OpenEMR's record", - screen_claims_success=False, act1_live=False, compiled_template=( "The program compiled from it: {steps} steps, certified under clinical-write." @@ -261,7 +242,6 @@ def break_detail(self, broken: "BreakFacts") -> list[str]: screen_crop=(204, 30, 1078, 262), ready="OpenEMR ready", ready_detail="OpenEMR 8.0.0.3 in Docker, synthetic data", - break_title="Try a referral that matches a chart", record_title="OpenEMR's record", ) diff --git a/openadapt/quickstart/story.py b/openadapt/quickstart/story.py index 961b4330d1..60102765da 100644 --- a/openadapt/quickstart/story.py +++ b/openadapt/quickstart/story.py @@ -1,4 +1,8 @@ -"""The quickstart in three acts: show it once, run it, break it. +"""The quickstart in three acts: show it once, run it, stop and restart it. + +On MockMed, Act 3 stops the runner partway through a batch and restarts it +(:mod:`openadapt.quickstart.restart`); on OpenEMR it runs a referral that +matches an existing chart, where the program stops before saving. This module decides what happens and in what order. The engine adapter (:mod:`openadapt.quickstart.engine`) does the work and measures it; the view @@ -12,7 +16,7 @@ import time from dataclasses import dataclass, field from pathlib import Path -from typing import Any, Callable, Optional, Protocol, Sequence +from typing import TYPE_CHECKING, Any, Callable, Optional, Protocol, Sequence from openadapt.quickstart.engine import ( RUN_NOTES, @@ -24,6 +28,9 @@ ) from openadapt.quickstart.scene import MOCKMED, Scene +if TYPE_CHECKING: + from openadapt.quickstart.restart import RestartFacts + #: The placeholder app address in the "try it on your own app" command. YOUR_APP_URL = "https://your-app.example" #: One-line Python drop-in for Playwright/CUA agents via ``openadapt-verify``. @@ -81,22 +88,13 @@ def run_all( def before_prompt(self) -> None: ... - def break_it(self) -> BreakFacts: ... - - def read_screen(self, broken: BreakFacts) -> Optional[str]: ... - def seal(self, runs: list[RunFacts]) -> Optional[SealFacts]: ... - def seal_broken(self, broken: BreakFacts) -> bool: ... - - def seal_pages( - self, - runs: list[RunFacts], - broken: Optional[BreakFacts], - command: Optional[Callable[[Path], str]] = None, - ) -> SealPages: ... - - def write_page(self, first: RunFacts, broken: BreakFacts) -> Optional[Path]: ... + # Act 3 is one of two kinds. MockMed's engine has ``prepare_restart()`` + # and ``crash_restart() -> RestartFacts``; OpenEMR's has ``break_it() -> + # BreakFacts``, ``read_screen(broken)`` and ``write_page(first, broken)``. + # The story finds them with getattr, as it does ``seal_pages(runs, + # command)``. @dataclass @@ -116,9 +114,9 @@ class NextSteps: #: The command that checks one run folder, for its Seal page. verify_run: Optional[Callable[[Path], str]] = None #: In a terminal and outside CI only: asks once whether to publish the - #: public Seals of the checked run and the stopped run, and does so on a - #: yes. Called as ``offer_publish(run_dirs, say, ask)``; returns False, - #: having said nothing, when hosted Seals are not live. + #: public Seal of the checked run, and does so on a yes. Called as + #: ``offer_publish(run_dirs, say, ask)``; returns False, having said + #: nothing, when hosted Seals are not live. offer_publish: Optional[ Callable[[list[Path], Callable[[str], None], Callable[[str], str]], bool] ] = None @@ -135,9 +133,12 @@ class Outcome: act1_seconds: float = 0.0 runs: list[RunFacts] = field(default_factory=list) act2_seconds: float = 0.0 + #: OpenEMR's Act 3: the referral that matches an existing chart. broken: Optional[BreakFacts] = None + #: MockMed's Act 3: the batch, the hard stop and the restart. + restart: Optional["RestartFacts"] = None seal: Optional[SealFacts] = None - #: The Seal pages (``seal.html``) of the first checked run and the stopped run. + #: The Seal page (``seal.html``) of the first checked run. seal_pages: SealPages = field(default_factory=SealPages) seal_page_opened: bool = False page: Optional[Path] = None @@ -158,6 +159,8 @@ def model_calls(self) -> int: calls = sum(run.model_calls for run in self.runs) if self.broken is not None: calls += self.broken.model_calls + if self.restart is not None: + calls += self.restart.model_calls return calls @property @@ -190,35 +193,23 @@ def run_row(self, run: RunFacts, total: int) -> None: ... def runs_total(self, outcome: Outcome) -> None: ... - def break_setup(self) -> None: ... + def act3_setup(self) -> None: ... def confirm(self, prompt: str) -> None: ... - def breaking(self) -> Any: ... + def act3_running(self) -> Any: ... def break_result(self, broken: BreakFacts) -> None: ... + def restart_result(self, facts: "RestartFacts") -> None: ... + def finale(self, outcome: Outcome, steps: NextSteps) -> None: ... def detail(self, lines: list[str]) -> None: ... def _engine_detail_run(run: RunFacts, scene: Scene) -> list[str]: - if not scene.screen_claims_success: - return [ - f"run {run.index}: execution {run.execution_outcome}, transaction " - f"{run.transaction_outcome}, record checks " - f"{run.effects_confirmed}/{run.effects_required} confirmed through " - f"OpenEMR's REST API, {run.records} chart(s) for this referral in " - f"OpenEMR's database; report {run.report_md}", - ] - return [ - f"run {run.index}: execution {run.execution_outcome}, transaction " - f"{run.transaction_outcome}, profile standard, record checks " - f"{run.effects_confirmed}/{run.effects_required} confirmed by an " - f"independent read of the database, {run.records} record(s) after the " - f"run; report {run.report_md}", - ] + return [scene.run_detail(run)] def run_story( @@ -226,7 +217,7 @@ def run_story( view: View, *, next_steps: Callable[[Outcome], NextSteps], - break_it: bool = True, + last_act: bool = True, interactive: bool = False, verbose: bool = False, open_page: Optional[Callable[[Path], bool]] = None, @@ -248,8 +239,12 @@ def run_story( ready = getattr(engine, "setup_summary", None) if ready: view.setup_done(ready) - # Act 1: show it once. Act 2's workers get ready meanwhile. + # Act 1: show it once. Act 2's workers, and Act 3's, get ready + # meanwhile. engine.start_workers() + prepare_restart = getattr(engine, "prepare_restart", None) + if last_act and prepare_restart is not None: + prepare_restart() view.act(1, "Show it once", _act1_subtitle(engine.visible, scene)) act_start = clock() outcome.demo_steps = engine.record(view.demo_step) @@ -311,33 +306,32 @@ def finished(run: RunFacts) -> None: if unready: note = getattr(view, "not_ready", None) if note is not None: - note(unready[0].explanation, break_it and skip_break) + note(unready[0].explanation, last_act and skip_break) # Sign the checked runs' reports while Act 3 runs; the finale waits. sealing = _in_background(lambda: engine.seal(list(outcome.runs))) - # Act 3: break it. + # Act 3: stop it mid-batch and restart it (MockMed), or a referral + # that matches an existing chart (OpenEMR). paging = None - if break_it and not skip_break: - view.act(3, "Break it", scene.act3_subtitle) - view.break_setup() + if last_act and not skip_break: + view.act(3, scene.act3_title, scene.act3_subtitle) + view.act3_setup() if interactive: waited = clock() engine.before_prompt() view.confirm(scene.confirm_prompt) paused += clock() - waited - with view.breaking(): - outcome.broken = engine.break_it() - broken = outcome.broken - if outcome.runs: - # The page needs only the runs; build it while the - # screenshot is read. - paging = _in_background( - lambda: engine.write_page(outcome.runs[0], broken) - ) - broken.screen_text = engine.read_screen(broken) - view.break_result(outcome.broken) - if verbose: - view.detail(scene.break_detail(outcome.broken)) + crash_restart = getattr(engine, "crash_restart", None) + if crash_restart is not None: + with view.act3_running(): + outcome.restart = crash_restart() + view.restart_result(outcome.restart) + if verbose: + from openadapt.quickstart.restart_view import detail_lines + + view.detail(detail_lines(outcome.restart)) + else: + paging = _break_act(engine, view, outcome, scene, verbose) outcome.seal = sealing.result() if paging is not None: @@ -356,24 +350,41 @@ def finished(run: RunFacts) -> None: return outcome +def _break_act( + engine: Any, view: View, outcome: Outcome, scene: Scene, verbose: bool +) -> Any: + """OpenEMR's Act 3: run the referral that matches a chart; show the stop. + + Returns the side-by-side page's future, or None. + """ + + paging = None + with view.act3_running(): + outcome.broken = engine.break_it() + broken = outcome.broken + if outcome.runs: + # The page needs only the runs; build it while the screenshot + # is read. + first = outcome.runs[0] + paging = _in_background(lambda: engine.write_page(first, broken)) + broken.screen_text = engine.read_screen(broken) + view.break_result(outcome.broken) + if verbose: + view.detail(scene.break_detail(outcome.broken)) + return paging + + def _write_seal_pages(engine: Engine, outcome: Outcome, steps: NextSteps) -> None: - """Sign the stopped run, then write the Seal pages. + """Write the Seal page of the first checked run, when the engine can. - The receipt counts the stopped run's Seal when it was written, whether or - not its page is; a page that can't be written leaves no Seal line. + A page that can't be written leaves no page line; the Seals still count. """ - if outcome.seal is not None and outcome.broken is not None: - try: - sealed = engine.seal_broken(outcome.broken) - except Exception: # noqa: BLE001 - the checked runs' Seals stand alone - sealed = False - if sealed: - outcome.seal = SealFacts(outcome.seal.key_id, outcome.seal.sealed + 1) + seal_pages = getattr(engine, "seal_pages", None) + if seal_pages is None: + return try: - outcome.seal_pages = engine.seal_pages( - list(outcome.runs), outcome.broken, steps.verify_run - ) + outcome.seal_pages = seal_pages(list(outcome.runs), steps.verify_run) except Exception: # noqa: BLE001 - the runs and their Seals stand without a page outcome.seal_pages = SealPages() diff --git a/openadapt/quickstart/view.py b/openadapt/quickstart/view.py index 6b785b885d..f1541553b1 100644 --- a/openadapt/quickstart/view.py +++ b/openadapt/quickstart/view.py @@ -2,11 +2,12 @@ Five steps, each a plain-English line and a dim detail: the app starts, the task is shown once, it becomes a program, the program runs on new inputs, and -the next save is broken on purpose. Then the person's Seal and one next step. +the last act (on MockMed, the runner stopped mid-batch and restarted). Then +the person's Seal and one next step. Both views say the same things in the same words (the helpers below). The live view adds spinners that resolve to check marks, a card that ticks off -the read-back field by field, the screen and the record side by side, a +the read-back field by field, OpenEMR's screen and record side by side, a drawn Seal and a clickable link to it. The plain view prints one line per fact with no color and no cursor moves, for logs, pipes, CI, ``NO_COLOR`` and ``TERM=dumb``. The engine's exact terms stay in each run's ``REPORT.md``. @@ -21,6 +22,7 @@ from pathlib import Path from typing import IO, Any, Iterator, Mapping, Optional, Sequence +from openadapt.quickstart import restart_view from openadapt.quickstart.engine import BreakFacts, DemoStep, RunFacts from openadapt.quickstart.notices import ( Notices, @@ -39,7 +41,7 @@ #: Width of the run-note column, so times line up. _LABEL_WIDTH = 40 -#: The number of steps in the story (the app, show, compile, run, break). +#: The number of steps in the story (the app, show, compile, run, act 3). STEPS = 5 #: Below this many columns the screen and the record stack instead of sitting #: side by side. @@ -129,7 +131,7 @@ def run_status(run: RunFacts, marks: Marks, scene: Scene = MOCKMED) -> str: def skipped_break_line(scene: Scene = MOCKMED) -> str: """Why Act 3 didn't run when no run got a ready screen.""" - return f"Skipped the last part ({scene.break_title.lower()}): it would stop the same way." + return f"Skipped the last part ({scene.act3_title.lower()}): it would stop the same way." def runs_total_line(outcome: Outcome, marks: Marks) -> str: @@ -148,12 +150,6 @@ def database_line(broken: BreakFacts, scene: Scene = MOCKMED) -> str: return scene.database_line(broken) -def bot_verdict(broken: BreakFacts, marks: Marks) -> Optional[str]: - """What a tool that trusts the screen would report, when the screen said so.""" - - return f"{marks.ok} Done" if broken.screen_showed_success else None - - def openadapt_verdict(broken: BreakFacts, marks: Marks, scene: Scene = MOCKMED) -> str: if broken.stopped: return f"{marks.stop} {scene.verdict(broken)}" @@ -240,7 +236,11 @@ def all_clear_runs(outcome: Outcome) -> bool: def all_clear(outcome: Outcome) -> bool: broke_ok = outcome.broken is None or outcome.broken.stopped - return all_clear_runs(outcome) and broke_ok + # A restart that couldn't run (no second process) isn't a failure; one + # that ran and went another way is. + restart = outcome.restart + restart_ok = restart is None or bool(restart.error) or restart.held + return all_clear_runs(outcome) and broke_ok and restart_ok def clean_title(outcome: Outcome) -> str: @@ -362,18 +362,12 @@ def seal_page_note(outcome: Outcome) -> str: def publish_runs(outcome: Outcome) -> list[Path]: - """The runs whose Seals the finale offers: the first checked run, then the - stopped run when Act 3 signed one. The stopped run is the point of the - quickstart, so it goes online with the checked run or not at all.""" + """The runs whose Seals the finale offers: the first checked run.""" page = outcome.seal_pages.verified if outcome.seal is None or page is None: return [] - runs = [page.parent] - broken = outcome.seal_pages.broken - if broken is not None and (broken.parent / "seal.json").is_file(): - runs.append(broken.parent) - return runs + return [page.parent] def next_step(steps: NextSteps) -> tuple[str, str, str]: @@ -406,9 +400,14 @@ def failure_step(outcome: Outcome) -> tuple[str, str]: ) if outcome.broken is not None: return ( - "The broken save didn't stop the program. Read its report", + "The referral didn't stop the program. Read its report", str(display_path(outcome.broken.report_md)), ) + if outcome.restart is not None and not outcome.restart.held: + return ( + "The restart didn't go as expected. Read its reports", + str(display_path(outcome.restart.ledger.parent.parent)), + ) return ("Nothing ran. Read the reports", str(display_path(outcome.root))) @@ -585,7 +584,7 @@ def act(self, number: int, title: str, subtitle: str) -> None: self._step(4, f"{heading} {dot} {how}" if how else heading) else: self._say() - self._step(5, self.scene.break_title) + self._step(5, self.scene.act3_title) def demo_step(self, step: DemoStep) -> None: self._demo.append(step) @@ -634,8 +633,8 @@ def not_ready(self, explanation: str, skipped_break: bool) -> None: if skipped_break: self._say(f" {skipped_break_line(self.scene)}") - def break_setup(self) -> None: - self._say(f" {self.scene.break_setup}") + def act3_setup(self) -> None: + self._say(f" {self.scene.act3_setup}") def _ask(self, prompt: str) -> str: self.stream.write(f" {prompt}") @@ -655,24 +654,24 @@ def confirm(self, prompt: str) -> None: except EOFError: self._say() - def breaking(self): + def act3_running(self): return self._quiet() + def restart_result(self, facts: Any) -> None: + for line in restart_view.plain_lines(facts, self.marks): + self._say(f" {line}") + summary = restart_view.summary_line(facts) + if summary: + self._say() + self._say(summary) + def break_result(self, broken: BreakFacts) -> None: scene = self.scene - labels = ( - "The screen:", - f"{scene.record_title}:", - "A screen-trusting bot:", - "OpenAdapt:", - ) + labels = ("The screen:", f"{scene.record_title}:", "OpenAdapt:") width = max(len(label) for label in labels) + 2 - screen, record, bot_label, openadapt = (f"{label:<{width}}" for label in labels) + screen, record, openadapt = (f"{label:<{width}}" for label in labels) self._say(f" {screen}{scene.screen_line(broken)}") self._say(f" {record}{database_line(broken, scene)}") - bot = bot_verdict(broken, self.marks) - if bot: - self._say(f" {bot_label}{bot}") self._say( f" {openadapt}{openadapt_verdict(broken, self.marks, scene)}" f" {seconds(broken.seconds)}" @@ -1124,12 +1123,12 @@ def not_ready(self, explanation: str, skipped_break: bool) -> None: if skipped_break: self.console.print(f"[dim]{_escape(skipped_break_line(self.scene))}[/]") - def break_setup(self) -> None: + def act3_setup(self) -> None: self._step_line( self.marks.arrow, "bold yellow", - self.scene.break_title, - self.scene.break_setup, + self.scene.act3_title, + self.scene.act3_setup, ) def _ask(self, prompt: str) -> str: @@ -1141,8 +1140,41 @@ def confirm(self, prompt: str) -> None: except EOFError: self.console.print() - def breaking(self): - return self._spinning(self.scene.break_title, self.scene.breaking) + def act3_running(self): + return self._spinning(self.scene.act3_title, self.scene.act3_running) + + def restart_result(self, facts: Any) -> None: + if facts.error: + self.console.print( + f"[yellow]{_escape(restart_view.skipped_line(facts))}[/]" + ) + return + total = len(facts.notes) + + def row(run: Any) -> None: + if run.skipped: + tone = "cyan" + else: + tone = "green" if run.checked else "red" + text = restart_view.note_row(run, total, self.marks) + self.console.print(f" [{tone}]{_escape(text)}[/]") + + for run in facts.before: + row(run) + tone = "bold yellow" if facts.killed else "bold red" + stop = restart_view.stop_line(facts, self.marks) + self.console.print(f" [{tone}]{_escape(stop)}[/]") + self.console.print(" [bold]Restarted with the same ledger:[/]") + for run in facts.after: + row(run) + tone = "green" if facts.held else "red" + copies = restart_view.copies_line(facts) + self.console.print(f" [bold]The database:[/] [{tone}]{_escape(copies)}[/]") + self.console.print(f"[dim]{_escape(restart_view.why_line(facts))}[/]") + summary = restart_view.summary_line(facts) + if summary: + self.console.print() + self.console.print(_escape(summary)) def break_result(self, broken: BreakFacts) -> None: # The screen and the record as text, in every terminal; the @@ -1155,12 +1187,7 @@ def break_result(self, broken: BreakFacts) -> None: self._verdicts(broken) def _record_text(self, broken: BreakFacts) -> str: - """The record's line: a red cross only where the screen claimed a save.""" - - line = _escape(database_line(broken, self.scene)) - if self.scene.screen_claims_success: - return f"[bold red]{self.marks.no} {line}[/]" - return f"[bold]{line}[/]" + return f"[bold]{_escape(database_line(broken, self.scene))}[/]" def _side_by_side(self, broken: BreakFacts) -> None: from rich.panel import Panel @@ -1168,19 +1195,18 @@ def _side_by_side(self, broken: BreakFacts) -> None: scene = self.scene quote = scene.screen_words(broken) - claims = scene.screen_claims_success and broken.screen_showed_success screen = Panel( - f"[green]{self.marks.ok}[/] {_escape(quote)}" if claims else _escape(quote), + _escape(quote), title="[bold]The screen[/]", title_align="left", - border_style="green" if claims else "dim", + border_style="dim", padding=(1, 2), ) record = Panel( self._record_text(broken), title=f"[bold]{_escape(scene.record_title)}[/]", title_align="left", - border_style="red" if scene.screen_claims_success else "dim", + border_style="dim", padding=(1, 2), ) self.console.print() @@ -1208,9 +1234,6 @@ def _verdicts(self, broken: BreakFacts) -> None: grid = Table.grid(padding=(0, 2)) grid.add_column(no_wrap=True) grid.add_column() - bot = bot_verdict(broken, self.marks) - if bot: - grid.add_row("[dim]A screen-trusting bot[/]", f"[red]{_escape(bot)}[/]") verdict = openadapt_verdict(broken, self.marks, scene) style = "bold yellow" if broken.stopped else "bold red" grid.add_row( @@ -1222,9 +1245,9 @@ def _verdicts(self, broken: BreakFacts) -> None: reconcile = reconcile_line(broken) if reconcile: self.console.print(f"[dim]{_escape(reconcile)}[/]") - # Where the screen showed no false success (OpenEMR), the side by - # side doesn't say what replaying the clicks would have done. - aha = None if scene.screen_claims_success else aha_line(broken, scene) + # The side by side doesn't say what replaying the clicks would have + # done; this line does. + aha = aha_line(broken, scene) if aha: self.console.print() self.console.print(_escape(aha)) diff --git a/packages/agent/README.md b/packages/agent/README.md index aabdcf2354..7072d32205 100644 --- a/packages/agent/README.md +++ b/packages/agent/README.md @@ -188,7 +188,7 @@ The sandbox has all three tools. With your own workflows, `run_workflow` appears The package is a local Model Context Protocol (MCP) server that talks over stdio, plus an `openadapt-agent` command. It needs Python 3.11 or 3.12. It checks inputs, stops second entries, and turns Flow's report into one of the four outcomes. [openadapt-flow](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/flow) records, replays, and checks the workflows. -To see Flow on its own, install the OpenAdapt launcher with `pip install openadapt`, then run `openadapt flow tutorial` or `openadapt quickstart --break-it`. +To see Flow on its own, install the OpenAdapt launcher with `pip install openadapt`, then run `openadapt flow tutorial` or `openadapt quickstart`. ### Connect your own agent diff --git a/scripts/capture_quickstart_pty.py b/scripts/capture_quickstart_pty.py index f985b1db80..c41d97ef03 100644 --- a/scripts/capture_quickstart_pty.py +++ b/scripts/capture_quickstart_pty.py @@ -8,7 +8,7 @@ Usage: python scripts/capture_quickstart_pty.py --out DIR --name NAME \ - --term-program Apple_Terminal --cols 120 -- openadapt quickstart --break-it + --term-program Apple_Terminal --cols 120 -- openadapt quickstart """ from __future__ import annotations diff --git a/scripts/record_quickstart.py b/scripts/record_quickstart.py index 7786faff27..0dfdb8878a 100644 --- a/scripts/record_quickstart.py +++ b/scripts/record_quickstart.py @@ -96,7 +96,7 @@ def main(argv: list[str] | None = None) -> int: for view in views[1:]: view._notices = views[0]._notices engine = FlowEngine(root, visible=False) - outcome = run_story(engine, tee, next_steps=steps, break_it=True) + outcome = run_story(engine, tee, next_steps=steps, last_act=True) for width, console in consoles.items(): title = f"openadapt quickstart ({width} columns)" diff --git a/tests/fixtures/cli_surface.json b/tests/fixtures/cli_surface.json index 4d300026b9..41a5c3dc0b 100644 --- a/tests/fixtures/cli_surface.json +++ b/tests/fixtures/cli_surface.json @@ -1,7 +1,7 @@ { "click": "8.5.0", "help": { - "openadapt": "Usage: openadapt [OPTIONS] COMMAND [ARGS]...\n\n Record, compile and run workflows with OpenAdapt.\n\n Compile a demonstrated workflow into deterministic local replay. Healthy runs make no model calls;\n configured checks can halt on ambiguity. Native and remote substrates use platform-specific extras\n and permissions; training/evaluation commands are research.\n\n Quick Start (uv fetches Python 3.12 if needed):\n uvx --python 3.12 openadapt@latest quickstart\n Or, on Python 3.11-3.12:\n python -m pip install --upgrade openadapt\n openadapt quickstart\n\n Manual Demo Lifecycle:\n openadapt flow demo-record --out rec\n openadapt compile rec --out bundle --name demo\n openadapt flow lint bundle\n openadapt flow certify bundle --policy permissive\n openadapt flow replay bundle --demo-app\n\n Lint lists the demo's coverage gaps. The demo has warnings, so `lint --strict` exits 1 on it. The\n manual demo is runnable but not certified for consequential work. Use `openadapt flow tutorial`\n for the effect-verified first run.\n\n Give an MCP client your compiled workflows:\n openadapt agent serve --bundles DIR --mode production\n\nOptions:\n --version Show the version and exit.\n --help Show this message and exit.\n\nCommands:\n demo Try the demonstration and tutorial\n verify Check effects, receipts, and evidence\n record Record a task and its narration\n teach Teach a correction to a stopped workflow\n compile Compile and prepare workflow bundles\n run Run, resume, and route workflows\n approve Review and approve paused work\n undo Declare and run approved undo steps\n qualify Qualify a workflow for its intended use\n repair Review, test, and promote repairs\n inspect Inspect workflows, runs, and reports\n workflow Manage reusable workflow libraries\n services Run local services and connectors\n setup Configure connections, privacy, and access\n research Run benchmarks and research tools\n kernel Run the commit-boundary runtime (optional alpha extra)\n mcpify Serve compiled workflow packs or JIT plans as a local MCP server\n wrap Run an agent task once, then reuse its checked compiled tool\n test Test an agent on real apps with planted faults, for CI\n audit Sample verified runs for statistical compliance spot-checks\n\nLegacy commands:\n agent Serve compiled workflows to an MCP client...\n bench Public benchmarks you can rerun with your...\n capture Standalone local human GUI capture...\n cohort-receipt Build or verify a zero-PHI Ed25519 Merkle...\n connect Connect this computer or VPC runner to...\n deploy Check this host and print the safe...\n doctor Check system requirements and dependencies.\n eval Research: evaluate computer-use models on...\n flight Record any agent you already run, and hold...\n flow Run the canonical demonstration compiler...\n handoff Hand a result to another agent with its...\n hooks Check a coding agent's writes to declared...\n login Sign in to OpenAdapt Cloud: `openadapt...\n plan Legacy (superseded by `openadapt kernel`):...\n pool Manage containerized xfreerdp3 + Xvfb...\n proxy Legacy (superseded by `openadapt kernel`):...\n pull Download a packaged workflow: `openadapt...\n quickstart Show a task once, run it, then watch it...\n receipt Check, view and share a run's receipt:...\n serve Research: serve the training dashboard and...\n shadow Check each write your agent makes against...\n support-bundle Redact a run directory into a...\n train Research: train ML models on captured...\n trust Manage customer-owned Ed25519 signing keys.\n version Show version information for all packages.", + "openadapt": "Usage: openadapt [OPTIONS] COMMAND [ARGS]...\n\n Record, compile and run workflows with OpenAdapt.\n\n Compile a demonstrated workflow into deterministic local replay. Healthy runs make no model calls;\n configured checks can halt on ambiguity. Native and remote substrates use platform-specific extras\n and permissions; training/evaluation commands are research.\n\n Quick Start (uv fetches Python 3.12 if needed):\n uvx --python 3.12 openadapt@latest quickstart\n Or, on Python 3.11-3.12:\n python -m pip install --upgrade openadapt\n openadapt quickstart\n\n Manual Demo Lifecycle:\n openadapt flow demo-record --out rec\n openadapt compile rec --out bundle --name demo\n openadapt flow lint bundle\n openadapt flow certify bundle --policy permissive\n openadapt flow replay bundle --demo-app\n\n Lint lists the demo's coverage gaps. The demo has warnings, so `lint --strict` exits 1 on it. The\n manual demo is runnable but not certified for consequential work. Use `openadapt flow tutorial`\n for the effect-verified first run.\n\n Give an MCP client your compiled workflows:\n openadapt agent serve --bundles DIR --mode production\n\nOptions:\n --version Show the version and exit.\n --help Show this message and exit.\n\nCommands:\n demo Try the demonstration and tutorial\n verify Check effects, receipts, and evidence\n record Record a task and its narration\n teach Teach a correction to a stopped workflow\n compile Compile and prepare workflow bundles\n run Run, resume, and route workflows\n approve Review and approve paused work\n undo Declare and run approved undo steps\n qualify Qualify a workflow for its intended use\n repair Review, test, and promote repairs\n inspect Inspect workflows, runs, and reports\n workflow Manage reusable workflow libraries\n services Run local services and connectors\n setup Configure connections, privacy, and access\n research Run benchmarks and research tools\n kernel Run the commit-boundary runtime (optional alpha extra)\n mcpify Serve compiled workflow packs or JIT plans as a local MCP server\n wrap Run an agent task once, then reuse its checked compiled tool\n test Test an agent on real apps with planted faults, for CI\n audit Sample verified runs for statistical compliance spot-checks\n\nLegacy commands:\n agent Serve compiled workflows to an MCP client...\n bench Public benchmarks you can rerun with your...\n capture Standalone local human GUI capture...\n cohort-receipt Build or verify a zero-PHI Ed25519 Merkle...\n connect Connect this computer or VPC runner to...\n deploy Check this host and print the safe...\n doctor Check system requirements and dependencies.\n eval Research: evaluate computer-use models on...\n flight Record any agent you already run, and hold...\n flow Run the canonical demonstration compiler...\n handoff Hand a result to another agent with its...\n hooks Check a coding agent's writes to declared...\n login Sign in to OpenAdapt Cloud: `openadapt...\n plan Legacy (superseded by `openadapt kernel`):...\n pool Manage containerized xfreerdp3 + Xvfb...\n proxy Legacy (superseded by `openadapt kernel`):...\n pull Download a packaged workflow: `openadapt...\n quickstart Show a task once, run it, then stop it...\n receipt Check, view and share a run's receipt:...\n serve Research: serve the training dashboard and...\n shadow Check each write your agent makes against...\n support-bundle Redact a run directory into a...\n train Research: train ML models on captured...\n trust Manage customer-owned Ed25519 signing keys.\n version Show version information for all packages.", "openadapt approve": "Usage: openadapt approve [OPTIONS]\n\n Run the canonical demonstration compiler and governed runtime.\n\n Every argument passes to openadapt-flow unchanged. This keeps the launcher command list, help,\n options, validation, and exit codes identical to the installed engine version.\n\nOptions:\n --help Show this message and exit.", "openadapt audit": "Usage: openadapt audit [OPTIONS] COMMAND [ARGS]...\n\n Sample verified runs for statistical compliance spot-checks.\n\nOptions:\n --help Show this message and exit.\n\nCommands:\n sample Draw a random statistical spot-check sample of verified runs.", "openadapt audit sample": "Usage: openadapt audit sample [OPTIONS]\n\n Draw a random statistical spot-check sample of verified runs.\n\nOptions:\n --receipts-dir, --input PATH Path to receipts directory or JSONL ledger (default:\n ~/.openadapt/verify).\n --rate FLOAT Fraction of eligible runs to sample, in (0.0, 1.0]. [default:\n 0.05]\n --count INTEGER Explicit number of runs to sample instead of using --rate.\n --min-samples INTEGER Minimum number of runs to sample (capped at eligible count).\n --max-samples INTEGER Maximum number of runs to sample.\n --since TEXT Include only runs at or after this ISO date/timestamp or window\n (e.g. 7d, 24h).\n --seed TEXT Deterministic seed for reproducible sampling (omit for\n cryptographic random sampling).\n --status TEXT Run status filter (case-insensitive, comma-separated, or ALL).\n [default: VERIFIED]\n --out PATH Write an audit_sample_v1 manifest to a JSON or JSONL file.\n --json Print the audit_sample_v1 manifest as JSON to stdout.\n --exclude-already-sampled PATH Exclude run IDs and digests already in a prior manifest or ledger\n (repeatable).\n --help Show this message and exit.", diff --git a/tests/snapshots/quickstart_openemr_plain.snapshot b/tests/snapshots/quickstart_openemr_plain.snapshot index bc685cd92e..a31baa9691 100644 --- a/tests/snapshots/quickstart_openemr_plain.snapshot +++ b/tests/snapshots/quickstart_openemr_plain.snapshot @@ -22,9 +22,9 @@ Synthetic data only. Files go to openadapt-quickstart [5/5] Try a referral that matches a chart OpenEMR already has a chart for Rosa Delgado. The next referral is a Rosa Delgado with another birth date. - The screen: "a matching chart: Delgado, Rosa, born 1958-03-27" - OpenEMR's record: 0 new charts - OpenAdapt: ■ Stopped before saving: possible duplicate 24.5s + The screen: "a matching chart: Delgado, Rosa, born 1958-03-27" + OpenEMR's record: 0 new charts + OpenAdapt: ■ Stopped before saving: possible duplicate 24.5s Why: OpenEMR's duplicate check found an existing chart. The program saves only when it finds none, so it stopped before saving. The demonstration clicked Confirm Create New Patient here. Replaying those clicks would have saved a possible duplicate. OpenAdapt stopped. diff --git a/tests/snapshots/quickstart_plain.snapshot b/tests/snapshots/quickstart_plain.snapshot index 435ec845ca..19ee886e8e 100644 --- a/tests/snapshots/quickstart_plain.snapshot +++ b/tests/snapshots/quickstart_plain.snapshot @@ -1,4 +1,4 @@ -OpenAdapt quickstart: show a task once, run it, then watch it catch a save that didn't happen. +OpenAdapt quickstart: show a task once, run it, then stop it mid-batch and watch the restart skip what was already saved. Synthetic data only. Files go to openadapt-quickstart [1/5] ✓ Clinic app ready · synthetic data, on this computer @@ -25,20 +25,21 @@ Synthetic data only. Files go to openadapt-quickstart ✓ note "Follow-up in two weeks" 5 of 5 runs · 0 model calls · $0.00 · 0.5s -[5/5] Break the next save - The app will show its saved message. The database will reject the save. - The screen: "Encounter saved — Synthetic follow-up in two weeks" - The database: 0 new records - A screen-trusting bot: ✓ Done - OpenAdapt: ■ Stopped. Not marked done. 7.7s - Why: OpenAdapt reads the record back from the database after each save. It found nothing, so it stopped. - A save may still have gone through, so a person checks the record before anything is retried. +[5/5] Stop it mid-batch, then restart + A batch of 2 new notes, each in its own copy of the clinic's database. The runner process is stopped hard after note 1 saves, then started again. + 1/2 Refer to physical therapy ✓ checked in the database 3.1s + ■ Runner process stopped with SIGKILL after note 1, before note 2 + Restarted with the same ledger: + 1/2 Refer to physical therapy · Skipped: the ledger has it as done, no save sent 0.4s + 2/2 Repeat labs before next visit ✓ checked in the database 3.2s + The database: each note saved once (note 1: 1 record, note 2: 1 record) + Why: OpenAdapt records each note in a ledger on disk before it saves it, and records the outcome after the record check. On restart it found note 1 marked done, so it sent no save for note 1 and saved only note 2. -The screen said "Encounter saved". The database had nothing. A bot that trusts the screen reports Done. OpenAdapt stopped. +The runner was killed partway through the batch. On restart, OpenAdapt sent no save for note 1 and saved note 2. Your receipt: Signed Signed by this computer - key seal-ed25519-0123456789abcdef · 6 reports signed + key seal-ed25519-0123456789abcdef · 5 reports signed Open it: openadapt-quickstart/run-1/seal.html checks the signature in your browser, offline; nothing is uploaded Real receipts from OpenEMR runs: https://openadapt.ai/seals @@ -49,4 +50,4 @@ Next: Give your agent this task as a tool Your own app: openadapt record --backend web --url https://your-app.example --out my-task Playwright/CUA drop-in: with checked_write("verify.yaml", values): ... # from openadapt_verify More next steps: openadapt quickstart --more -Done in 2.5s. Reports: openadapt-quickstart, one REPORT.md per run; side by side: openadapt-quickstart/index.html +Done in 2.5s. Reports: openadapt-quickstart, one REPORT.md per run diff --git a/tests/test_cli_quickstart_polish.py b/tests/test_cli_quickstart_polish.py index 10e8860c2c..24cfbb80f4 100644 --- a/tests/test_cli_quickstart_polish.py +++ b/tests/test_cli_quickstart_polish.py @@ -80,10 +80,11 @@ def test_explicit_out_is_honored_verbatim(story_calls): @pytest.mark.parametrize( ("argv", "expected"), [ - ([], {"break_it": True, "verbose": False}), - (["--no-break"], {"break_it": False}), + ([], {"last_act": True, "verbose": False}), + (["--no-restart"], {"last_act": False}), + # The old name still works. + (["--no-break"], {"last_act": False}), (["--verbose"], {"verbose": True}), - (["--break-it"], {"break_it": True}), ], ) def test_quickstart_options_reach_the_story(story_calls, monkeypatch, argv, expected): diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py index be4f811ba4..11fcd2814a 100644 --- a/tests/test_quickstart.py +++ b/tests/test_quickstart.py @@ -1,5 +1,9 @@ """`openadapt quickstart`: three acts, plain and live output, honest numbers. +Act 3 on MockMed stops the runner mid-batch and restarts it; the fake engine +returns the restart's facts. ``act3="break"`` gives the fake OpenEMR's Act 3 +(a referral that matches a chart) instead. + The story runs against a fake engine here, so these tests take milliseconds. The fake returns whatever facts a test gives it, and the output must follow: nothing the quickstart prints may be a constant standing in for a run. The @@ -45,12 +49,14 @@ detect_image_protocol, image_sequence, ) +from openadapt.quickstart.restart import NoteRun, RestartFacts +from openadapt.quickstart.scene import MOCKMED, OPENEMR from openadapt.quickstart.story import NextSteps, Outcome, run_story from openadapt.quickstart.view import Marks, PlainView, RichView, make_view, more_lines SNAPSHOT = Path(__file__).parent / "snapshots" / "quickstart_plain.snapshot" -SCREEN_TEXT = "Encounter saved — Synthetic follow-up in two weeks" +SCREEN_TEXT = "Possible duplicate: Rosa Delgado" DEMO = [ ("Click Open", 0.4), @@ -100,16 +106,16 @@ def _run(root: Path, index: int, **overrides) -> RunFacts: def _broken(root: Path, **overrides) -> BreakFacts: facts = BreakFacts( run_dir=root / "run-broken", - fault="optimistic", + fault="possible duplicate", execution_outcome="HALTED", transaction_outcome="RECONCILIATION_REQUIRED", - screen_showed_success=True, + screen_showed_success=False, screen_text=SCREEN_TEXT, screenshot=None, new_records=0, effects_required=2, - effects_refuted=1, - halt_reason="record_written refuted", + effects_refuted=0, + halt_reason="duplicate check listed a match", model_calls=0, seconds=7.7, stop_attributed=True, @@ -117,6 +123,52 @@ def _broken(root: Path, **overrides) -> BreakFacts: return replace(facts, **overrides) +def _note(root: Path, index: int, folder: str, **overrides) -> NoteRun: + run = NoteRun( + index=index, + note=RUN_NOTES[index + 1], + run_dir=root / "restart" / folder, + execution_outcome="VERIFIED", + transaction_outcome="VERIFIED", + checked=True, + skipped=False, + ledger_outcome="VERIFIED", + actions=6, + model_calls=0, + seconds=3.0 + index / 10, + ) + return replace(run, **overrides) + + +def _restart(root: Path, **overrides) -> RestartFacts: + """A restart that went as planned, unless ``overrides`` say otherwise.""" + + facts = RestartFacts( + notes=list(RUN_NOTES[2:4]), + ledger=root / "restart" / "ledger" / "writes.sqlite", + before=[_note(root, 1, "note-1")], + killed=True, + signal="SIGKILL", + after=[ + _note( + root, + 1, + "note-1-restart", + execution_outcome="HALTED", + transaction_outcome="REJECTED_POLICY", + checked=False, + skipped=True, + actions=0, + seconds=0.4, + ), + _note(root, 2, "note-2-restart"), + ], + copies=[1, 1], + seconds=9.0, + ) + return replace(facts, **overrides) + + class FakeEngine: """Stands in for the browser and the engine; returns the facts it's given.""" @@ -127,6 +179,8 @@ def __init__( visible: bool = False, runs: Optional[dict[int, dict]] = None, broken: Optional[dict] = None, + restart: Optional[dict] = None, + act3: str = "restart", program_steps: int = 6, seal: Optional[SealFacts] = SealFacts("seal-ed25519-0123456789abcdef", 5), page: bool = True, @@ -141,6 +195,14 @@ def __init__( self.visible = visible self._runs = runs or {} self._broken = broken or {} + self._restart = restart or {} + if act3 == "break": + # OpenEMR's Act 3: the story finds no restart and runs break_it. + self.scene = OPENEMR + self.crash_restart = None + self.prepare_restart = None + else: + self.scene = MOCKMED self._program_steps = program_steps self._seal = seal self._page = page @@ -194,6 +256,13 @@ def run_all(self, notes, on_finish): def before_prompt(self): self.calls.append("before prompt") + def prepare_restart(self): + self.calls.append("prepare restart") + + def crash_restart(self): + self.calls.append("restart") + return _restart(self.root, **self._restart) + def break_it(self): self.calls.append("break") broken = dict(self._broken) @@ -209,18 +278,11 @@ def seal(self, runs): return None return SealFacts(self._seal.key_id, sum(1 for run in runs if run.checked)) - def seal_broken(self, broken): - self.calls.append("seal broken") - return True - - def seal_pages(self, runs, broken, command=None): + def seal_pages(self, runs, command=None): self.calls.append("seal pages") self.seal_command = command(self.root / "run-1") if command else None first = next((run for run in runs if run.checked), None) - return SealPages( - verified=first.run_dir / "seal.html" if first else None, - broken=broken.run_dir / "seal.html" if broken else None, - ) + return SealPages(verified=first.run_dir / "seal.html" if first else None) def write_page(self, first, broken): self.calls.append("page") @@ -245,7 +307,7 @@ def _plain(engine, **kwargs) -> tuple[str, Outcome]: stream = io.StringIO() outcome = run_story( engine, - PlainView(stream), + PlainView(stream, scene=engine.scene), next_steps=_steps, clock=_clock(), **kwargs, @@ -280,13 +342,12 @@ def test_plain_output_runs_the_three_acts_in_order(root): assert [call for call in engine.calls if call != "seal"] == [ "enter", "start workers", + "prepare restart", "record", "compile", *(f"run {index}" for index in range(1, 6)), - "break", - "page", + "restart", "exit", - "seal broken", "seal pages", ] assert engine.calls.index("seal") > engine.calls.index("run 5") @@ -305,6 +366,7 @@ def test_plain_output_has_no_internal_vocabulary(root): "billable", "success rail", "RECONCILIATION_REQUIRED", + "REJECTED_POLICY", "HALTED", "VERIFIED", "system of record", @@ -316,9 +378,19 @@ def test_plain_output_has_no_internal_vocabulary(root): def test_verbose_adds_the_engine_detail(root): output, _ = _plain(FakeEngine(root), verbose=True) - assert "transaction RECONCILIATION_REQUIRED" in output - assert "engine: record_written refuted" in output + assert f"ledger {root / 'restart' / 'ledger' / 'writes.sqlite'}" in output + assert ( + "restart, note 1: execution HALTED, transaction REJECTED_POLICY, " + "idempotent replay True, ledger outcome VERIFIED, 0 actions" in output + ) assert str(root / "run-1" / "REPORT.md") in output + assert str(root / "restart" / "note-2-restart" / "REPORT.md") in output + + +def test_verbose_adds_openemrs_stop_detail(root): + output, _ = _plain(FakeEngine(root, act3="break"), verbose=True) + assert "transaction RECONCILIATION_REQUIRED" in output + assert "engine: duplicate check listed a match" in output def test_finale_has_one_next_step_and_the_rest_behind_more(root): @@ -374,13 +446,12 @@ def test_quickstart_more_prints_and_runs_nothing(tmp_path, monkeypatch): assert "openadapt-quickstart/run-1/seal.html" in result.output -def test_no_break_skips_act_three(root): +def test_no_restart_skips_act_three(root): engine = FakeEngine(root) - output, outcome = _plain(engine, break_it=False) - assert "Break it" not in output - assert "break" not in engine.calls - assert "page" not in engine.calls - assert outcome.broken is None + output, outcome = _plain(engine, last_act=False) + assert "restart" not in engine.calls + assert "prepare restart" not in engine.calls + assert outcome.restart is None and outcome.broken is None assert "[5/5]" not in output assert "Your receipt: " in output @@ -414,8 +485,8 @@ def test_numbers_follow_the_runs(root): assert "4 of 5 saved and checked · 3 AI calls · $0.04" in output assert "5 of 5" not in output assert "0 AI calls" not in output - # Four checked runs and the stopped one. - assert "key seal-ed25519-0123456789abcdef · 5 reports signed" in output + # The four checked runs. + assert "key seal-ed25519-0123456789abcdef · 4 reports signed" in output assert "■ 4 of 5 saved and checked" in output assert "4 of 5 runs · 3 model calls · $0.04 · " in output # A run that didn't check out replaces the next step with its report. @@ -431,53 +502,135 @@ def test_a_repeated_run_says_so(root): assert output.count("second try") == 1 -def test_the_aha_line_appears_only_when_the_run_showed_it(root): - shown, _ = _plain(FakeEngine(root)) +def test_act_three_shows_the_stop_the_skip_and_one_save_per_note(root): + output, outcome = _plain(FakeEngine(root)) + act = output[output.index("[5/5] ") :] + assert act.startswith("[5/5] Stop it mid-batch, then restart\n") + lines = [line.strip() for line in act.splitlines()] + at = lines.index( + "■ Runner process stopped with SIGKILL after note 1, before note 2" + ) + assert lines[at - 1].startswith("1/2 Refer to physical therapy") + assert lines[at - 1].endswith("✓ checked in the database 3.1s") + assert lines[at + 1] == "Restarted with the same ledger:" + assert "· Skipped: the ledger has it as done, no save sent 0.4s" in lines[at + 2] + assert lines[at + 3].startswith("2/2 Repeat labs before next visit") + assert lines[at + 4] == ( + "The database: each note saved once (note 1: 1 record, note 2: 1 record)" + ) assert ( - 'The screen said "Encounter saved". The database had nothing. A bot that ' - "trusts the screen reports Done. OpenAdapt stopped." in shown + "The runner was killed partway through the batch. On restart, " + "OpenAdapt sent no save for note 1 and saved note 2." in output + ) + assert outcome.restart is not None and outcome.restart.held + assert "Next: Give your agent this task as a tool" in output + + +@pytest.mark.parametrize( + ("overrides", "shown"), + [ + ({"copies": [2, 1]}, "note 1: 2 records, note 2: 1 record"), + ({"killed": False}, "✗ The runner was still running; it was not stopped"), + ({"before": []}, "stopped with SIGKILL before any note, before note 1"), + ], +) +def test_a_restart_that_went_another_way_says_what_happened(root, overrides, shown): + output, outcome = _plain(FakeEngine(root, restart=overrides)) + assert shown in output + assert "sent no save for note 1 and saved note 2" not in output + assert "didn't go as expected" in output + assert "Next: The restart didn't go as expected. Read its reports" in output + assert "claude mcp add" not in output + assert outcome.restart is not None and not outcome.restart.held + + +def test_an_error_after_the_stop_is_shown_and_fails_the_act(root): + output, outcome = _plain( + FakeEngine( + root, + restart={"after": [], "restart_error": "RuntimeError: gate refused"}, + ) + ) + assert "The restart stopped with an error (RuntimeError: gate refused)" in output + assert "Next: The restart didn't go as expected. Read its reports" in output + assert outcome.restart is not None and not outcome.restart.held + + +def test_a_restart_that_did_not_hold_fails_the_command(monkeypatch, tmp_path): + def fake(root, **kwargs): + outcome = Outcome(root=root) + outcome.runs = [_run(root, 1)] + outcome.restart = _restart(root, copies=[2, 1]) + return outcome + + monkeypatch.setattr("openadapt.quickstart.run_quickstart", fake) + monkeypatch.setattr("openadapt.cli._flow_runs_quickstart", lambda: True) + with CliRunner().isolated_filesystem(temp_dir=tmp_path): + result = CliRunner().invoke(cli.main, ["quickstart", "--out", "qs"]) + assert result.exit_code == 1 + + +def test_a_note_two_the_restart_skipped_is_not_a_success(root): + facts = _restart(root) + second = replace(facts.after[1], skipped=True, checked=False, actions=0) + output, _ = _plain( + FakeEngine(root, restart={"after": [facts.after[0], second], "copies": [1, 0]}) + ) + assert "note 2: 0 records" in output + assert "sent no save for note 1 and saved note 2" not in output + + +def test_a_restart_that_could_not_start_is_skipped_not_failed(root): + output, _ = _plain( + FakeEngine(root, restart={"error": "the second runner process didn't start"}) ) + assert "Skipped this part: the second runner process didn't start." in output + assert "Restarted with the same ledger" not in output + assert "Next: Give your agent this task as a tool" in output - landed, _ = _plain(FakeEngine(root, broken={"new_records": 1})) - assert "The database had nothing" not in landed - assert "1 new record" in landed - quiet, _ = _plain(FakeEngine(root, broken={"screen_showed_success": False})) - assert "A screen-trusting bot" not in quiet - assert "reports Done" not in quiet +def test_openemrs_summary_line_appears_only_when_the_run_showed_it(root): + shown, _ = _plain(FakeEngine(root, act3="break")) + assert "Replaying those clicks would have saved a possible duplicate." in shown + assert "■ Stopped before saving: possible duplicate" in shown - missed, _ = _plain(FakeEngine(root, broken={"execution_outcome": "VERIFIED"})) - assert "Not marked done" not in missed + landed, _ = _plain(FakeEngine(root, act3="break", broken={"new_records": 1})) + assert "would have saved a possible duplicate" not in landed + assert "1 new chart" in landed + + missed, _ = _plain( + FakeEngine(root, act3="break", broken={"execution_outcome": "VERIFIED"}) + ) + assert "Stopped before saving" not in missed assert "did not stop" in missed -def test_a_stop_the_record_check_did_not_cause_is_not_the_demonstration(root): +def test_a_stop_the_check_did_not_cause_is_not_the_demonstration(root): # Codex review on #1431: a halt for another reason (here a readiness halt - # before the save, nothing refuted, nothing read off the screen) must not - # read as the record check catching the silent failure. + # before the save, nothing read off the screen) must not read as this + # act's check stopping it. output, _ = _plain( FakeEngine( root, + act3="break", broken={ "screen_text": None, - "screen_showed_success": False, - "effects_refuted": 0, "stop_attributed": False, "transaction_outcome": "HALTED_BEFORE_EFFECT", "halt_reason": "readiness: the page never settled before step_000", }, ) ) - assert "It found nothing" not in output - assert "reports Done" not in output - assert "a saved message" not in output, "the screen was never observed" - assert "Not marked done" not in output + assert "duplicate check found an existing chart" not in output + assert "listing a matching chart" not in output, "the screen was never observed" + assert "Stopped before saving" not in output assert "not at the check this act sets off" in output def test_an_engine_without_run_inputs_does_not_claim_new_notes(root): output, _ = _plain(FakeEngine(root, note_param=False)) - assert "new notes" not in output + # Act 3's batch always gives each run its note; Act 2 is what this checks. + assert "new notes" not in output[: output.index("[5/5]")] assert "[4/5] Run it 5 times · all at once" in output @@ -515,34 +668,21 @@ def test_the_finale_names_the_persons_own_seal_then_the_real_ones(root): # The person's own Seal opens; the side-by-side page does not. assert opened == [root / "run-1" / "seal.html"] assert outcome.seal_page_opened - assert outcome.seal_pages.broken == root / "run-broken" / "seal.html" - assert "side by side: openadapt-quickstart/index.html\n" in output + assert "side by side" not in output # The page's own command checks that run folder. assert engine.seal_command == "openadapt verify openadapt-quickstart/run-1" def test_a_seal_page_that_fails_leaves_the_seal_and_no_page_line(root): class NoPages(FakeEngine): - def seal_pages(self, runs, broken, command=None): + def seal_pages(self, runs, command=None): raise RuntimeError("no viewer") output, outcome = _plain(NoPages(root), open_page=lambda page: True) assert "Open it" not in output - # The stopped run's Seal was written, so it counts without its page. - assert "key seal-ed25519-0123456789abcdef · 6 reports signed" in output - assert not outcome.seal_page_opened - - -def test_the_stopped_run_counts_only_when_its_seal_was_written(root): - class NoBrokenSeal(FakeEngine): - def seal_broken(self, broken): - raise RuntimeError("key_unavailable") - - output, outcome = _plain(NoBrokenSeal(root), open_page=lambda page: True) + # The runs' Seals were written, so they count without a page. assert "key seal-ed25519-0123456789abcdef · 5 reports signed" in output - # The person's own Seal page is still written and opened. - assert " Open it: openadapt-quickstart/run-1/seal.html" in output - assert outcome.seal_page_opened + assert not outcome.seal_page_opened def test_quickstart_exit_code_follows_the_runs(monkeypatch, tmp_path): @@ -571,10 +711,10 @@ def test_no_prompt_without_a_terminal(root, monkeypatch): monkeypatch.setattr("openadapt.quickstart.engine.display_available", lambda: False) stream = io.StringIO() run_quickstart( - root, visible=False, break_it=True, verbose=False, steps=_steps, stream=stream + root, visible=False, last_act=True, verbose=False, steps=_steps, stream=stream ) assert "Press Enter" not in stream.getvalue() - assert "[5/5] Break the next save" in stream.getvalue() + assert "[5/5] Stop it mid-batch, then restart" in stream.getvalue() def test_a_terminal_gets_the_prompt_and_waiting_is_not_counted(root, monkeypatch): @@ -596,7 +736,7 @@ def enter(*args): clock=lambda: next(clock_values), ) assert asked == [True] - assert "Press Enter to make the next save fail silently" in stream.getvalue() + assert "Press Enter to start the batch" in stream.getvalue() # 106 s elapsed, 100 s of it waiting at the prompt. assert outcome.total_seconds == pytest.approx(6.0) @@ -656,7 +796,7 @@ def eof(*args): outcome = run_story( FakeEngine(root), PlainView(output), next_steps=_steps, interactive=True ) - assert outcome.broken is not None + assert outcome.restart is not None # --------------------------------------------------------------------------- @@ -700,9 +840,12 @@ def test_terminals_without_unicode_get_ascii_marks(root): def _rich(root, environ, width: int = 110, **engine_kwargs) -> str: stream = _Terminal() - view = RichView(stream, environ=environ, width=width, animate=False) + engine = FakeEngine(root, **engine_kwargs) + view = RichView( + stream, environ=environ, width=width, animate=False, scene=engine.scene + ) run_story( - FakeEngine(root, **engine_kwargs), + engine, view, next_steps=_steps, clock=_clock(), @@ -745,12 +888,11 @@ def test_terminal_view_tells_the_story_with_boxes_and_one_next_step(root): assert "Open › New Encounter › Triage › Note" in text assert "─ Saved and checked ─" in text assert '✓ note "Follow-up in two weeks"' in text - assert "╭─ The screen" in text and "╭─ The database" in text - assert "Encounter saved — Synthetic" in text - assert "✗ 0 new records" in text - assert "A screen-trusting bot ✓ Done" in text - assert "■ Stopped. Not marked done." in text - assert "a person checks the record before anything is retried" in text + assert "Stop it mid-batch, then restart" in text + assert "■ Runner process stopped with SIGKILL after note 1, before note 2" in text + assert "Skipped: the ledger has it as done, no save sent" in text + assert "The database: each note saved once" in text + assert "The screen" not in text assert "◆ Your receipt" in text and "●─●─●─●─●─◆" in text assert "claude mcp add openadapt -- openadapt agent serve --allow-run" in text assert text.count("Next ") == 1 @@ -789,8 +931,6 @@ def test_narrow_terminal_stacks_and_never_boxes_a_wrapped_command(root): f"Open it {seal}", "› claude mcp add openadapt -- openadapt agent serve --allow-run", ] - # The screen and the record stack: no line holds both boxes. - assert not any("The screen" in line and "The database" in line for line in lines) assert "› claude mcp add openadapt -- openadapt agent serve --allow-run" in output @@ -853,11 +993,11 @@ def test_terminal_view_draws_the_screenshot_where_supported(root, protocol, mark root.mkdir() shot = _png(root / "shot.png", 1280, 800) environ = {"OPENADAPT_INLINE_IMAGES": protocol} - output = _rich(root, environ, broken={"screenshot": shot}) + output = _rich(root, environ, act3="break", broken={"screenshot": shot}) assert marker in output # The text boxes come first in every terminal; the screenshot is extra. visible = _visible(output) - assert "╭─ The screen" in visible and "The database" in visible + assert "╭─ The screen" in visible and "OpenEMR's record" in visible assert visible.index("╭─ The screen") < visible.index("The screen's screenshot") @@ -878,15 +1018,17 @@ def test_terminal_view_shows_the_screen_as_text_without_a_confirmed_protocol( root.mkdir() shot = _png(root / "shot.png", 1280, 800) - output = _rich(root, environ, broken={"screenshot": shot}) + output = _rich(root, environ, act3="break", broken={"screenshot": shot}) assert "\x1b]1337;" not in output and "\x1b_G" not in output visible = _visible(output) - assert "╭─ The screen" in visible and "The database" in visible + assert "╭─ The screen" in visible and "OpenEMR's record" in visible assert "The screen's screenshot" not in visible def test_terminal_view_falls_back_when_the_screenshot_is_missing(root): - output = _rich(root, {"TERM_PROGRAM": "iTerm.app"}, broken={"screenshot": None}) + output = _rich( + root, {"TERM_PROGRAM": "iTerm.app"}, act3="break", broken={"screenshot": None} + ) assert "\x1b]1337;" not in output assert "╭─ The screen" in _visible(output) @@ -1179,7 +1321,7 @@ def test_real_quickstart(tmp_path, monkeypatch, capfd): outcome = run_quickstart( root, visible=False, - break_it=True, + last_act=True, verbose=False, steps=_steps, stream=stream, @@ -1190,9 +1332,11 @@ def test_real_quickstart(tmp_path, monkeypatch, capfd): runs = len(FlowEngine.inputs) assert outcome.checked == runs, output assert outcome.model_calls == 0 - assert outcome.broken is not None and outcome.broken.stopped - assert outcome.broken.new_records == 0 - assert outcome.broken.transaction_outcome == "RECONCILIATION_REQUIRED" + restart = outcome.restart + assert restart is not None and restart.held, output + assert restart.killed and restart.copies == [1, 1] + assert restart.after[0].skipped and restart.after[0].actions == 0 + assert restart.after[0].ledger_outcome == "VERIFIED" assert f"{runs} of {runs} saved and checked" in output from openadapt_flow import sealed_set @@ -1223,7 +1367,7 @@ def test_real_quickstart(tmp_path, monkeypatch, capfd): if path.name != "seal.html": for note in notes: assert note not in data, path - for folder in ("recording", "bundle", "run-1", "run-broken"): + for folder in ("recording", "bundle", "run-1", "restart/note-1"): assert sealed_set.is_sealed(root / folder), folder # Every file on disk is in the folder's index: a plaintext file # outside it makes the next read of the folder refuse. @@ -1240,7 +1384,7 @@ def test_real_quickstart(tmp_path, monkeypatch, capfd): assert "in plaintext at" not in err -def test_the_seal_pages_are_run_ones_and_the_stopped_runs(tmp_path, monkeypatch): +def test_the_seal_page_is_run_ones(tmp_path, monkeypatch): """Runs finish in any order; the page the finale opens is the first run's.""" from openadapt import seal_view @@ -1257,46 +1401,12 @@ def test_the_seal_pages_are_run_ones_and_the_stopped_runs(tmp_path, monkeypatch) ), ) runs = [_run(tmp_path, index) for index in (3, 2, 1, 5, 4)] - broken = _broken(tmp_path) - for run_dir in [run.run_dir for run in runs] + [broken.run_dir]: - run_dir.mkdir(parents=True) - (run_dir / "seal.json").write_text("{}") - engine = FlowEngine(tmp_path, visible=False) - pages = engine.seal_pages(runs, broken) + for run in runs: + run.run_dir.mkdir(parents=True) + (run.run_dir / "seal.json").write_text("{}") + pages = FlowEngine(tmp_path, visible=False).seal_pages(runs) assert pages.verified == tmp_path / "run-1" / "seal.html" - assert pages.broken == tmp_path / "run-broken" / "seal.html" - assert written == [ - ("run-1", "Run 1 of 5"), - ("run-broken", "The run with the failed save"), - ] - - -def test_an_unsealed_stopped_run_gets_no_page(tmp_path, monkeypatch): - from openadapt import seal_view - from openadapt.quickstart.engine import FlowEngine - - monkeypatch.setattr(seal_view, "bundle_graph", lambda bundle: {"nodes": []}) - monkeypatch.setattr( - seal_view, "write_seal_page", lambda run_dir, **kw: run_dir / "seal.html" - ) - pages = FlowEngine(tmp_path, visible=False).seal_pages([], _broken(tmp_path)) - assert pages.broken is None and pages.verified is None - - -def test_sealing_the_stopped_run_signs_its_report(tmp_path, monkeypatch): - from openadapt.quickstart.engine import FlowEngine - - sealed = [] - - def seal_run(run_dir, **kw): - sealed.append(run_dir.name) - (run_dir / "seal.json").write_text("{}") - - monkeypatch.setattr("openadapt_flow.offline_seal.seal_run", seal_run) - broken = _broken(tmp_path) - broken.run_dir.mkdir(parents=True) - assert FlowEngine(tmp_path, visible=False).seal_broken(broken) is True - assert sealed == ["run-broken"] + assert written == [("run-1", "Run 1 of 5")] # --------------------------------------------------------------------------- @@ -1489,7 +1599,7 @@ def fake_run_story(engine, view, **kwargs): quickstart_mod.run_quickstart( tmp_path / "qs", visible=False, - break_it=True, + last_act=True, verbose=False, steps=lambda o: NextSteps(verify=None, record="r", agent="a"), stream=_Terminal(), diff --git a/tests/test_quickstart_command.py b/tests/test_quickstart_command.py index 8b143e3c6a..f9182b598e 100644 --- a/tests/test_quickstart_command.py +++ b/tests/test_quickstart_command.py @@ -1,7 +1,6 @@ """The documented first command is one spelling everywhere it is printed. -``uvx --python 3.12 openadapt@latest quickstart`` (with ``--break-it`` where -the break is shown) gets the newest launcher on a Python the engine supports, +``uvx --python 3.12 openadapt@latest quickstart`` gets the newest launcher on a Python the engine supports, with nothing installed first. The README (and so the PyPI description), llms-full.txt and the launcher's own Python fix all use it. """ @@ -35,7 +34,8 @@ def _texts() -> dict[str, str]: def test_readme_and_llms_full_use_the_documented_command(): for name, text in _texts().items(): - assert f"{COMMAND} --break-it" in text, name + assert f"{COMMAND}\n" in text, name + assert "--break-it" not in text, name # No other uvx spelling of the quickstart. for match in re.finditer(r"uvx [^\n`]*?quickstart", text): assert match.group(0) == COMMAND, (name, match.group(0)) diff --git a/tests/test_quickstart_openemr.py b/tests/test_quickstart_openemr.py index f230fdd7b8..e91f73c19e 100644 --- a/tests/test_quickstart_openemr.py +++ b/tests/test_quickstart_openemr.py @@ -427,7 +427,7 @@ def test_plain_output_matches_the_snapshot(root): def test_act_three_reads_as_a_stop_before_a_duplicate(root): output, outcome = _plain(FakeOpenEMR(root)) assert "■ Stopped before saving: possible duplicate" in output - assert "OpenEMR's record: 0 new charts" in output + assert "OpenEMR's record: 0 new charts" in output assert "A screen-trusting bot" not in output, "nothing on screen claimed success" assert outcome.broken is not None and outcome.broken.stopped @@ -592,7 +592,7 @@ def test_real_openemr_quickstart(tmp_path, monkeypatch): outcome = run_quickstart( root, visible=False, - break_it=True, + last_act=True, verbose=False, steps=_steps, stream=stream, diff --git a/tests/test_quickstart_restart.py b/tests/test_quickstart_restart.py new file mode 100644 index 0000000000..a2731a601b --- /dev/null +++ b/tests/test_quickstart_restart.py @@ -0,0 +1,164 @@ +"""Act 3 on MockMed: the batch, the hard stop after note 1, the restart. + +These tests stand in for the browser runs; the real run is covered by +``test_real_quickstart`` (opt in with ``OPENADAPT_REAL_QUICKSTART=1``). +""" + +from __future__ import annotations + +import multiprocessing +import os +import signal +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +from openadapt.quickstart import restart +from openadapt.quickstart.restart import ( + RESTART_NOTES, + BatchWorker, + NoteRun, + crash_and_restart, + ledger_key, +) + + +def _run(run_dir: Path, index: int, note: str, **overrides) -> NoteRun: + run = NoteRun( + index=index, + note=note, + run_dir=run_dir, + execution_outcome="VERIFIED", + transaction_outcome="VERIFIED", + checked=True, + skipped=False, + ledger_outcome="VERIFIED", + actions=6, + model_calls=0, + seconds=1.0, + ) + return replace(run, **overrides) + + +class FakeWorker: + def __init__(self, events): + self.events = events + + def first_note(self, jobs, bundle_dir, ledger_path): + index, note, _url, run_dir, key = jobs[0] + self.events.append(("worker", index, key, ledger_path)) + return _run(Path(run_dir), index, note) + + def kill(self): + self.events.append(("kill",)) + return True + + def close(self): + self.events.append(("close",)) + + +def _serve(urls): + def serve(): + url = f"http://127.0.0.1:{9000 + len(urls)}/" + urls.append(url) + return url, None, lambda: urls.append(f"stopped {url}") + + return serve + + +def test_the_restart_reuses_the_ledger_after_the_worker_is_killed( + tmp_path, monkeypatch +): + events: list = [] + seen_ledgers: set[Path] = set() + + def run_note(*, base_url, run_dir, index, note, ledger_path, key, **_kw): + seen_ledgers.add(ledger_path) + events.append(("here", index, key)) + # The engine's ledger decides: note 1's key is already reserved. + if index == 1: + return _run(run_dir, index, note, skipped=True, checked=False, actions=0) + return _run(run_dir, index, note) + + monkeypatch.setattr(restart, "run_note", run_note) + monkeypatch.setattr(restart, "note_count", lambda url, note: 1) + root = tmp_path / "qs" + urls: list[str] = [] + facts = crash_and_restart( + root=root, + workflow=object(), + bundle_dir=root / "bundle", + visible=False, + worker=FakeWorker(events), + serve=_serve(urls), + ) + ledger = root / "restart" / "ledger" / "writes.sqlite" + assert events == [ + ("worker", 1, ledger_key("qs", 1), ledger), + ("kill",), + ("here", 1, ledger_key("qs", 1)), + ("here", 2, ledger_key("qs", 2)), + ("close",), + ] + assert seen_ledgers == {ledger} + assert facts.held and facts.copies == [1, 1] + assert facts.notes == list(RESTART_NOTES) + # Each note had its own database, and both were stopped afterwards. + assert sum(1 for url in urls if url.startswith("stopped")) == 2 + + +def test_a_duplicate_in_the_database_is_not_held(tmp_path, monkeypatch): + monkeypatch.setattr( + restart, + "run_note", + lambda **kw: ( + _run(kw["run_dir"], kw["index"], kw["note"], skipped=True) + if kw["index"] == 1 + else _run(kw["run_dir"], kw["index"], kw["note"]) + ), + ) + counts = iter([2, 1]) + monkeypatch.setattr(restart, "note_count", lambda url, note: next(counts)) + facts = crash_and_restart( + root=tmp_path / "qs", + workflow=object(), + bundle_dir=tmp_path, + visible=False, + worker=FakeWorker([]), + serve=_serve([]), + ) + assert facts.copies == [2, 1] + assert not facts.held + + +def test_no_worker_means_the_act_is_skipped(tmp_path): + facts = crash_and_restart( + root=tmp_path, + workflow=object(), + bundle_dir=tmp_path, + visible=False, + worker=None, + serve=_serve([]), + ) + assert facts.error and not facts.held and not facts.before + + +def _sleeper(conn, visible, browser=""): # pragma: no cover - child process + os.setpgrp() + conn.send(("ready",)) + conn.recv() + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX process groups") +def test_kill_stops_the_worker_with_sigkill(monkeypatch): + monkeypatch.setattr(restart, "_worker_main", _sleeper) + worker = BatchWorker(visible=False) + try: + assert worker._recv(30)[0] == "ready" + assert worker.kill() is True + assert worker.process.exitcode == -signal.SIGKILL + finally: + worker.close() + assert multiprocessing.active_children() == [] or not worker.process.is_alive() diff --git a/tests/test_quickstart_robust.py b/tests/test_quickstart_robust.py index 45f2d24c77..8252c46e7e 100644 --- a/tests/test_quickstart_robust.py +++ b/tests/test_quickstart_robust.py @@ -19,7 +19,6 @@ from click.testing import CliRunner from test_quickstart import ( FakeEngine, - _broken, _clock, _plain, _rich, @@ -125,23 +124,6 @@ def test_a_stop_for_another_reason_is_not_retried(root): assert folders == ["run-1"] and finished == [stopped] -def test_the_break_run_gets_one_more_try(root, monkeypatch): - engine = FlowEngine(root, visible=False) - unready = _broken(root, not_ready=True, stop_attributed=False, seconds=10.0) - caught = _broken(root, run_dir=root / "run-broken-retry", seconds=7.0) - tries = iter([unready, caught]) - seen: list[Path] = [] - - def once(run_dir): - seen.append(run_dir) - return next(tries) - - monkeypatch.setattr(engine, "_break_once", once) - result = engine.break_it() - assert seen == [root / "run-broken", root / "run-broken-retry"] - assert result is caught and result.seconds == 17.0 - - # --------------------------------------------------------------------------- # What the views say # --------------------------------------------------------------------------- @@ -155,7 +137,7 @@ def test_no_ready_screen_explains_and_skips_the_break(root): assert explanation in text assert "Skipped the last part" in text assert "Stopped before its first click" in text - assert outcome.broken is None + assert outcome.broken is None and outcome.restart is None assert "not at the check" not in text @@ -163,6 +145,7 @@ def test_an_unready_break_run_says_why_in_plain_words(root): explanation = not_ready_explanation(False) engine = FakeEngine( root, + act3="break", broken={ "not_ready": True, "stop_attributed": False, @@ -181,6 +164,7 @@ def test_an_unready_break_run_says_why_in_plain_words(root): _rich( root, terminal, + act3="break", broken={ "not_ready": True, "stop_attributed": False, diff --git a/tests/test_seal_publish.py b/tests/test_seal_publish.py index 71f3e55a72..21b7a5b7e4 100644 --- a/tests/test_seal_publish.py +++ b/tests/test_seal_publish.py @@ -1118,21 +1118,15 @@ def test_anything_but_yes_uploads_nothing(make_run, answer): assert transport.requests == [] and said[-1] == "Not published." -def test_the_finale_offers_the_stopped_run_with_the_checked_one(tmp_path): +def test_the_finale_offers_the_checked_runs_seal(tmp_path): from openadapt.quickstart.engine import SealFacts, SealPages from openadapt.quickstart.story import Outcome from openadapt.quickstart.view import publish_runs root = tmp_path / "openadapt-quickstart" - for name in ("run-1", "run-broken"): - (root / name).mkdir(parents=True) - (root / name / "seal.html").write_text("") - pages = SealPages( - verified=root / "run-1" / "seal.html", broken=root / "run-broken" / "seal.html" - ) + (root / "run-1").mkdir(parents=True) + (root / "run-1" / "seal.html").write_text("") + pages = SealPages(verified=root / "run-1" / "seal.html") outcome = Outcome(root=root, seal=SealFacts("", 1), seal_pages=pages) - # The stopped run is offered only once it has its own Seal. assert publish_runs(outcome) == [root / "run-1"] - (root / "run-broken" / "seal.json").write_text("{}") - assert publish_runs(outcome) == [root / "run-1", root / "run-broken"] assert publish_runs(Outcome(root=root, seal=None, seal_pages=pages)) == [] From bdd7975f4f03ba21c73e747eea9f1692963e1eda Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 16:14:04 -0500 Subject: [PATCH 2/4] docs(capabilities): cite #2840 on the quickstart restart row --- .../0035-see-a-crash-and-a-restart-in-the-quickstart.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0035-see-a-crash-and-a-restart-in-the-quickstart.md b/capabilities/04-the-core-a-checked-entry-every-time/0035-see-a-crash-and-a-restart-in-the-quickstart.md index 5b7b26c160..676f69c8da 100644 --- a/capabilities/04-the-core-a-checked-entry-every-time/0035-see-a-crash-and-a-restart-in-the-quickstart.md +++ b/capabilities/04-the-core-a-checked-entry-every-time/0035-see-a-crash-and-a-restart-in-the-quickstart.md @@ -1 +1 @@ -| See a crash and a restart in the quickstart: on MockMed, Act 3 runs a batch of two new notes in a separate worker process, stops it with SIGKILL after note 1's save is checked, and restarts the batch with the same on-disk write ledger (`IdempotencyLedger`); the replayer finds note 1's key and sends no save for it (its report: idempotent replay, 0 actions), then saves note 2; each note's database is read afterwards. Each note has its own copy of the clinic's database, as in Act 2 | On main | Synthetic (MockMed; real headless runs on macOS, unit tests with fakes) | `openadapt quickstart`; [restart.py](openadapt/quickstart/restart.py) | +| See a crash and a restart in the quickstart: on MockMed, Act 3 runs a batch of two new notes in a separate worker process, stops it with SIGKILL after note 1's save is checked, and restarts the batch with the same on-disk write ledger (`IdempotencyLedger`); the replayer finds note 1's key and sends no save for it (its report: idempotent replay, 0 actions), then saves note 2; each note's database is read afterwards. Each note has its own copy of the clinic's database, as in Act 2 | On main ([#2840](https://github.com/OpenAdaptAI/OpenAdapt/pull/2840)) | Synthetic (MockMed; real headless runs on macOS, unit tests with fakes) | `openadapt quickstart`; [restart.py](openadapt/quickstart/restart.py) | From 0662f8be8c956c2b44fa6e6c20c60b608ec07612 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 16:27:14 -0500 Subject: [PATCH 3/4] fix(quickstart): say 'saved once' only when the restart skipped note 1 MockMed drops a save whose key it already holds, so one record per note can't rule out a resend. The database line now credits 'saved once' only when the restart report shows note 1 skipped with no actions and a VERIFIED ledger outcome. A worker that doesn't finish note 1 is reported as not finishing, not as stopping early (a timeout leaves it running). Review findings 1, 2 and 5 on #2840. --- openadapt/quickstart/restart.py | 3 ++- openadapt/quickstart/restart_view.py | 5 ++++- tests/test_quickstart_restart.py | 32 ++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/openadapt/quickstart/restart.py b/openadapt/quickstart/restart.py index 67f8110ca3..825e9396d2 100644 --- a/openadapt/quickstart/restart.py +++ b/openadapt/quickstart/restart.py @@ -110,6 +110,7 @@ def held(self) -> bool: first.checked and again.skipped and again.actions == 0 + and again.ledger_outcome == "VERIFIED" and second.checked and not second.skipped and self.copies == [1, 1] @@ -448,7 +449,7 @@ def crash_and_restart( try: facts.before.append(worker.first_note(jobs, bundle_dir, ledger_path)) except RuntimeError as error: - facts.error = f"the runner process stopped early: {error}" + facts.error = f"the runner process didn't finish note 1: {error}" return facts facts.killed = worker.kill() facts.signal = "SIGKILL" if hasattr(signal, "SIGKILL") else "" diff --git a/openadapt/quickstart/restart_view.py b/openadapt/quickstart/restart_view.py index a7e582f5f1..24e556b048 100644 --- a/openadapt/quickstart/restart_view.py +++ b/openadapt/quickstart/restart_view.py @@ -55,7 +55,10 @@ def copies_line(facts: RestartFacts) -> str: for index, count in enumerate(facts.copies, 1): noun = "record" if count == 1 else "records" parts.append(f"note {index}: {count} {noun}") - if facts.copies and all(count == 1 for count in facts.copies): + # MockMed drops a save whose key it already holds, so a count of 1 alone + # can't rule out a resend. Say "saved once" only when the restart report + # shows note 1 skipped with no actions (``held``). + if facts.held and all(count == 1 for count in facts.copies): return "each note saved once (" + ", ".join(parts) + ")" return ", ".join(parts) diff --git a/tests/test_quickstart_restart.py b/tests/test_quickstart_restart.py index a2731a601b..8a0802a37e 100644 --- a/tests/test_quickstart_restart.py +++ b/tests/test_quickstart_restart.py @@ -162,3 +162,35 @@ def test_kill_stops_the_worker_with_sigkill(monkeypatch): finally: worker.close() assert multiprocessing.active_children() == [] or not worker.process.is_alive() + + +def test_saved_once_needs_the_skip_not_just_one_record_each(): + """MockMed drops a resend whose key it already has, so [1, 1] alone can't + show "saved once": the line needs note 1 skipped with no actions.""" + + from openadapt.quickstart.restart import RestartFacts + from openadapt.quickstart.restart_view import copies_line + + here = Path("run") + resent = RestartFacts(notes=list(RESTART_NOTES), ledger=Path("ledger")) + resent.killed = True + resent.before = [_run(here, 1, RESTART_NOTES[0])] + # The restart ran note 1 again (6 actions) instead of skipping it. + resent.after = [ + _run(here, 1, RESTART_NOTES[0]), + _run(here, 2, RESTART_NOTES[1]), + ] + resent.copies = [1, 1] + assert not resent.held + assert "saved once" not in copies_line(resent) + assert copies_line(resent) == "note 1: 1 record, note 2: 1 record" + + held = replace( + resent, + after=[ + _run(here, 1, RESTART_NOTES[0], skipped=True, actions=0), + _run(here, 2, RESTART_NOTES[1]), + ], + ) + assert held.held + assert copies_line(held).startswith("each note saved once (") From f75d5fbf84645f84d078a3e33a1d1fd322e39d31 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 17:58:13 -0500 Subject: [PATCH 4/4] fix(quickstart): pass the verdict-fold check and the agent README test Read settled outcomes through one helper (says_verified) instead of four literal comparisons, narrow the optional REPORT.md handler, report a worker failure with contextlib.suppress and exit it cleanly, and update the agent README test to the new plain quickstart command. --- openadapt/quickstart/restart.py | 32 +++++++++++++++++------ openadapt/quickstart/restart_view.py | 4 +-- packages/agent/tests/test_distribution.py | 2 +- 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/openadapt/quickstart/restart.py b/openadapt/quickstart/restart.py index 825e9396d2..c01e245da2 100644 --- a/openadapt/quickstart/restart.py +++ b/openadapt/quickstart/restart.py @@ -21,6 +21,8 @@ from __future__ import annotations +import contextlib +import logging import multiprocessing import os import signal @@ -43,6 +45,19 @@ RESTART_DIR = "restart" +_log = logging.getLogger(__name__) + + +def says_verified(value: object) -> bool: + """True when an outcome the engine already settled reads ``VERIFIED``. + + The act only reads verdicts the replayer, the record check and the ledger + settled; it never decides one. One comparison, used everywhere. + """ + + return str(value) == "VERIFIED" + + @dataclass class NoteRun: """One note's run, read from its report, the ledger and its database.""" @@ -110,7 +125,7 @@ def held(self) -> bool: first.checked and again.skipped and again.actions == 0 - and again.ledger_outcome == "VERIFIED" + and says_verified(again.ledger_outcome) and second.checked and not second.skipped and self.copies == [1, 1] @@ -240,8 +255,9 @@ def run_note( from openadapt_flow.report import render_run_report render_run_report(run_dir) - except Exception: # noqa: BLE001 - report.json is the record either way - pass + except (ImportError, OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: + # REPORT.md is a convenience; report.json is the record either way. + _log.debug("REPORT.md not rendered for %s: %s", run_dir, exc) record = ledger.lookup(key) ledger.close() envelope = getattr(report, "outcome_envelope", None) @@ -255,8 +271,8 @@ def run_note( ) checked = ( not skipped - and str(report.execution_outcome) == "VERIFIED" - and report.transaction_outcome == "VERIFIED" + and says_verified(report.execution_outcome) + and says_verified(report.transaction_outcome) and required > 0 and confirmed == required and note_count(base_url, note) >= 1 @@ -333,10 +349,10 @@ def _worker_main(conn: Connection, visible: bool, browser: str = "") -> None: except (EOFError, KeyboardInterrupt, BrokenPipeError): return except Exception as exc: # noqa: BLE001 - reported to the parent - try: + with contextlib.suppress(BrokenPipeError, OSError): conn.send(("broken", f"{type(exc).__name__}: {exc}")) - except (BrokenPipeError, OSError): - pass + # The parent shows the error; exit the worker without a traceback. + raise SystemExit(1) from exc finally: conn.close() diff --git a/openadapt/quickstart/restart_view.py b/openadapt/quickstart/restart_view.py index 24e556b048..08cfb67021 100644 --- a/openadapt/quickstart/restart_view.py +++ b/openadapt/quickstart/restart_view.py @@ -8,7 +8,7 @@ from typing import Any, Optional -from openadapt.quickstart.restart import NoteRun, RestartFacts +from openadapt.quickstart.restart import NoteRun, RestartFacts, says_verified #: Width of the note column, so the statuses line up. NOTE_WIDTH = 34 @@ -22,7 +22,7 @@ def note_status(run: NoteRun, marks: Any) -> str: """One note's result: checked, skipped by the ledger, or what stopped it.""" if run.skipped: - done = run.ledger_outcome == "VERIFIED" + done = says_verified(run.ledger_outcome) why = "the ledger has it as done" if done else "the ledger has it as started" return f"{marks.dot} Skipped: {why}, no save sent" if run.checked: diff --git a/packages/agent/tests/test_distribution.py b/packages/agent/tests/test_distribution.py index a05c8cc9b4..15e45a21ee 100644 --- a/packages/agent/tests/test_distribution.py +++ b/packages/agent/tests/test_distribution.py @@ -310,7 +310,7 @@ def test_identity_sentence_is_shared() -> None: assert "This only registers the server." in readme assert "This only registers the server." in skill assert "openadapt flow tutorial" in readme - assert "openadapt quickstart --break-it" in readme + assert "openadapt quickstart" in readme assert "name: computer-use" not in readme.lower()