diff --git a/packages/flow/openadapt_flow/connector/daemon.py b/packages/flow/openadapt_flow/connector/daemon.py index afbff04801..2cba94ec78 100644 --- a/packages/flow/openadapt_flow/connector/daemon.py +++ b/packages/flow/openadapt_flow/connector/daemon.py @@ -85,7 +85,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 99c4eb00c8..7f3ff34bb2 100644 --- a/packages/flow/openadapt_flow/connector/executor.py +++ b/packages/flow/openadapt_flow/connector/executor.py @@ -273,29 +273,34 @@ 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), - # Its own session: an operator Ctrl-C or a service stop signals - # the daemon's process group, not the governed child. The daemon - # stops children itself (cancel_job), so each outcome is judged. - start_new_session=True, - ) - 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), + # Its own session: an operator Ctrl-C or a service stop signals + # the daemon's process group, not the governed child. The daemon + # stops children itself (cancel_job), so each outcome is judged. + start_new_session=True, + ) + 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() except BaseException: @@ -918,6 +923,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, @@ -946,6 +958,7 @@ def _execute_job( status = status_from_report(outcome.returncode, report) error_code: Optional[str] = None report_target_kind = report.get("execution_target_kind") + outcome_envelope = precise_outcome_from_report(report) # After the child started, no readable report, or a nonzero exit with # a report that claims success, does not say whether the write landed: # a cancel, a service stop, an OOM kill or a crash can end a child @@ -964,7 +977,21 @@ def _execute_job( outcome_unknown = not _reported_terminal_outcome(report) or ( outcome.returncode != 0 and claims_success ) - if outcome_unknown: + # 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" + or outcome_unknown + ): + status = "halt" + error_code = "cancelled_after_child_start" + outcome_error = ( + "cancelled after child start; reconcile the system of record" + ) + elif outcome_unknown: status = "halt" error_code = "child_outcome_unknown" outcome_error = ( @@ -980,8 +1007,6 @@ def _execute_job( "the signed dispatch target_kind (fail closed)" ) else: - # A cancel that arrived after the child reported does not change - # what the child did: its own outcome stands. outcome_error = None if status == "failed": error_code = "governed_run_failed" @@ -1021,15 +1046,20 @@ 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 in ("cancelled_after_child_start", "child_outcome_unknown") + and not report + ): + report_ref = None halt = halt_object(report) - if error_code == "child_outcome_unknown" and halt is None: + if error_code in ("cancelled_after_child_start", "child_outcome_unknown"): halt = {"present": True} - outcome_envelope = precise_outcome_from_report(report) 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..0a0b305d13 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,110 @@ 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()) diff --git a/packages/flow/tests/test_connector_pilot.py b/packages/flow/tests/test_connector_pilot.py index 903688fb6e..ccad94d29f 100644 --- a/packages/flow/tests/test_connector_pilot.py +++ b/packages/flow/tests/test_connector_pilot.py @@ -501,20 +501,28 @@ def runner(argv, run_dir, env): runner=runner, ) assert result.status == "halt" - assert result.error_code == "child_outcome_unknown" + assert result.error_code == "cancelled_after_child_start" + assert result.report_ref is None assert result.halt == {"present": True} and result.outcome is None def test_cancel_after_the_child_reported_keeps_its_real_outcome(tmp_path): job = parse_job(_payload(), lease_job_id="bjob_late") + envelope = json.loads(_VERIFIED_ENVELOPE.read_text()) + def runner(argv, run_dir, env): cancel_job("bjob_late") # too late: the child already finished report = { - "execution_target_kind": "web", + "workflow_name": job.workflow_id, + "started_at": "2026-10-10T00:00:00Z", + "execution_target_kind": job.target_kind, "success": True, - "execution_outcome": "VERIFIED", - "results": [{"ok": True}], + "execution_profile": envelope["profile"], + "execution_outcome": envelope["outcome"], + "execution_completed": envelope["execution_completed"], + "production_eligible": envelope["production_eligible"], + "outcome_envelope": envelope, } return RunOutcome(returncode=0, report=report) @@ -525,6 +533,11 @@ def runner(argv, run_dir, env): runner=runner, ) assert result.status == "success" and result.error_code is None + assert result.outcome is not None + assert ( + result.outcome["workflow_contract_sha256"] + == envelope["workflow_contract_sha256"] + ) @pytest.mark.parametrize( @@ -555,7 +568,7 @@ def runner(argv, run_dir, env): runner=runner, ) assert result.status == "halt" - assert result.error_code == "child_outcome_unknown" + assert result.error_code == "cancelled_after_child_start" assert result.halt == {"present": True} and result.outcome is None @@ -720,7 +733,7 @@ def spy(*args, **kwargs): ] assert len(acks) == 1 and acks[0]["job_id"] == job_id assert acks[0]["status"] != "failed" - assert acks[0].get("error_code") == "child_outcome_unknown" + assert acks[0].get("error_code") == "cancelled_after_child_start" @pytest.mark.skipif(not hasattr(os, "getsid"), reason="POSIX sessions")