From c7a31be4196b727501f07f840d1d324d82ca88b9 Mon Sep 17 00:00:00 2001 From: Richard Abrich Date: Sat, 21 Nov 2026 00:36:38 -0500 Subject: [PATCH 1/2] Reconcile cancellations that may follow a connector write --- .../flow/openadapt_flow/connector/daemon.py | 5 +- .../flow/openadapt_flow/connector/executor.py | 66 +++++++---- packages/flow/tests/test_connector.py | 106 ++++++++++++++++++ 3 files changed, 155 insertions(+), 22 deletions(-) diff --git a/packages/flow/openadapt_flow/connector/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index d1bc4ab28f..0cd71d9f07 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -83,7 +83,10 @@ def phi_free_callback_body(job: ByocJob, result: ExecutionResult) -> dict[str, A body["halt"] = {"present": True} if result.outcome is not None: body["outcome"] = result.outcome - if result.status != "success" and failure_signal_sharing_enabled(): + if result.error_code == "cancelled_after_child_start": + # The interrupted report cannot establish a failure kind or final effect. + body["error_code"] = "cancelled_after_child_start" + elif result.status != "success" and failure_signal_sharing_enabled(): body["failure_signal"] = result.failure_signal or automation_failure_signal( None, result.status, job.target_kind ) diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index fc5849da09..82f2ebdb5c 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -265,25 +265,30 @@ class _ChildNotStarted(RuntimeError): """The operating system refused to start the governed process.""" +class _CancelledBeforeStart(RuntimeError): + """The control plane stopped the job before its process was created.""" + + def _subprocess_runner( argv: list[str], run_dir: Path, child_env: Mapping[str, str] ) -> RunOutcome: job_id = getattr(_CURRENT, "job_id", None) - try: - proc = subprocess.Popen( # nosec - fixed argv and exact process-local env - argv, - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - env=dict(child_env), - ) - except OSError as exc: - raise _ChildNotStarted(type(exc).__name__) from exc - if job_id: - with _CHILDREN.lock: + # Order cancellation and registration at one boundary. A control that + # wins the lock prevents launch; a control that follows can stop the PID. + with _CHILDREN.lock: + if job_id and job_id in _CHILDREN.cancelled: + raise _CancelledBeforeStart() + try: + proc = subprocess.Popen( # nosec - fixed argv and exact process-local env + argv, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=dict(child_env), + ) + except OSError as exc: + raise _ChildNotStarted(type(exc).__name__) from exc + if job_id: _CHILDREN.procs[job_id] = proc - cancelled = job_id in _CHILDREN.cancelled - if cancelled: - proc.terminate() try: proc.wait() finally: @@ -844,6 +849,13 @@ def _execute_job( try: outcome = runner(argv, run_dir, child_env) + except _CancelledBeforeStart: + return _refused( + job, + "cancelled_by_control_plane", + "cancelled before the governed child started", + verified_bundle_sha256=observed_sha256, + ) except _ChildNotStarted as exc: return _refused( job, @@ -872,10 +884,18 @@ def _execute_job( status = status_from_report(outcome.returncode, report) error_code: Optional[str] = None report_target_kind = report.get("execution_target_kind") - if job_cancelled(job.lease_job_id): - status = "failed" - error_code = "cancelled_by_control_plane" - outcome_error = "cancelled by the control plane while running" + outcome_envelope = precise_outcome_from_report(report) + # Cancellation can race with both the write and the child's final report. + # Retain a validated terminal success or halt for this substrate. Otherwise + # the stop cannot establish what happened to the system of record. + if job_cancelled(job.lease_job_id) and ( + report_target_kind != job.target_kind + or outcome_envelope is None + or status == "failed" + ): + status = "halt" + error_code = "cancelled_after_child_start" + outcome_error = "cancelled after child start; reconcile the system of record" elif report_target_kind != job.target_kind: status = "failed" error_code = "target_kind_mismatch" @@ -923,13 +943,17 @@ def _execute_job( # 4. The PHI-bearing report body goes to the CUSTOMER'S store, never ours. report_ref: Optional[str] = job.report_ref() + if error_code == "cancelled_after_child_start" and not report: + report_ref = None halt = halt_object(report) - outcome_envelope = precise_outcome_from_report(report) + if error_code == "cancelled_after_child_start": + halt = {"present": True} if error_code is not None and outcome_envelope is not None: - # A cancelled or mismatched run never reports a success envelope. + # An uncertain or mismatched run never reports a success envelope. outcome_envelope = None try: - storage.write_report(report_ref, report) + if report_ref is not None: + storage.write_report(report_ref, report) except Exception as exc: # A storage fault says nothing about what the child did, so it # never becomes a runner failure: a run that actuated would show diff --git a/packages/flow/tests/test_connector.py b/packages/flow/tests/test_connector.py index b70bfc6fb8..f4510bf046 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -22,6 +22,9 @@ import json import os import stat +import sys +import time +from concurrent.futures import ThreadPoolExecutor from pathlib import Path import httpx @@ -570,6 +573,109 @@ def runner(argv, run_dir, env): assert cp.acks[0]["status"] == "done" +@pytest.mark.parametrize( + "phase", + [ + "before_start", + "at_spawn", + "after_write", + "late_verified", + "wrong_target", + "legacy_success", + "conflicting_exit", + ], +) +def test_cancellation_reports_effect_evidence_and_releases_the_lease(tmp_path, phase): + from openadapt_flow.connector.executor import _subprocess_runner, cancel_job + + cp = StubControlPlane() + cp.enqueue("org_demo", _payload()) + job_id = f"bjob_cancel_{phase}" + cp.jobs[0]["id"] = job_id + client = ConnectorClient( + "https://app.test", transport=httpx.MockTransport(cp.handler) + ) + client.enroll(enrollment_secret="s", org_id="org_demo", name="n") + storage = InMemoryCustomerStorage(bundle_bytes=_BUNDLE_BYTES) + record = tmp_path / "synthetic-record" + if phase == "before_start": + cancel_job(job_id) + + def runner(argv, run_dir, env): + # The subprocess writes a real synthetic record. A control delivered + # before the executor consumes its result can still observe either an + # incomplete or an already-finalized report. + assert phase != "before_start" + report = VERIFIED_REPORT + if phase == "legacy_success": + report = SUCCESS_REPORT + elif phase == "wrong_target": + report = {**VERIFIED_REPORT, "execution_target_kind": "citrix"} + child = ( + "import pathlib, sys, time\n" + "with pathlib.Path(sys.argv[1]).open('a') as saved: saved.write('saved\\n')\n" + "if sys.argv[2]: pathlib.Path(sys.argv[2]).write_text(sys.argv[3])\n" + "else: time.sleep(10)\n" + "sys.exit(int(sys.argv[4]))\n" + ) + command = [ + sys.executable, + "-c", + child, + str(record), + "" if phase == "after_write" else str(run_dir / "report.json"), + json.dumps(report), + "1" if phase == "conflicting_exit" else "0", + ] + if phase == "at_spawn": + cancel_job(job_id) + if phase == "after_write": + def stop_after_write(): + deadline = time.monotonic() + 8 + while time.monotonic() < deadline: + if record.exists() and record.read_text() == "saved\n": + return cancel_job(job_id) + time.sleep(0.02) + return False + + with ThreadPoolExecutor(max_workers=1) as pool: + stopped = pool.submit(stop_after_write) + outcome = _subprocess_runner(command, run_dir, env) + assert stopped.result() and outcome.returncode != 0 + return outcome + outcome = _subprocess_runner(command, run_dir, env) + cancel_job(job_id) + return outcome + + result = run_once( + client, _settings(), runner=runner, storage_factory=lambda job: storage + ) + assert result["callback_accepted"] and len(cp.callbacks) == len(cp.acks) == 1 + body, ack = cp.callbacks[0]["body"], cp.acks[0] + assert "synthetic-record" not in json.dumps(body) + if phase in {"before_start", "at_spawn"}: + assert not record.exists() + assert result["status"] == body["status"] == ack["status"] == "failed" + assert ack["error_code"] == "cancelled_by_control_plane" + else: + assert record.read_text().splitlines() == ["saved"] + assert ack["status"] == "done" + assert body["bundle_sha256"] == _BUNDLE_SHA256 + if phase == "late_verified": + assert result["status"] == body["status"] == "success" + assert body["outcome"]["outcome"] == "VERIFIED" + assert ack["error_code"] is None + else: + assert result["status"] == body["status"] == "halt" + assert body["halt"] == {"present": True} and "outcome" not in body + assert ack["error_code"] == body["error_code"] + assert ack["error_code"] == "cancelled_after_child_start" + assert "failure_signal" not in body + if phase == "after_write": + assert body["report_path"] is None + assert "report_sha256" not in body["metrics"] + + def test_report_write_failure_lease_is_not_acked_failed(): cp = StubControlPlane() cp.enqueue("org_demo", _payload()) From e7bc2183985efb581eb9191804a64a6b1936c7de Mon Sep 17 00:00:00 2001 From: Richard Abrich Date: Sat, 21 Nov 2026 01:36:46 -0500 Subject: [PATCH 2/2] Apply Ruff to the cancellation outcome and test --- packages/flow/openadapt_flow/connector/executor.py | 4 +++- packages/flow/tests/test_connector.py | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/connector/executor.py b/packages/flow/openadapt_flow/connector/executor.py index 82f2ebdb5c..99e57df039 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -895,7 +895,9 @@ def _execute_job( ): status = "halt" error_code = "cancelled_after_child_start" - outcome_error = "cancelled after child start; reconcile the system of record" + outcome_error = ( + "cancelled after child start; reconcile the system of record" + ) elif report_target_kind != job.target_kind: status = "failed" error_code = "target_kind_mismatch" diff --git a/packages/flow/tests/test_connector.py b/packages/flow/tests/test_connector.py index f4510bf046..0a0b305d13 100644 --- a/packages/flow/tests/test_connector.py +++ b/packages/flow/tests/test_connector.py @@ -630,6 +630,7 @@ def runner(argv, run_dir, env): if phase == "at_spawn": cancel_job(job_id) if phase == "after_write": + def stop_after_write(): deadline = time.monotonic() + 8 while time.monotonic() < deadline: