diff --git a/backend/tests/test_provisioner_request_threading.py b/backend/tests/test_provisioner_request_threading.py index d4342832e9..7cb3b7643f 100644 --- a/backend/tests/test_provisioner_request_threading.py +++ b/backend/tests/test_provisioner_request_threading.py @@ -5,15 +5,18 @@ from __future__ import annotations import asyncio import inspect import json +import logging import threading import time from contextlib import contextmanager +from datetime import UTC, datetime, timedelta from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock import httpx import pytest import requests +import urllib3 from blockbuster import BlockBuster from kubernetes.client.rest import ApiException @@ -272,6 +275,699 @@ def test_bash_capacity_already_exists_race_reads_winning_pod(monkeypatch, provis assert core.created_pods == [] +def test_service_failure_after_pod_already_exists_keeps_concurrent_creators_pod(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + # The fast path misses the Service, the Pod create loses the race to a + # concurrent creator (409), then the Service create fails for an unrelated + # reason. The Pod belongs to the winner; rolling it back would tear down + # a sandbox another Gateway is waiting on. + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: None) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=409))) + monkeypatch.setattr(core, "create_namespaced_service", MagicMock(side_effect=ApiException(status=500))) + delete_pod = MagicMock() + monkeypatch.setattr(core, "delete_namespaced_pod", delete_pod) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-raced")) + assert error.value.status_code == 500 + assert "Service creation failed" in error.value.detail + assert core.created_pods == [] + delete_pod.assert_not_called() + + +def test_pod_creation_failure_reports_without_rollback(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: None) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=500))) + create_service = MagicMock() + monkeypatch.setattr(core, "create_namespaced_service", create_service) + delete_pod = MagicMock() + monkeypatch.setattr(core, "delete_namespaced_pod", delete_pod) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-pod-failed")) + assert error.value.status_code == 500 + assert "Pod creation failed" in error.value.detail + assert core.created_pods == [] + create_service.assert_not_called() + delete_pod.assert_not_called() + + +def test_service_failure_rolls_back_the_pod_this_request_created(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: None) + monkeypatch.setattr(core, "create_namespaced_service", MagicMock(side_effect=ApiException(status=500))) + delete_pod = MagicMock() + monkeypatch.setattr(core, "delete_namespaced_pod", delete_pod) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-own-pod")) + assert error.value.status_code == 500 + assert "Service creation failed" in error.value.detail + assert core.created_pods == ["sandbox-own-pod"] + delete_pod.assert_called_once() + args, kwargs = delete_pod.call_args + assert args == ("sandbox-sandbox-own-pod", provisioner_module.K8S_NAMESPACE) + preconditions = kwargs["body"].preconditions + assert preconditions.uid == "pod-sandbox-own-pod-1" + assert preconditions.resource_version == "1" + + +def test_service_failure_keeps_pod_and_original_error_when_absence_check_transports(monkeypatch, provisioner_module, caplog): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: None) + monkeypatch.setattr(core, "create_namespaced_service", MagicMock(side_effect=ApiException(status=500, reason="service broke"))) + # A read timeout surfaces as a urllib3 transport error, not an ApiException. + transport_error = urllib3.exceptions.MaxRetryError(None, "/services/sandbox-sandbox-transport-svc", "read timed out") + monkeypatch.setattr(core, "read_namespaced_service", MagicMock(side_effect=transport_error)) + delete_pod = MagicMock() + monkeypatch.setattr(core, "delete_namespaced_pod", delete_pod) + with caplog.at_level(logging.WARNING): + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-transport")) + assert error.value.status_code == 500 + assert "service broke" in error.value.detail + assert core.created_pods == ["sandbox-transport"] + delete_pod.assert_not_called() + assert any("absence" in record.message for record in caplog.records) + + +def test_pod_race_adoption_marks_the_pod_before_reporting_running(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + reads = iter([None, "http://sandbox"]) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: next(reads)) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=409))) + original_response = provisioner_module._sandbox_response + + def recording_response(*args, **kwargs): + core.events.append(("response", args[0])) + return original_response(*args, **kwargs) + + monkeypatch.setattr(provisioner_module, "_sandbox_response", recording_response) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert response.status == "Running" + # One best-effort mark before the URL wait and one after the final + # attestation; both name the same Pod. + assert core.patched_pods == ["sandbox-existing", "sandbox-existing"] + assert core.pod_annotations["sandbox-existing"] == {"deer-flow/adopted": "pod-sandbox-existing-0"} + patch_events = [index for index, event in enumerate(core.events) if event == ("patch", "sandbox-existing")] + response_index = core.events.index(("response", "sandbox-existing")) + assert patch_events[0] < response_index + assert response_index < patch_events[1] + + +def test_pod_race_pre_adoption_keeps_the_pod_when_a_rollback_runs_during_the_url_wait(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=409))) + access_url_calls = 0 + marks_seen_during_wait = [] + + def access_url(*_args, **_kwargs): + nonlocal access_url_calls + access_url_calls += 1 + if access_url_calls == 1: + return None + # A concurrent creator's rollback runs during the access-URL wait. The + # pre-adoption mark written before the wait carries the attested UID, so + # the rollback keeps the Pod. + marks_seen_during_wait.append(dict(core.pod_annotations.get("sandbox-existing", {}))) + provisioner_module._delete_pod_unless_adopted("sandbox-existing", expected_uid="pod-sandbox-existing-0") + return "http://sandbox" + + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", access_url) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert response.status == "Running" + assert core.deleted_pods == [] + # The mark present during the wait is the Pod UID, not a bare "true": a + # later replacement under the same name must not inherit it. + assert marks_seen_during_wait == [{"deer-flow/adopted": "pod-sandbox-existing-0"}] + + +def test_pod_race_pre_adoption_failure_does_not_block_the_final_adoption(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + reads = iter([None, "http://sandbox"]) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: next(reads)) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=409))) + original_patch = core.patch_namespaced_pod + patch_calls = 0 + + def fail_first_patch(name, namespace, body): + nonlocal patch_calls + patch_calls += 1 + if patch_calls == 1: + raise ApiException(status=500) + return original_patch(name, namespace, body) + + monkeypatch.setattr(core, "patch_namespaced_pod", MagicMock(side_effect=fail_first_patch)) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + # The best-effort pre-adoption failed, but the final attestation still + # marks the Pod and reports it Running. + assert response.status == "Running" + assert core.patched_pods == ["sandbox-existing"] + assert core.pod_annotations["sandbox-existing"] == {"deer-flow/adopted": "pod-sandbox-existing-0"} + + +def test_pod_race_pre_adoption_read_failure_does_not_block_the_final_adoption(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + reads = iter([None, "http://sandbox"]) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: next(reads)) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=409))) + original_read = core.read_namespaced_pod + read_calls = 0 + + def fail_first_read(name, namespace): + nonlocal read_calls + read_calls += 1 + if read_calls == 1: + raise ApiException(status=500) + return original_read(name, namespace) + + monkeypatch.setattr(core, "read_namespaced_pod", MagicMock(side_effect=fail_first_read)) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + # The pre-adoption read failed, but the final attestation still reads the + # Pod, marks it, and reports it Running. + assert response.status == "Running" + assert core.patched_pods == ["sandbox-existing"] + assert core.pod_annotations["sandbox-existing"] == {"deer-flow/adopted": "pod-sandbox-existing-0"} + + +def test_pod_race_pre_adoption_read_transport_error_does_not_block_the_final_adoption(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + reads = iter([None, "http://sandbox"]) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: next(reads)) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=409))) + original_read = core.read_namespaced_pod + read_calls = 0 + + def transport_first_read(name, namespace): + nonlocal read_calls + read_calls += 1 + if read_calls == 1: + raise urllib3.exceptions.MaxRetryError(None, name, "read timed out") + return original_read(name, namespace) + + monkeypatch.setattr(core, "read_namespaced_pod", MagicMock(side_effect=transport_first_read)) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + # A transport error while pre-adopting is best-effort; the final attestation + # still marks the Pod and reports it Running. + assert response.status == "Running" + assert core.patched_pods == ["sandbox-existing"] + assert core.pod_annotations["sandbox-existing"] == {"deer-flow/adopted": "pod-sandbox-existing-0"} + + +def test_pod_race_pre_adoption_patch_transport_error_does_not_block_the_final_adoption(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + reads = iter([None, "http://sandbox"]) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: next(reads)) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=409))) + original_patch = core.patch_namespaced_pod + patch_calls = 0 + + def transport_first_patch(name, namespace, body): + nonlocal patch_calls + patch_calls += 1 + if patch_calls == 1: + raise urllib3.exceptions.MaxRetryError(None, name, "patch timed out") + return original_patch(name, namespace, body) + + monkeypatch.setattr(core, "patch_namespaced_pod", MagicMock(side_effect=transport_first_patch)) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + # A transport error while pre-adopting is best-effort; the final attestation + # still marks the Pod and reports it Running. + assert response.status == "Running" + assert core.patched_pods == ["sandbox-existing"] + assert core.pod_annotations["sandbox-existing"] == {"deer-flow/adopted": "pod-sandbox-existing-0"} + + +def test_adoption_mark_failure_reports_instead_of_running(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + reads = iter([None, "http://sandbox"]) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: next(reads)) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=409))) + monkeypatch.setattr(core, "patch_namespaced_pod", MagicMock(side_effect=ApiException(status=404, reason="gone"))) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert error.value.status_code == 500 + assert "Could not adopt Pod" in error.value.detail + + +def test_fast_path_marks_the_existing_pod_before_reporting_running(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert response.status == "Running" + assert core.patched_pods == ["sandbox-existing"] + assert core.pod_annotations["sandbox-existing"] == {"deer-flow/adopted": "pod-sandbox-existing-0"} + assert core.created_pods == [] + + +def test_fast_path_does_not_report_a_terminating_pod_without_requirements(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + core.terminating_pods.add("sandbox-existing") + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert error.value.status_code == 409 + assert "terminating" in error.value.detail + # The status check rejects before writing a mark to a Pod that is going away. + assert core.patched_pods == [] + + +def test_fast_path_does_not_report_a_terminating_pod_with_capacity_requirements(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + core.terminating_pods.add("sandbox-existing") + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing", max_shell_sessions=10)) + # With requirements, _sandbox_response itself rejects the terminating Pod + # before the create-level check runs; either way the result is 409. + assert error.value.status_code == 409 + assert "terminating" in error.value.detail + assert core.patched_pods == [] + + +def test_fast_path_does_not_report_running_when_the_pod_started_terminating(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + original_response = provisioner_module._sandbox_response + + def delete_after_attestation(*args, **kwargs): + # The response is attested as Running, then the concurrent rollback's + # delete commits before the adoption mark. Kubernetes still accepts a + # metadata patch on a terminating Pod, so the mark alone would not + # stop this request from reporting a sandbox that is going away. + response = original_response(*args, **kwargs) + core.terminating_pods.add("sandbox-existing") + return response + + monkeypatch.setattr(provisioner_module, "_sandbox_response", delete_after_attestation) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert error.value.status_code == 409 + assert "terminating" in error.value.detail + + +def test_fast_path_does_not_report_running_or_overwrite_a_peers_mark_when_the_pod_was_replaced(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + original_response = provisioner_module._sandbox_response + + def replace_after_attestation(*args, **kwargs): + # The attested Pod is gone and another create owns the same name by + # the time the adoption patch would land. + response = original_response(*args, **kwargs) + core.pod_uids["sandbox-existing"] = "pod-sandbox-existing-replacement" + core.pod_annotations["sandbox-existing"] = {"deer-flow/adopted": "pod-sandbox-existing-replacement"} + return response + + monkeypatch.setattr(provisioner_module, "_sandbox_response", replace_after_attestation) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert error.value.status_code == 409 + assert "replaced" in error.value.detail + # The name now addresses the replacement, which carries the replacement + # creator's mark. The patch carries the attested UID in metadata.uid, so + # the API server rejects it and the replacement's mark must survive. + assert core.patched_pods == [] + assert core.pod_annotations["sandbox-existing"] == {"deer-flow/adopted": "pod-sandbox-existing-replacement"} + + +def test_fast_path_mark_preserves_other_annotations(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + core.pod_annotations["sandbox-existing"] = {"peer/note": "keep"} + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert response.status == "Running" + # Strategic merge adds the adoption key; it does not replace the map. + assert core.pod_annotations["sandbox-existing"] == { + "peer/note": "keep", + "deer-flow/adopted": "pod-sandbox-existing-0", + } + + +def test_pod_race_adoption_does_not_report_a_terminating_pod_without_requirements(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + reads = iter([None, "http://sandbox"]) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: next(reads)) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=409))) + # No capacity requirement is sent, so _sandbox_response returns the phase + # as data instead of raising. A create still must not report it as ready. + core.terminating_pods.add("sandbox-existing") + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert error.value.status_code == 409 + assert "terminating" in error.value.detail + assert core.patched_pods == [] + + +def test_pod_race_adoption_does_not_report_running_when_the_pod_started_terminating(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + reads = iter([None, "http://sandbox"]) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: next(reads)) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=409))) + original_response = provisioner_module._sandbox_response + + def terminate_after_attestation(*args, **kwargs): + response = original_response(*args, **kwargs) + core.terminating_pods.add("sandbox-existing") + return response + + monkeypatch.setattr(provisioner_module, "_sandbox_response", terminate_after_attestation) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert error.value.status_code == 409 + assert "terminating" in error.value.detail + + +def test_pod_race_adoption_does_not_report_running_when_the_pod_was_replaced(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + reads = iter([None, "http://sandbox"]) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: next(reads)) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=409))) + original_response = provisioner_module._sandbox_response + + def replace_after_attestation(*args, **kwargs): + response = original_response(*args, **kwargs) + core.pod_uids["sandbox-existing"] = "pod-sandbox-existing-replacement" + core.pod_annotations.pop("sandbox-existing", None) + return response + + monkeypatch.setattr(provisioner_module, "_sandbox_response", replace_after_attestation) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert error.value.status_code == 409 + assert "replaced" in error.value.detail + # Only the pre-adoption mark of the Pod that was attested; the final mark + # must not land on the replacement under the same name. + assert core.patched_pods == ["sandbox-existing"] + assert "sandbox-existing" not in core.pod_annotations + + +def test_create_does_not_report_running_for_a_self_created_pod_that_was_already_terminating(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + core.terminating_pods.add("sandbox-new") + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-new")) + assert error.value.status_code == 409 + assert "terminating" in error.value.detail + assert core.created_pods == ["sandbox-new"] + + +def test_create_marks_a_replacement_of_the_pod_it_created_before_reporting_running(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + original_response = provisioner_module._sandbox_response + + def replace_created_pod(*args, **kwargs): + # The Pod this request created is gone by the time it reads the + # response; another create owns the name. The response is still valid, + # but the replacement must carry the adoption mark. + core.pod_uids["sandbox-new"] = "pod-sandbox-new-replacement" + return original_response(*args, **kwargs) + + monkeypatch.setattr(provisioner_module, "_sandbox_response", replace_created_pod) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-new")) + assert response.status == "Running" + assert response.container_id == "pod-sandbox-new-replacement" + assert core.patched_pods == ["sandbox-new"] + assert core.pod_annotations["sandbox-new"] == {"deer-flow/adopted": "pod-sandbox-new-replacement"} + + +def test_create_a_new_pod_does_not_patch_it(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-new")) + assert response.status == "Running" + # A create that keeps the Pod it created needs no adoption mark. + assert core.patched_pods == [] + + +def test_fast_path_adoption_mark_failure_reports_instead_of_running(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + monkeypatch.setattr(core, "patch_namespaced_pod", MagicMock(side_effect=ApiException(status=500, reason="patch broke"))) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert error.value.status_code == 500 + assert "Could not adopt Pod" in error.value.detail + + +def test_rollback_keeps_pod_adopted_after_its_read_before_the_delete(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: None) + monkeypatch.setattr(core, "create_namespaced_service", MagicMock(side_effect=ApiException(status=500))) + original_delete = core.delete_namespaced_pod + + def adopt_then_delete(name, namespace, body=None): + # A peer adopts the Pod after this request confirmed the Service absent. + core.patch_namespaced_pod(name, namespace, {"metadata": {"annotations": {"deer-flow/adopted": "true"}}}) + return original_delete(name, namespace, body=body) + + delete_pod = MagicMock(side_effect=adopt_then_delete) + monkeypatch.setattr(core, "delete_namespaced_pod", delete_pod) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-adopted")) + assert error.value.status_code == 500 + assert core.created_pods == ["sandbox-adopted"] + assert core.deleted_pods == [] + + +def test_rollback_keeps_pod_when_adoption_lands_before_its_read(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: None) + monkeypatch.setattr(core, "create_namespaced_service", MagicMock(side_effect=ApiException(status=500))) + original_read = core.read_namespaced_pod + + def adopt_before_read(name, namespace): + # A peer adopts the Pod after the 404 absence check but before the + # rollback reads it. The new resourceVersion alone would satisfy the + # delete precondition, so only the adoption mark can keep the Pod. + core.patch_namespaced_pod(name, namespace, {"metadata": {"annotations": {"deer-flow/adopted": "true"}}}) + return original_read(name, namespace) + + monkeypatch.setattr(core, "read_namespaced_pod", MagicMock(side_effect=adopt_before_read)) + delete_pod = MagicMock() + monkeypatch.setattr(core, "delete_namespaced_pod", delete_pod) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-mark-first")) + assert error.value.status_code == 500 + delete_pod.assert_not_called() + + +def test_rollback_delete_transport_error_keeps_original_service_error(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: None) + monkeypatch.setattr(core, "create_namespaced_service", MagicMock(side_effect=ApiException(status=500, reason="service broke"))) + transport_error = urllib3.exceptions.MaxRetryError(None, "/pods/sandbox-sandbox-delete-transport", "timed out") + monkeypatch.setattr(core, "delete_namespaced_pod", MagicMock(side_effect=transport_error)) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-delete-transport")) + assert error.value.status_code == 500 + assert "service broke" in error.value.detail + + +def test_create_sweeps_only_unserviced_pods_past_the_grace_period(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1, ready_after_service_reads={"sandbox-sweep": 1}) + monkeypatch.setattr(provisioner_module, "core_v1", core) + now = datetime.now(UTC) + old = now - timedelta(seconds=provisioner_module._ORPHAN_POD_GRACE_SECONDS + 60) + young = now - timedelta(seconds=60) + core.pod_shell_capacities["sandbox-old"] = 10 + core.pod_uids["sandbox-old"] = "pod-sandbox-old-listed" + core.listed_pods = [ + SimpleNamespace(metadata=SimpleNamespace(name="sandbox-sandbox-old", uid="pod-sandbox-old-listed", labels={"sandbox-id": "sandbox-old"}, creation_timestamp=old)), + SimpleNamespace(metadata=SimpleNamespace(name="sandbox-sandbox-young", uid="pod-sandbox-young-listed", labels={"sandbox-id": "sandbox-young"}, creation_timestamp=young)), + SimpleNamespace(metadata=SimpleNamespace(name="sandbox-sandbox-listed", uid="pod-sandbox-listed-listed", labels={"sandbox-id": "sandbox-listed"}, creation_timestamp=old)), + ] + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-sweep")) + assert response.status == "Running" + assert core.deleted_pods == ["sandbox-old"] + + +def test_create_sweep_keeps_orphan_adopted_between_listing_and_delete(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1, ready_after_service_reads={"sandbox-sweep": 1}) + monkeypatch.setattr(provisioner_module, "core_v1", core) + old = datetime.now(UTC) - timedelta(seconds=provisioner_module._ORPHAN_POD_GRACE_SECONDS + 60) + core.pod_shell_capacities["sandbox-old"] = 10 + core.pod_uids["sandbox-old"] = "pod-sandbox-old-listed" + core.listed_pods = [ + SimpleNamespace(metadata=SimpleNamespace(name="sandbox-sandbox-old", uid="pod-sandbox-old-listed", labels={"sandbox-id": "sandbox-old"}, creation_timestamp=old)), + ] + original_read = core.read_namespaced_pod + + def adopt_before_read(name, namespace): + # The list said unserviced, but a peer adopted the Pod before the + # sweep re-read it. Deleting from the stale list would tear that + # sandbox down. + if name == "sandbox-sandbox-old": + core.patch_namespaced_pod(name, namespace, {"metadata": {"annotations": {"deer-flow/adopted": "true"}}}) + return original_read(name, namespace) + + monkeypatch.setattr(core, "read_namespaced_pod", MagicMock(side_effect=adopt_before_read)) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-sweep")) + assert response.status == "Running" + assert core.patched_pods == ["sandbox-old"] + assert core.deleted_pods == [] + + +def test_create_sweep_keeps_a_replaced_pod(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1, ready_after_service_reads={"sandbox-sweep": 1}) + monkeypatch.setattr(provisioner_module, "core_v1", core) + old = datetime.now(UTC) - timedelta(seconds=provisioner_module._ORPHAN_POD_GRACE_SECONDS + 60) + core.listed_pods = [ + SimpleNamespace(metadata=SimpleNamespace(name="sandbox-sandbox-old", uid="pod-sandbox-old-listed", labels={"sandbox-id": "sandbox-old"}, creation_timestamp=old)), + ] + # The listed Pod is gone by the time the sweep re-reads the name: another + # create has replaced it. The list's age and UID no longer describe the + # object under that name, so the sweep must not delete it. + core.pod_uids["sandbox-old"] = "pod-sandbox-old-replacement" + core.pod_shell_capacities["sandbox-old"] = 10 + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-sweep")) + assert response.status == "Running" + assert core.deleted_pods == [] + + +def test_create_sweep_rechecks_the_service_after_listing(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1, ready_after_service_reads={"sandbox-sweep": 1}) + monkeypatch.setattr(provisioner_module, "core_v1", core) + old = datetime.now(UTC) - timedelta(seconds=provisioner_module._ORPHAN_POD_GRACE_SECONDS + 60) + core.pod_shell_capacities["sandbox-old"] = 10 + core.pod_uids["sandbox-old"] = "pod-sandbox-old-listed" + core.listed_pods = [ + SimpleNamespace(metadata=SimpleNamespace(name="sandbox-sandbox-old", uid="pod-sandbox-old-listed", labels={"sandbox-id": "sandbox-old"}, creation_timestamp=old)), + ] + original_read = core.read_namespaced_service + + def read_service_with_late_restore(name, namespace): + # The Service list predates a Service that was created or restored + # after it. Deleting from the stale list would tear down the sandbox + # that Service now addresses. + if _sandbox_id_from_service_name(name) == "sandbox-old": + return _node_port_service("sandbox-old") + return original_read(name, namespace) + + monkeypatch.setattr(core, "read_namespaced_service", MagicMock(side_effect=read_service_with_late_restore)) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-sweep")) + assert response.status == "Running" + assert core.deleted_pods == [] + + +def test_create_sweep_keeps_pod_when_the_service_recheck_transports(monkeypatch, provisioner_module, caplog): + core = _RecordingCoreV1(event_loop_thread_id=-1, ready_after_service_reads={"sandbox-sweep": 1}) + monkeypatch.setattr(provisioner_module, "core_v1", core) + old = datetime.now(UTC) - timedelta(seconds=provisioner_module._ORPHAN_POD_GRACE_SECONDS + 60) + core.pod_shell_capacities["sandbox-old"] = 10 + core.pod_uids["sandbox-old"] = "pod-sandbox-old-listed" + core.listed_pods = [ + SimpleNamespace(metadata=SimpleNamespace(name="sandbox-sandbox-old", uid="pod-sandbox-old-listed", labels={"sandbox-id": "sandbox-old"}, creation_timestamp=old)), + ] + original_read = core.read_namespaced_service + + def read_service_transport(name, namespace): + if _sandbox_id_from_service_name(name) == "sandbox-old": + raise urllib3.exceptions.MaxRetryError(None, name, "read timed out") + return original_read(name, namespace) + + monkeypatch.setattr(core, "read_namespaced_service", MagicMock(side_effect=read_service_transport)) + with caplog.at_level(logging.WARNING): + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-sweep")) + assert response.status == "Running" + assert core.deleted_pods == [] + assert any("absence" in record.message for record in caplog.records) + + +def test_create_sweep_skips_the_requested_sandbox(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1, ready_after_service_reads={"sandbox-sweep": 1}) + monkeypatch.setattr(provisioner_module, "core_v1", core) + old = datetime.now(UTC) - timedelta(seconds=provisioner_module._ORPHAN_POD_GRACE_SECONDS + 60) + core.listed_pods = [ + SimpleNamespace(metadata=SimpleNamespace(name="sandbox-sandbox-sweep", uid="pod-sandbox-sweep-listed", labels={"sandbox-id": "sandbox-sweep"}, creation_timestamp=old)), + ] + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-sweep")) + assert response.status == "Running" + assert "sandbox-sweep" not in core.deleted_pods + + +def test_service_failure_keeps_pod_when_service_committed_despite_the_error(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: None) + # The Service write commits even though the create call reports an error. + # A peer can already serve this Pod through it, so it must not be rolled + # back. + core.service_sandboxes.add("sandbox-svc-committed") + monkeypatch.setattr(core, "create_namespaced_service", MagicMock(side_effect=ApiException(status=500))) + delete_pod = MagicMock() + monkeypatch.setattr(core, "delete_namespaced_pod", delete_pod) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-svc-committed")) + assert error.value.status_code == 500 + assert core.created_pods == ["sandbox-svc-committed"] + delete_pod.assert_not_called() + + +def test_service_failure_keeps_pod_when_service_state_is_unknown(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: None) + monkeypatch.setattr(core, "create_namespaced_service", MagicMock(side_effect=ApiException(status=500))) + # The read-back also fails, so absence cannot be confirmed. + monkeypatch.setattr(core, "read_namespaced_service", MagicMock(side_effect=ApiException(status=500))) + delete_pod = MagicMock() + monkeypatch.setattr(core, "delete_namespaced_pod", delete_pod) + with pytest.raises(provisioner_module.HTTPException) as error: + provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-svc-unknown")) + assert error.value.status_code == 500 + assert core.created_pods == ["sandbox-svc-unknown"] + delete_pod.assert_not_called() + + +def test_double_already_exists_race_reads_winner_without_rollback(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", core) + reads = iter([None, "http://sandbox"]) + monkeypatch.setattr(provisioner_module, "_sandbox_access_url", lambda *_a, **_kw: next(reads)) + monkeypatch.setattr(core, "create_namespaced_pod", MagicMock(side_effect=ApiException(status=409))) + monkeypatch.setattr(core, "create_namespaced_service", MagicMock(side_effect=ApiException(status=409))) + delete_pod = MagicMock() + monkeypatch.setattr(core, "delete_namespaced_pod", delete_pod) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-existing")) + assert response.status == "Running" + assert core.created_pods == [] + delete_pod.assert_not_called() + + +def test_service_already_exists_keeps_the_pod_this_request_created(monkeypatch, provisioner_module): + core = _RecordingCoreV1(event_loop_thread_id=-1, ready_after_service_reads={"sandbox-svc-raced": 1}) + monkeypatch.setattr(provisioner_module, "core_v1", core) + # This request wins the Pod race but loses the Service race. The winner's + # Service selects the Pod by sandbox-id label, so the fresh Pod is adopted + # and must not be rolled back. + core.service_sandboxes.add("sandbox-svc-raced") + monkeypatch.setattr(core, "create_namespaced_service", MagicMock(side_effect=ApiException(status=409))) + delete_pod = MagicMock() + monkeypatch.setattr(core, "delete_namespaced_pod", delete_pod) + response = provisioner_module.create_sandbox(provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-svc-raced")) + assert response.status == "Running" + assert core.created_pods == ["sandbox-svc-raced"] + delete_pod.assert_not_called() + + def test_broker_request_without_image_cannot_mount_credentials(monkeypatch, provisioner_module): core = _RecordingCoreV1(event_loop_thread_id=-1) monkeypatch.setattr(provisioner_module, "core_v1", core) @@ -600,6 +1296,19 @@ class _RecordingCoreV1: self.created_pods: list[str] = [] self.created_pod_specs: dict[str, object] = {} self.created_services: list[str] = [] + self.patched_pods: list[str] = [] + self.pod_resource_versions: dict[str, int] = {} + self.pod_uids: dict[str, str] = {} + self.pod_annotations: dict[str, dict[str, str]] = {} + self.terminating_pods: set[str] = set() + self.events: list[tuple[str, str]] = [] + self.deleted_pods: list[str] = [] + self.listed_pods: list = [] + + def _pod_uid(self, sandbox_id: str) -> str: + if sandbox_id not in self.pod_uids: + self.pod_uids[sandbox_id] = f"pod-{sandbox_id}-{len(self.created_pods)}" + return self.pod_uids[sandbox_id] def _record_k8s_call(self) -> None: thread_id = threading.get_ident() @@ -632,7 +1341,12 @@ class _RecordingCoreV1: if capacity is None: raise ApiException(status=404) return SimpleNamespace( - metadata=SimpleNamespace(uid=f"pod-{sandbox_id}-{len(self.created_pods)}", deletion_timestamp=None), + metadata=SimpleNamespace( + uid=self._pod_uid(sandbox_id), + resource_version=str(self.pod_resource_versions.get(sandbox_id, 0)), + annotations=dict(self.pod_annotations.get(sandbox_id, {})), + deletion_timestamp=datetime.now(UTC) if sandbox_id in self.terminating_pods else None, + ), status=SimpleNamespace(phase="Running"), spec=self.created_pod_specs[sandbox_id].spec if sandbox_id in self.created_pod_specs @@ -646,13 +1360,41 @@ class _RecordingCoreV1: ), ) - def create_namespaced_pod(self, _namespace: str, pod) -> None: + def create_namespaced_pod(self, _namespace: str, pod): self._record_k8s_call() sandbox_id = pod.metadata.labels["sandbox-id"] self.created_pods.append(sandbox_id) self.created_pod_specs[sandbox_id] = pod + self.pod_resource_versions[sandbox_id] = self.pod_resource_versions.get(sandbox_id, 0) + 1 env = {item.name: item.value for item in (pod.spec.containers[0].env or [])} self.pod_shell_capacities[sandbox_id] = int(env.get("MAX_SHELL_SESSIONS", "10")) + return SimpleNamespace(metadata=SimpleNamespace(uid=self._pod_uid(sandbox_id))) + + def patch_namespaced_pod(self, name: str, _namespace: str, body): + self._record_k8s_call() + sandbox_id = name[len("sandbox-") :] + metadata = (body or {}).get("metadata") or {} + expected_uid = metadata.get("uid") + if expected_uid is not None and expected_uid != self._pod_uid(sandbox_id): + # The strategic merge patch carries the immutable UID. The API + # server rejects a patch that addresses a same-name replacement + # before applying any field in it. + raise ApiException(status=422) + annotations = metadata.get("annotations") or {} + self.pod_annotations.setdefault(sandbox_id, {}).update(annotations) + self.patched_pods.append(sandbox_id) + self.events.append(("patch", sandbox_id)) + self.pod_resource_versions[sandbox_id] = self.pod_resource_versions.get(sandbox_id, 0) + 1 + # Kubernetes accepts metadata patches on a Pod that is already + # terminating; model the returned object rather than hiding it. + return SimpleNamespace( + metadata=SimpleNamespace( + uid=self._pod_uid(sandbox_id), + resource_version=str(self.pod_resource_versions[sandbox_id]), + annotations=dict(self.pod_annotations[sandbox_id]), + deletion_timestamp=datetime.now(UTC) if sandbox_id in self.terminating_pods else None, + ) + ) def create_namespaced_service(self, _namespace: str, service) -> None: self._record_k8s_call() @@ -664,9 +1406,22 @@ class _RecordingCoreV1: self._record_k8s_call() self.service_sandboxes.discard(_sandbox_id_from_service_name(_name)) - def delete_namespaced_pod(self, _name: str, _namespace: str) -> None: + def delete_namespaced_pod(self, _name: str, _namespace: str, body=None) -> None: self._record_k8s_call() - self.pod_shell_capacities.pop(_name[len("sandbox-") :], None) + sandbox_id = _name[len("sandbox-") :] + preconditions = getattr(body, "preconditions", None) + if preconditions is not None: + if preconditions.uid is not None and preconditions.uid != self._pod_uid(sandbox_id): + raise ApiException(status=409) + if preconditions.resource_version is not None and preconditions.resource_version != str(self.pod_resource_versions.get(sandbox_id, 0)): + raise ApiException(status=409) + self.deleted_pods.append(sandbox_id) + self.pod_shell_capacities.pop(sandbox_id, None) + + def list_namespaced_pod(self, _namespace: str, *, label_selector: str): + self._record_k8s_call() + assert label_selector == "app=deer-flow-sandbox" + return SimpleNamespace(items=list(self.listed_pods)) def list_namespaced_service(self, _namespace: str, *, label_selector: str): self._record_k8s_call() diff --git a/deploy/helm/deer-flow/README.md b/deploy/helm/deer-flow/README.md index 9dc129d8a1..ae6ceb67f6 100644 --- a/deploy/helm/deer-flow/README.md +++ b/deploy/helm/deer-flow/README.md @@ -476,9 +476,10 @@ kubectl -n deer-flow exec deploy/deer-flow-provisioner -- curl -s localhost:8002 user-data mode. Default `ReadWriteOnce`; use `ReadWriteMany` (NFS) on multi-node clusters so sandbox Pods on other nodes can mount it. - **Provisioner RBAC.** The provisioner gets a ServiceAccount with a namespaced - Role (get/list/watch/create/delete on pods + services) and a narrow ClusterRole + Role (get/list/watch/create/delete on pods + services, patch on pods for the + adoption mark a concurrent creator writes) and a narrow ClusterRole (namespace get/create). It uses in-cluster service-account creds — no - kubeconfig mount. The unused update/patch/pods-exec/events verbs were dropped + kubeconfig mount. The unused update/pods-exec/events verbs were dropped (audited against `docker/provisioner/app.py`). - **Skills.** Disabled by default (emptyDir at `/app/skills`). Populate via `skills.existingClaim` or `skills.configMap`, or bake skills into a custom @@ -546,9 +547,9 @@ per-workload with testing: `securityContext`, so this is not required). A cluster enforcing the `restricted` Pod Security Admission standard would require this setting. - **Provisioner RBAC narrowing.** The Role grants get/list/watch/create/delete - on pods and services in the namespace (update/patch/pods-exec/events were - dropped as unused). These verbs still apply to *all* Pods in the namespace, - not just sandbox Pods — RBAC can't scope by label, so the remaining + on pods and services plus patch on pods in the namespace (update/pods-exec/ + events were dropped as unused). These verbs still apply to *all* Pods in the + namespace, not just sandbox Pods — RBAC can't scope by label, so the remaining options are a dedicated sandbox namespace or admission control (OPA/Kyverno). - **`startupProbe`.** Workloads have readiness + liveness probes but no startup probe. The gateway's `livenessProbe.initialDelaySeconds: 30` covers slow starts diff --git a/deploy/helm/deer-flow/templates/NOTES.txt b/deploy/helm/deer-flow/templates/NOTES.txt index 5e57cb98f3..0d2f80fa07 100644 --- a/deploy/helm/deer-flow/templates/NOTES.txt +++ b/deploy/helm/deer-flow/templates/NOTES.txt @@ -31,10 +31,11 @@ for HTTPS. Provisioner / sandbox notes: • The provisioner ServiceAccount has a namespaced Role (get, list, watch, - create, delete on Pods + Services incl. pods/log, in this namespace) and a - narrow ClusterRole (namespace get + create, cluster-wide). These verbs - apply to *all* Pods in the namespace, not just sandbox Pods - scoping to - sandbox Pods is deferred hardening (see README "Not yet enforced"). + create, delete on Pods + Services incl. pods/log, and patch on Pods for + the adoption mark, in this namespace) and a narrow ClusterRole (namespace + get + create, cluster-wide). These verbs apply to *all* Pods in the + namespace, not just sandbox Pods - scoping to sandbox Pods is deferred + hardening (see README "Not yet enforced"). • Sandbox Pods are created in namespace {{ include "deer-flow.namespace" . }}. • PVC mode is enabled: sandbox Pods mount the `{{ include "deer-flow.homePVC" . }}` PVC for per-thread user-data. diff --git a/deploy/helm/deer-flow/templates/provisioner-rbac.yaml b/deploy/helm/deer-flow/templates/provisioner-rbac.yaml index cf8503f998..3282e8e6a0 100644 --- a/deploy/helm/deer-flow/templates/provisioner-rbac.yaml +++ b/deploy/helm/deer-flow/templates/provisioner-rbac.yaml @@ -18,14 +18,18 @@ metadata: {{- include "deer-flow.labels" . | nindent 4 }} app.kubernetes.io/component: provisioner rules: - # Verbs mirror docker/provisioner/app.py, which only calls get/create/delete - # on pods and get/list/create/delete on services. update/patch, pods/exec, - # and events were unused and dropped (least privilege). These verbs still - # apply to *all* Pods in the namespace - scoping to sandbox Pods is deferred - # (see README "Not yet enforced"). + # Verbs mirror docker/provisioner/app.py: get/list/watch/create/delete on + # pods and services, plus patch on pods for the adoption mark a concurrent + # creator writes before a Pod it did not create is reported Running. + # pods/exec and events stay unused and dropped (least privilege). These verbs + # still apply to *all* Pods in the namespace - scoping to sandbox Pods is + # deferred (see README "Not yet enforced"). - apiGroups: [""] resources: ["pods", "pods/log", "services"] verbs: ["get", "list", "watch", "create", "delete"] + - apiGroups: [""] + resources: ["pods"] + verbs: ["patch"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/docker/provisioner/README.md b/docker/provisioner/README.md index b8d1fc0268..2a764cea75 100644 --- a/docker/provisioner/README.md +++ b/docker/provisioner/README.md @@ -305,8 +305,9 @@ kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}' 3. **Kubernetes Access**: - The provisioner needs permissions to: - - Create/read/delete Pods in the `deer-flow` namespace - - Create/read/delete Services in the `deer-flow` namespace + - Get/list/create/delete and patch Pods in the `deer-flow` namespace (patch + writes the adoption mark a concurrent creator records) + - Get/list/create/delete Services in the `deer-flow` namespace - Read Namespaces (to create `deer-flow` if missing) 4. **Host Paths**: @@ -454,20 +455,60 @@ chart's `provisioner.replicas`; compose runs a single container): its own success before reading the winner's objects back (including `MAX_SHELL_SESSIONS`, so a lower-capacity winner is still reported to the Gateway as `409`). Several Gateway Pods already run this race against a - single provisioner. + single provisioner. When a Service create fails for another reason, the + handler rolls back only a Pod it created itself, and only once the Service + is confirmed absent. A create that serves a Pod it did not create, a create + whose own Pod was replaced by the time it reads the response, and the fast + path that returns an existing sandbox all mark the Pod before reporting it + Running. The mark is a strategic merge patch that carries the UID the create + attested (before the access-URL wait, the UID it just read) in the Pod's + immutable `metadata.uid`, so the API server rejects it when the name now + addresses a same-name replacement; a stale create cannot mark a replacement + behind a peer's Running response, and a matching UID merges only the adoption + annotation. Every path that marks the Pod then rejects a Pod that is + terminating, or whose UID no longer matches the one it attested, after the + mark lands, reporting `409` instead of Running. A create that lost the Pod + race marks the Pod once before the access-URL wait and again after the final + attestation, so a rollback that runs during the wait keeps the Pod; when a + rollback commits before the pre-adoption mark, that create reports `409` or + `500` to the retrying Gateway, unless another create has meanwhile placed a + new Pod under the name, which the final attestation marks before Running. The + rollback checks the mark and deletes + conditionally on the UID its own create returned and the resourceVersion it + read, so a Pod behind a Running create response is never torn down. This + coordination only holds once every replica runs this version: during a + rolling upgrade, a replica on the previous image does not read the adoption + mark and can still delete a Pod that another replica adopted. +- A Pod whose create committed while its Service write failed can be left + with no Service and would stay invisible to `GET /api/sandboxes`, which + enumerates Services. A sweep at startup, and inline on creates that reach + the creation path, deletes those leftovers once they are older than a + ten-minute grace period, so a caller that never retries does not leak them + past the next provisioner restart or such a create; each candidate is + re-read and deleted only while its listed UID still matches, and the Service + is read again before that Pod re-read and conditional delete, so a Service + created or restored after the list keeps the Pod. A Service created between + that recheck and the delete can still lose the race: the concurrent create + then reports `409` while the Pod is terminating, or `500` once it is gone, + never Running. A Pod carrying a live adoption mark (the current Pod's UID, or the + legacy `true`) is never swept (if `destroy_sandbox` deletes the Service but + fails to delete such a Pod, it needs manual cleanup). - `DELETE /api/sandboxes/{sandbox_id}` tolerates `404`, so two replicas deleting the same sandbox both return success. - NodePorts are allocated by the API server when the Service is created; the provisioner only reads the assigned port back. -- No replica runs a background loop (there is no reaper or cache), and - `/api/capabilities` is derived from environment variables every replica of - one Deployment shares. +- No replica runs a background loop or keeps a process-local cache: the + orphan sweep runs at startup and inline on create, and `/api/capabilities` + is derived from environment variables every replica of one Deployment + shares. -The one startup write is `_ensure_namespace()`: when `K8S_NAMESPACE` does not -exist yet, two replicas starting together can both see `404` and race to create -it; the loser's `409 AlreadyExists` is treated as "the namespace exists", so -both replicas start. Under the Helm chart the provisioner runs inside the -namespace it manages, so this path never runs there. +At startup the provisioner waits for the kubeconfig, initializes the client, +ensures the namespace exists, and then runs the orphan sweep as a best-effort +step that cannot stop startup. When `K8S_NAMESPACE` does not exist yet, two +replicas starting together can both see `404` and race to create it; the +loser's `409 AlreadyExists` is treated as "the namespace exists", so both +replicas start. Under the Helm chart the provisioner runs inside the namespace +it manages, so this path never runs there. ## Security Considerations diff --git a/docker/provisioner/app.py b/docker/provisioner/app.py index 7cae4aa45b..2cc43e74b8 100644 --- a/docker/provisioner/app.py +++ b/docker/provisioner/app.py @@ -30,6 +30,7 @@ Architecture (docker-compose-dev): from __future__ import annotations +import asyncio import logging import ntpath import os @@ -568,6 +569,12 @@ async def lifespan(_app: FastAPI): _wait_for_kubeconfig() core_v1 = _init_k8s_client() _ensure_namespace() + # Reap leftovers from earlier failed creates even if no create ever runs + # again. The sweep is best effort and must not stop the provisioner. + try: + await asyncio.to_thread(_sweep_orphaned_pods, exclude_sandbox_id="") + except Exception: # noqa: BLE001 - a failed sweep must not fail startup + logger.warning("Orphan sweep at startup failed", exc_info=True) logger.info("Provisioner is ready (using host Kubernetes)") yield @@ -1293,6 +1300,200 @@ def _sandbox_access_url(sandbox_id: str, *, tolerate_read_errors: bool = False) return _url_from_service(svc, sandbox_id) +def _service_confirmed_absent(sandbox_id: str) -> bool: + """Whether the sandbox Service is confirmed missing. + + A Service write that reports an error may still have committed: a peer + that discovers the Service can already serve the sandbox Pod through it. + Only a 404 confirms absence; any other outcome keeps the Pod. + """ + try: + core_v1.read_namespaced_service(_svc_name(sandbox_id), K8S_NAMESPACE) + except ApiException as exc: + if exc.status != 404: + logger.warning("Service %s absence check failed: %s", _svc_name(sandbox_id), exc.reason) + return exc.status == 404 + except urllib3.exceptions.HTTPError as exc: + # A transport failure leaves the Service state unknown; keep the Pod + # and let this request report the original creation error instead. + logger.warning("Transient error confirming Service %s absence: %s", _svc_name(sandbox_id), exc) + return False + return False + + +def _mark_pod_adopted(sandbox_id: str, *, expected_uid: str) -> k8s_client.V1Pod: + """Mark the Pod this create is about to serve so a rollback cannot remove it. + + Every create that serves a Pod it did not create records this mark before + returning Running: a create that lost the Pod race, a create whose own Pod + was replaced, and an existing sandbox served by the fast path. The + strategic merge patch carries the UID the caller attested (before the + access-URL wait, the UID it just read) in ``metadata.uid``; that field is + immutable, so the API server rejects the patch when the name now addresses + a same-name replacement and the mark never lands on it. With a matching + UID the patch merges only the adoption key, leaving any other annotations + intact. A + successful patch bumps the Pod's resourceVersion, so a rollback that + already read the Pod fails its conditional delete, and a rollback that + reads it afterwards sees the mark and keeps the Pod. Returns the patched + Pod so the caller can reject a Pod that started terminating after the + response was attested. + """ + target = _pod_name(sandbox_id) + if not expected_uid: + raise HTTPException(status_code=500, detail=f"Could not adopt Pod {target}: no attested UID") + try: + return core_v1.patch_namespaced_pod( + target, + K8S_NAMESPACE, + {"metadata": {"uid": expected_uid, "annotations": {"deer-flow/adopted": expected_uid}}}, + ) + except ApiException as exc: + if exc.status in {409, 422}: + raise HTTPException(status_code=409, detail="Existing sandbox was replaced while this request attested it") from exc + raise HTTPException(status_code=500, detail=f"Could not adopt Pod {target}: {exc}") from exc + except urllib3.exceptions.HTTPError as exc: + raise HTTPException(status_code=500, detail=f"Could not adopt Pod {target}: {exc}") from exc + + +def _adopt_attested_pod(sandbox_id: str, response) -> None: + """Mark the attested Pod and verify it is still the one the response names. + + A metadata patch can succeed on a Pod that started terminating after the + response was built, and the name can address a replacement by the time the + mark lands. A create must not report either as ready. + """ + adopted_pod = _mark_pod_adopted(sandbox_id, expected_uid=response.container_id) + metadata = getattr(adopted_pod, "metadata", None) + if metadata is None: + raise HTTPException(status_code=500, detail=f"Could not verify Pod {_pod_name(sandbox_id)} after adopting it") + if getattr(metadata, "deletion_timestamp", None): + raise HTTPException(status_code=409, detail="Existing sandbox is still terminating") + adopted_uid = getattr(metadata, "uid", None) + if adopted_uid is not None and response.container_id is not None and adopted_uid != response.container_id: + raise HTTPException(status_code=409, detail="Existing sandbox was replaced while this request attested it") + + +def _pre_adopt_racing_pod(sandbox_id: str) -> None: + """Best-effort adoption mark before the access-URL wait. + + A create that lost the Pod race creates the Service and then waits for an + access URL. During that wait a concurrent creator's rollback can still + delete the Pod: the rollback knows only the UID it created and has already + seen the Service absent. Marking before the wait bumps the Pod's + resourceVersion and records the adoption, so that rollback keeps it. The + mark must carry the Pod UID, which the 409 response does not return, so + read it once. The final response read still attests the Pod and marks it + again; a failure here only leaves that shorter window. + """ + target = _pod_name(sandbox_id) + try: + pod = core_v1.read_namespaced_pod(target, K8S_NAMESPACE) + except (ApiException, urllib3.exceptions.HTTPError) as exc: + logger.info("Could not pre-adopt Pod %s: %s", target, exc) + return + metadata = getattr(pod, "metadata", None) + uid = getattr(metadata, "uid", None) if metadata is not None else None + if not uid or getattr(metadata, "deletion_timestamp", None): + return + try: + _mark_pod_adopted(sandbox_id, expected_uid=uid) + except HTTPException as exc: + logger.warning("Could not pre-adopt Pod %s: %s", target, exc.detail) + + +def _delete_pod_unless_adopted(sandbox_id: str, *, expected_uid: str | None = None, pod_name: str | None = None) -> bool: + """Delete a Pod unless a create adopted it or it is not the expected Pod. + + The read and the delete share one snapshot. An adoption mark + (``deer-flow/adopted``) carrying this Pod's UID, or the legacy ``true`` + value written by a create that could not attest the UID, means a peer + already serves the Pod. A mark carrying another UID belongs to a Pod that + has since been replaced and is ignored. The conditional delete is fenced + on the UID and resourceVersion just read, so an adoption that lands in + between aborts it either way: a sandbox that a concurrent creator has just + started serving is never torn down. ``expected_uid`` rejects a same-name + replacement, and ``pod_name`` pins the object a sweep listed. An + unreadable state keeps the Pod too. Returns whether the delete ran. + """ + target = pod_name or _pod_name(sandbox_id) + try: + pod = core_v1.read_namespaced_pod(target, K8S_NAMESPACE) + except ApiException as exc: + if exc.status != 404: + logger.warning("Could not read Pod %s before deletion: %s", target, exc.reason) + return False + except urllib3.exceptions.HTTPError as exc: + logger.warning("Could not read Pod %s before deletion: %s", target, exc) + return False + adopted = (pod.metadata.annotations or {}).get("deer-flow/adopted") + if adopted == "true" or (adopted is not None and adopted == pod.metadata.uid): + logger.info("Kept Pod %s: a concurrent create adopted it", target) + return False + if adopted is not None: + logger.info("Ignoring stale adoption mark %s on Pod %s", adopted, target) + if expected_uid is not None and pod.metadata.uid != expected_uid: + logger.info("Kept Pod %s: it was replaced after it was selected", target) + return False + try: + core_v1.delete_namespaced_pod( + target, + K8S_NAMESPACE, + body=k8s_client.V1DeleteOptions( + preconditions=k8s_client.V1Preconditions( + uid=pod.metadata.uid, + resource_version=pod.metadata.resource_version, + ) + ), + ) + except (ApiException, urllib3.exceptions.HTTPError) as exc: + logger.info("Kept Pod %s: conditional delete did not run (%s)", target, exc) + return False + return True + + +_ORPHAN_POD_GRACE_SECONDS = 600 + + +def _sweep_orphaned_pods(*, exclude_sandbox_id: str) -> None: + """Delete sandbox Pods that no Service adopted and that outlived the grace period. + + A create whose Pod write committed while its Service write failed and whose + absence check could not run leaves a Pod nothing addresses: list_sandboxes + enumerates Services, so neither the Gateway nor a retry would find it again. + Sweeping on create and at startup reaps those leftovers; the grace period + keeps a freshly created Pod from being considered. Each candidate is + re-read and deleted only while its listed UID still matches, so a same-name + replacement and a Pod with a live adoption mark are left alone. The Service + is read again immediately before the delete: the list can predate a Service + created or restored after it was taken. + """ + try: + services = core_v1.list_namespaced_service(K8S_NAMESPACE, label_selector="app=deer-flow-sandbox").items or [] + pods = core_v1.list_namespaced_pod(K8S_NAMESPACE, label_selector="app=deer-flow-sandbox").items or [] + except (ApiException, urllib3.exceptions.HTTPError) as exc: + logger.warning("Could not list sandbox objects for orphan sweep: %s", exc) + return + serviced = {((service.metadata.labels or {}).get("sandbox-id")) for service in services} + now = time.time() + for pod in pods: + sandbox_id = (pod.metadata.labels or {}).get("sandbox-id") + if not sandbox_id or sandbox_id == exclude_sandbox_id or sandbox_id in serviced: + continue + created_at = getattr(pod.metadata, "creation_timestamp", None) + if created_at is None or now - created_at.timestamp() < _ORPHAN_POD_GRACE_SECONDS: + continue + expected_uid = getattr(pod.metadata, "uid", None) + if not expected_uid: + logger.warning("Skipped orphan sweep for Pod %s: no UID in the list response", pod.metadata.name) + continue + if not _service_confirmed_absent(sandbox_id): + logger.info("Kept orphaned Pod %s: a Service is present or its state is unknown", pod.metadata.name) + continue + if _delete_pod_unless_adopted(sandbox_id, expected_uid=expected_uid, pod_name=pod.metadata.name): + logger.info("Swept orphaned Pod %s: no Service after %s s", pod.metadata.name, _ORPHAN_POD_GRACE_SECONDS) + + def _pod_shell_capacity(pod) -> int: containers = getattr(getattr(pod, "spec", None), "containers", None) or [] sandbox_container = next((container for container in containers if getattr(container, "name", None) == "sandbox"), None) @@ -1441,7 +1642,7 @@ def create_sandbox(req: CreateSandboxRequest): existing_url = _sandbox_access_url(sandbox_id, tolerate_read_errors=True) if existing_url: try: - return _sandbox_response( + response = _sandbox_response( sandbox_id, existing_url, required_capacity=max_shell_sessions, @@ -1453,10 +1654,26 @@ def create_sandbox(req: CreateSandboxRequest): # Only a confirmed missing Pod may fall through to creation. if not isinstance(exc, ApiException) or exc.status != 404: raise HTTPException(status_code=500, detail=f"Could not verify existing sandbox shell capacity: {exc}") from exc + else: + # Report Running only after the mark lands: a concurrent creator's + # rollback checks the mark, or fails its resourceVersion + # precondition, instead of deleting a Pod this caller was told is + # ready. The capacity check inside _sandbox_response only rejects a + # terminating Pod when requirements are sent; a create must never + # report Running for one, with or without requirements. + if response.status == "Terminating": + raise HTTPException(status_code=409, detail="Existing sandbox is still terminating") + _adopt_attested_pod(sandbox_id, response) + return response + + # ── Sweep leftovers from earlier failed creates ───────────────── + _sweep_orphaned_pods(exclude_sandbox_id=sandbox_id) # ── Create Pod ─────────────────────────────────────────────────── + pod_created = False + created_pod_uid: str | None = None try: - core_v1.create_namespaced_pod( + created_pod = core_v1.create_namespaced_pod( K8S_NAMESPACE, _build_pod( sandbox_id, @@ -1471,6 +1688,8 @@ def create_sandbox(req: CreateSandboxRequest): environment=req.environment, ), ) + pod_created = True + created_pod_uid = getattr(getattr(created_pod, "metadata", None), "uid", None) logger.info(f"Created Pod {_pod_name(sandbox_id)}") except ApiException as exc: if exc.status != 409: # 409 = AlreadyExists @@ -1482,13 +1701,21 @@ def create_sandbox(req: CreateSandboxRequest): logger.info(f"Created Service {_svc_name(sandbox_id)}") except ApiException as exc: if exc.status != 409: - # Roll back the Pod on failure - try: - core_v1.delete_namespaced_pod(_pod_name(sandbox_id), K8S_NAMESPACE) - except ApiException: - pass + # Roll back only the Pod this request created, and only once the + # Service is confirmed absent. On a 409 Pod race the Pod belongs + # to the concurrent creator, and a Service write that errored may + # still have committed; deleting either would tear down a sandbox + # another Gateway is waiting on or already using. + if pod_created and _service_confirmed_absent(sandbox_id): + _delete_pod_unless_adopted(sandbox_id, expected_uid=created_pod_uid) raise HTTPException(status_code=500, detail=f"Service creation failed: {exc.reason}") + if not pod_created: + # Pre-adopt before the URL wait so a concurrent creator's rollback + # cannot delete the Pod during it; the final response read still + # attests and marks the Pod. + _pre_adopt_racing_pod(sandbox_id) + # ── Wait until the Service has a usable access URL ─────────────── sandbox_url: str | None = None for _ in range(20): @@ -1503,7 +1730,7 @@ def create_sandbox(req: CreateSandboxRequest): # A concurrent creator can win the 409 race with a lower-capacity Pod. # Never claim that the requested value was applied without reading it back. try: - return _sandbox_response( + response = _sandbox_response( sandbox_id, sandbox_url, required_capacity=max_shell_sessions, @@ -1513,6 +1740,14 @@ def create_sandbox(req: CreateSandboxRequest): except (ApiException, RuntimeError) as exc: raise HTTPException(status_code=500, detail=f"Could not verify created sandbox shell capacity: {exc}") from exc + if response.status == "Terminating": + raise HTTPException(status_code=409, detail="Existing sandbox is still terminating") + if not pod_created or response.container_id != created_pod_uid: + # A Pod this request did not create (it lost the 409 race, or its own + # Pod was replaced) is marked before reporting Running. + _adopt_attested_pod(sandbox_id, response) + return response + @app.delete("/api/sandboxes/{sandbox_id}") def destroy_sandbox(sandbox_id: str):