Skip to content

Self-improving AI Employees for everyone

fix(temporal): restore pending controls and repair CI regressions

trohitg8435e83fb5d9
diff --git a/client/src/components/credentials/panels/__tests__/BrowserLoginBindings.test.tsx b/client/src/components/credentials/panels/__tests__/BrowserLoginBindings.test.tsx
index 9c5081be..f137de1e 100644
--- a/client/src/components/credentials/panels/__tests__/BrowserLoginBindings.test.tsx
+++ b/client/src/components/credentials/panels/__tests__/BrowserLoginBindings.test.tsx
@@ -30,8 +30,12 @@ beforeEach(() => {
});
async function fillReferences(user: ReturnType<typeof userEvent.setup>) {
- await user.type(screen.getByLabelText('Username 1Password reference'), username);
- await user.type(screen.getByLabelText('Password 1Password reference'), password);
+ // References are copied from 1Password. Paste exercises the input handlers
+ // without simulating more than a hundred individual keystrokes per form.
+ await user.click(screen.getByLabelText('Username 1Password reference'));
+ await user.paste(username);
+ await user.click(screen.getByLabelText('Password 1Password reference'));
+ await user.paste(password);
}
describe('BrowserLoginBindings', () => {
diff --git a/client/src/features/home/workspace/__tests__/takeover.test.tsx b/client/src/features/home/workspace/__tests__/takeover.test.tsx
new file mode 100644
index 00000000..d276f3da
--- /dev/null
+++ b/client/src/features/home/workspace/__tests__/takeover.test.tsx
@@ -0,0 +1,56 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, renderHook } from '@testing-library/react';
+
+const mocks = vi.hoisted(() => ({
+ pauseWorkflow: vi.fn(),
+ resumeWorkflow: vi.fn(),
+ pillToast: vi.fn(),
+}));
+vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),
+ useWebSocketActions: () => mocks,
+}));
+vi.mock('../../ui/pillToast', () => ({ pillToast: mocks.pillToast }));
+
+import { normalizeWorkflowControlStatus } from '@/contexts/WebSocketContext';
+import { parseEmployee } from '../../data/schemas';
+import { useHomeStore } from '../../state/homeStore';
+import { useTakeOver } from '../takeover';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ useHomeStore.setState({ takeovers: {} });
+ mocks.pauseWorkflow.mockResolvedValue(normalizeWorkflowControlStatus({
+ generation: 1, state: 'paused', revision: 5,
+ }, 'w1'));
+});
+
+describe('Hand back lifecycle recovery', () => {
+ it.each(['workflow_control_superseded', 'transport'])(
+ 'releases the screen after Resume ends with %s', async (error) => {
+ const employee = parseEmployee({
+ workflow_id: 'w1', name: 'Maya', role: 'Receptionist', status: 'working',
+ control: normalizeWorkflowControlStatus({ generation: 1, state: 'running', revision: 4 }, 'w1'),
+ })!;
+ const giveBack = vi.fn();
+ const screen = { claim: vi.fn(async () => giveBack) };
+ mocks.resumeWorkflow.mockRejectedValue(new Error(error));
+ const { result } = renderHook(() => useTakeOver(employee, () => screen));
+ await act(async () => result.current.takeOver());
+ expect(result.current.active).toBe(true);
+ mocks.pillToast.mockClear();
+
+ await act(async () => result.current.handBack());
+
+ expect(mocks.resumeWorkflow).toHaveBeenCalledWith('w1', 4);
+ expect(giveBack).toHaveBeenCalledOnce();
+ expect(result.current).toMatchObject({ active: false, busy: false });
+ expect(useHomeStore.getState().takeovers).toEqual({});
+ if (error === 'workflow_control_superseded') {
+ expect(mocks.pillToast).not.toHaveBeenCalled();
+ } else {
+ expect(mocks.pillToast).toHaveBeenCalledWith('That did not work. Try again.', { tone: 'error' });
+ }
+ },
+ );
+});
diff --git a/client/src/features/home/workspace/takeover.ts b/client/src/features/home/workspace/takeover.ts
index ccdc2f8c..9ffc3e00 100644
--- a/client/src/features/home/workspace/takeover.ts
+++ b/client/src/features/home/workspace/takeover.ts
@@ -67,6 +67,7 @@ export function useTakeOver(employee: EmployeeSummary, surface: () => SurfaceCon
if (mine.stopped) await resumeWorkflow(employee.workflow_id, employee.control.revision);
pillToast(`Handed back to ${employee.name}`);
} catch (error) {
+ if (error instanceof Error && error.message === 'workflow_control_superseded') return;
pillToast(controlErrorMessage(error), { tone: 'error' });
} finally {
setTakeover(employee.workflow_id, null);
diff --git a/server/nodes/agent/_inline.py b/server/nodes/agent/_inline.py
index 37b9a215..8b776b3a 100644
--- a/server/nodes/agent/_inline.py
+++ b/server/nodes/agent/_inline.py
@@ -41,6 +41,19 @@ logger = get_logger(__name__)
TEAM_LEAD_TYPES = frozenset({"orchestrator_agent", "ai_employee"})
+def _employee_review_event(context: Dict[str, Any], event: Dict[str, Any] | None) -> Dict[str, Any] | None:
+ """Ordinary task completions do not identify a durable employee job.
+
+ Older task triggers carry task/status without team identity. Passing them
+ as employee-review evidence would query jobs with a null team and could
+ attach an unrelated unbound job. An explicitly admitted job still receives
+ the original event so malformed review identity fails validation.
+ """
+ if event and (context.get("employee_job_id") or event.get("team_id")):
+ return event
+ return None
+
+
async def prepare_agent_call(
*,
node_id: str,
@@ -65,7 +78,7 @@ async def prepare_agent_call(
context.update({"node_id": node_id, "node_type": node_type})
from services.employees.team_runtime import attach_employee_job, employee_job_parameters, employee_lead_prompt, employee_review_input
- await attach_employee_job(database, context, employee_review_input(context))
+ await attach_employee_job(database, context, _employee_review_event(context, employee_review_input(context)))
connection_database = database
if context.get("employee_job_id"):
context["parameter_snapshot"] = await employee_job_parameters(database, context)
@@ -94,7 +107,7 @@ async def prepare_agent_call(
# Step 1: task-context injection. Tools are kept — the injected
# guidance requires the Task Manager tool to act on the completion.
if task_data:
- await attach_employee_job(database, context, task_data)
+ await attach_employee_job(database, context, _employee_review_event(context, task_data))
from services.plugin.edge_walker import bind_employee_job_source
await bind_employee_job_source(node_id, context, database, tool_data)
task_context = format_task_context(task_data)
diff --git a/server/services/deployment/handlers.py b/server/services/deployment/handlers.py
index 00d6961b..97b3db3c 100644
--- a/server/services/deployment/handlers.py
+++ b/server/services/deployment/handlers.py
@@ -78,10 +78,13 @@ _deployment_tasks: Dict[str, asyncio.Task] = {}
# A socket only waits on these tasks. Disconnecting a waiter must not undo a
# durable Stop, and status polling must never start a second checkpoint drain.
_control_transition_tasks: Dict[tuple[str, int], asyncio.Task] = {}
+_boot_reconciliation_tasks: Dict[tuple[str, int], asyncio.Task] = {}
_control_completion_locks: weakref.WeakValueDictionary = weakref.WeakValueDictionary()
# Counts and Queries are UI observations, never checkpoint acknowledgements.
# An unavailable worker must not keep Reset behind an admission broadcast.
_CONTROL_OBSERVATION_TIMEOUT_SECONDS = 1.0
+_BOOT_REARM_TIMEOUT_SECONDS = 30.0
+_BOOT_RETRY_SECONDS = 1.0
def _control_completion_lock(workflow_id: str) -> asyncio.Lock:
@@ -119,6 +122,13 @@ def _supersede_versioned_transitions(control) -> None:
# Cancel local polling only. Reset's termination sweep is the
# authoritative cancellation of Temporal executions.
task.cancel()
+ _cancel_boot_reconciliation(control)
+
+
+def _cancel_boot_reconciliation(control) -> None:
+ for (control_id, generation), task in list(_boot_reconciliation_tasks.items()):
+ if control_id == control.id and generation == control.generation and not task.done():
+ task.cancel()
async def _await_versioned_transition(service: WorkflowControlService, control, *, task=None) -> Dict[str, Any]:
@@ -1484,7 +1494,7 @@ async def mark_clean_shutdown() -> None:
"""Stamp the clean-shutdown marker (lifespan teardown hook)."""
from core.container import container
- tasks = list(_control_transition_tasks.values())
+ tasks = [*_control_transition_tasks.values(), *_boot_reconciliation_tasks.values()]
for task in tasks:
task.cancel()
if tasks:
@@ -1584,6 +1594,13 @@ async def reconcile_active_controls_on_boot() -> int:
processed = 0
for control in controls:
try:
+ if _versioned_control(control) and control.status in {"pausing", "resuming"}:
+ # A checkpoint can remain open on admitted work for months.
+ # Its eventual completion must still restore local collectors,
+ # without blocking this boot pass or other generations.
+ _schedule_boot_reconciliation(service, control, recovery_pause=recovery_pause)
+ processed += 1
+ continue
control, controller_status = await _reconcile_control(service, control)
if control.status == "starting":
control = await _converge_interrupted_start(
@@ -1606,6 +1623,85 @@ async def reconcile_active_controls_on_boot() -> int:
return processed
+def _schedule_boot_reconciliation(service: WorkflowControlService, control, *, recovery_pause: bool) -> asyncio.Task:
+ key = (control.id, int(control.generation))
+ existing = _boot_reconciliation_tasks.get(key)
+ if existing is not None and not existing.done():
+ return existing
+ task = asyncio.create_task(_restore_after_boot_transition(service, control, recovery_pause=recovery_pause),
+ name=f"workflow-boot:{control.id}:{control.generation}")
+ _boot_reconciliation_tasks[key] = task
+
+ def completed(done: asyncio.Task) -> None:
+ if _boot_reconciliation_tasks.get(key) is done:
+ _boot_reconciliation_tasks.pop(key, None)
+ if not done.cancelled() and (exc := done.exception()) is not None:
+ logger.warning("Boot workflow restoration failed", workflow_id=control.workflow_id,
+ generation=control.generation, error=str(exc))
+
+ task.add_done_callback(completed)
+ return task
+
+
+async def _restore_after_boot_transition(service: WorkflowControlService, control, *, recovery_pause: bool) -> None:
+ """Restore a pending generation's local half after its durable drain.
+
+ Transient Update/setup failures retry independently of status requests.
+ Reset shares only the bounded setup critical section, never the
+ checkpoint wait. Re-reading the owning generation prevents an old boot
+ continuation from deploying the next Start's graph or changing its gate.
+ """
+ identity = (control.id, control.generation)
+ while True:
+ try:
+ current = await service.database.get_latest_workflow_control(control.workflow_id)
+ if (current is None or (current.id, current.generation) != identity
+ or current.status not in {"pausing", "resuming", "paused", "running"}):
+ return
+ if current.status in {"pausing", "resuming"}:
+ await asyncio.shield(_schedule_versioned_transition(service, current))
+ latest = await service.database.get_latest_workflow_control(control.workflow_id)
+ if latest is not None and (latest.id, latest.generation) == identity and latest.status in {"pausing", "resuming"}:
+ await asyncio.sleep(_BOOT_RETRY_SECONDS)
+ continue
+ if recovery_pause and current.status == "running":
+ # A Resume interrupted by a crash follows the same recovery
+ # policy as an already-running row. Fence it before rebuilding
+ # collectors, then let its acknowledged pause settle normally.
+ await _pause_for_recovery(service, current, reason="unclean_shutdown")
+ await asyncio.sleep(_BOOT_RETRY_SECONDS)
+ continue
+
+ async with _control_completion_lock(control.workflow_id):
+ latest = await service.database.get_latest_workflow_control(control.workflow_id)
+ if (latest is None or (latest.id, latest.generation) != identity
+ or latest.status not in {"paused", "running"}):
+ continue
+ if latest.revision != current.revision or latest.status != current.status:
+ continue
+ try:
+ async def restore_local():
+ await _rearm_generation(latest)
+ if latest.status == "running":
+ # A failed/timed-out attempt kept its local gate
+ # closed. Release it after setup is known complete.
+ from core.container import container
+ await container.workflow_service().resume_deployment(control.workflow_id)
+ await asyncio.wait_for(restore_local(), timeout=_BOOT_REARM_TIMEOUT_SECONDS)
+ except Exception:
+ _close_local_admission(control.workflow_id)
+ raise
+ return
+ except asyncio.CancelledError:
+ # Reset owns the subsequent local teardown and execution sweep.
+ # Shutdown likewise leaves the durable intent for the next boot.
+ raise
+ except Exception as exc:
+ logger.warning("Boot workflow restoration remains pending", workflow_id=control.workflow_id,
+ generation=control.generation, error_type=type(exc).__name__, error=str(exc))
+ await asyncio.sleep(_BOOT_RETRY_SECONDS)
+
+
async def _converge_interrupted_start(
service: WorkflowControlService,
control,
@@ -1679,6 +1775,15 @@ async def _rearm_generation(control) -> None:
workflow_service = container.workflow_service()
if workflow_service.is_workflow_deployed(control.workflow_id):
+ if control.workflow_id in _deployment_tasks:
+ # A previous bounded rearm may still be waiting on its shielded
+ # setup task. The manager installs local state before collectors
+ # finish starting, so "deployed" alone is not a setup receipt.
+ setup = await _await_deployment_setup(control.workflow_id)
+ if not setup.get("success"):
+ raise RuntimeError(str(setup.get("error", "deployment_setup_failed")))
+ if control.status == "paused":
+ await _restore_rearmed_pause(control)
return
snapshot = control.graph_snapshot or {}
nodes = snapshot.get("nodes") or []
@@ -1718,27 +1823,7 @@ async def _rearm_generation(control) -> None:
if not setup.get("success"):
raise RuntimeError(str(setup.get("error", "deployment_setup_failed")))
if control.status == "paused":
- # Restore the paused posture on the freshly re-armed local half.
- workflow_service.pause_deployment(control.workflow_id)
- await workflow_service.update_trigger_pause_status(
- control.workflow_id,
- paused=True,
- )
- await _set_cron_pause(control.workflow_id, paused=True, strict=False)
- # The deploy handler just broadcast executing=true / status=running
- # on the wire; counter-broadcast the paused posture so a connected
- # client doesn't watch the workflow flip to running and never back.
- from services.status_broadcaster import get_status_broadcaster
-
- broadcaster = get_status_broadcaster()
- await broadcaster.update_workflow_status(
- executing=False, current_node=None, progress=0,
- workflow_id=control.workflow_id,
- )
- await broadcaster.update_deployment_status(
- is_running=True, status="paused", active_runs=0,
- workflow_id=control.workflow_id,
- )
+ await _restore_rearmed_pause(control)
logger.info(
"Re-armed durable generation after restart",
workflow_id=control.workflow_id,
@@ -1747,6 +1832,25 @@ async def _rearm_generation(control) -> None:
)
+async def _restore_rearmed_pause(control) -> None:
+ from core.container import container
+ from services.status_broadcaster import get_status_broadcaster
+
+ workflow_service = container.workflow_service()
+ workflow_service.pause_deployment(control.workflow_id)
+ await workflow_service.update_trigger_pause_status(control.workflow_id, paused=True)
+ await _set_cron_pause(control.workflow_id, paused=True, strict=False)
+ # Setup emits running status; publish the durable paused posture once its
+ # receipt arrives, including when an earlier rearm waiter timed out.
+ broadcaster = get_status_broadcaster()
+ await broadcaster.update_workflow_status(
+ executing=False, current_node=None, progress=0, workflow_id=control.workflow_id,
+ )
+ await broadcaster.update_deployment_status(
+ is_running=True, status="paused", active_runs=0, workflow_id=control.workflow_id,
+ )
+
+
async def _await_deployment_setup(workflow_id: str) -> Dict[str, Any]:
"""Wait for trigger/listener setup started by the legacy deploy handler."""
task = _deployment_tasks.get(workflow_id)
@@ -2408,6 +2512,12 @@ async def handle_reset_workflow(data: Dict[str, Any], websocket: WebSocket) -> D
# The completed-generation branch above only resets direct Workspace
# tasks. Generation-wide cleanup below must not sweep a later Start.
+ if data.get("expected_root_execution_id"):
+ # A generation-scoped Reset can preempt a blocked boot setup waiter
+ # before acquiring the completion lock. The root identity was checked
+ # above and is rechecked by the owning-row CAS below; revision-only
+ # callers retain their strict conflict contract and bounded lock wait.
+ _cancel_boot_reconciliation(current)
async with _control_completion_lock(workflow_id):
# Completion can win while Reset waits for this short lock. Reload
# before CAS and never let a delayed Reset sweep a later generation.
diff --git a/server/services/employees/reconcile_jobs.py b/server/services/employees/reconcile_jobs.py
index e15cf000..c46a0ff9 100644
--- a/server/services/employees/reconcile_jobs.py
+++ b/server/services/employees/reconcile_jobs.py
@@ -4,6 +4,9 @@ This module never starts workflows, calls models, or delivers results. CLI
inspection is read-only by default and does not run application startup or
database migrations. Temporal visibility is used only to locate histories;
the histories and exact run-chain identities provide the proof.
+
+The one-shot CLI writes content-free NDJSON decisions to stdout for operators
+and scripts. Those reports are command output, separate from application logs.
"""
from __future__ import annotations
diff --git a/server/tests/conftest.py b/server/tests/conftest.py
index 34d440ac..efb45f73 100644
--- a/server/tests/conftest.py
+++ b/server/tests/conftest.py
@@ -12,6 +12,10 @@ from unittest.mock import MagicMock
import pytest
+# Register shared real-database fixtures through pytest rather than importing
+# a sibling conftest, whose directory scope depends on collection order.
+pytest_plugins = ("tests.database_fixtures",)
+
# Ensure server/ is on sys.path
SERVER_DIR = Path(__file__).parent.parent
if str(SERVER_DIR) not in sys.path:
diff --git a/server/tests/core_config/test_cookie_posture.py b/server/tests/core_config/test_cookie_posture.py
index 383be1b2..38c0d04f 100644
--- a/server/tests/core_config/test_cookie_posture.py
+++ b/server/tests/core_config/test_cookie_posture.py
@@ -91,6 +91,7 @@ class TestSameSiteNoneValidator:
base = {
"host": "127.0.0.1",
"port": 3010,
+ "debug": False,
"jwt_secret_key": "x" * 32,
"secret_key": "y" * 32,
"cors_origins": ["http://localhost:3001"],
diff --git a/server/tests/database_fixtures.py b/server/tests/database_fixtures.py
new file mode 100644
index 00000000..b5609b79
--- /dev/null
+++ b/server/tests/database_fixtures.py
@@ -0,0 +1,69 @@
+"""Real application database fixtures shared across sibling test packages."""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+import sys
+import uuid
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+
+async def real_database(tmp_path: Path):
+ """A real ``core.database.Database`` on an isolated temporary database.
+
+ Root conftest stubs ``core.database`` for fast plugin tests, so load the
+ real module privately. ``TEST_POSTGRES_URL`` retains the existing option
+ to run these contracts against a separately created PostgreSQL database.
+ """
+ server_dir = Path(__file__).resolve().parent.parent
+ module_name = f"tests._employees_database_{uuid.uuid4().hex}"
+ spec = importlib.util.spec_from_file_location(module_name, server_dir / "core" / "database.py")
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[module_name] = module
+ spec.loader.exec_module(module)
+
+ db_path = tmp_path / f"employees-{uuid.uuid4().hex}.db"
+ admin = None
+ postgres_name = "employee_test_" + uuid.uuid4().hex
+ postgres_url = os.environ.get("TEST_POSTGRES_URL")
+ database_url = f"sqlite+aiosqlite:///{db_path.as_posix()}"
+ if postgres_url:
+ # The root harness stubs core as a package without a search path.
+ if "core.shared_database" not in sys.modules:
+ shared_spec = importlib.util.spec_from_file_location("core.shared_database",
+ server_dir / "core" / "shared_database.py")
+ shared = importlib.util.module_from_spec(shared_spec)
+ sys.modules["core.shared_database"] = shared
+ shared_spec.loader.exec_module(shared)
+ from sqlalchemy.engine import make_url
+ from sqlalchemy.ext.asyncio import create_async_engine
+ from sqlalchemy import text
+ admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")
+ async with admin.connect() as connection:
+ await connection.execute(text(f'CREATE DATABASE "{postgres_name}"'))
+ database_url = make_url(postgres_url).set(database=postgres_name).render_as_string(hide_password=False)
+ settings = SimpleNamespace(
+ database_url=database_url,
+ database_echo=False,
+ database_pool_size=5,
+ database_max_overflow=5,
+ )
+ database = module.Database(settings)
+ try:
+ await database.startup()
+ yield database
+ finally:
+ await database.shutdown()
+ if admin:
+ async with admin.connect() as connection:
+ await connection.execute(text(f'DROP DATABASE "{postgres_name}" WITH (FORCE)'))
+ await admin.dispose()
+ sys.modules.pop(module_name, None)
+ for candidate in (db_path, Path(f"{db_path}-wal"), Path(f"{db_path}-shm")):
+ candidate.unlink(missing_ok=True)
diff --git a/server/tests/nodes/test_agent_prepare_call.py b/server/tests/nodes/test_agent_prepare_call.py
index 565eb917..a6872975 100644
--- a/server/tests/nodes/test_agent_prepare_call.py
+++ b/server/tests/nodes/test_agent_prepare_call.py
@@ -54,3 +54,65 @@ async def test_completion_firing_keeps_tools(status):
# The task context is still injected ahead of the original prompt.
assert "task-1" in prepared["parameters"]["prompt"]
assert prepared["parameters"]["prompt"].endswith("review")
+
+
+async def test_legacy_completion_does_not_lookup_unbound_employee_jobs():
+ """A real current-run event without a team remains an ordinary completion."""
+ import nodes.agent._inline as inline
+
+ task = {"task_id": "ordinary-task", "status": "completed", "result": "done"}
+ context = {"workflow_id": "wf", "nodes": [{"id": "trigger", "type": "taskTrigger"}],
+ "outputs": {"trigger": task}}
+ with patch.object(inline, "collect_agent_connections", AsyncMock(return_value=_connections(
+ task_data=task, tool_data=[{"node_id": "manager", "node_type": "taskManager"}]))), \
+ patch.object(inline, "collect_teammate_connections", AsyncMock(return_value=[])):
+ prepared = await inline.prepare_agent_call(node_id="lead", node_type="orchestrator_agent",
+ parameters={"prompt": "review"}, context=context, database=object())
+ assert "employee_job_id" not in context
+ assert prepared["tool_data"][0]["node_id"] == "manager"
+ assert "ordinary-task" in prepared["parameters"]["prompt"]
+
+
[email protected]("admitted_job", [None, "job"])
+async def test_employee_review_lookup_failure_is_not_silently_ignored(admitted_job):
+ """Team-scoped reviews and admitted jobs retain authoritative DB failures."""
+ import nodes.agent._inline as inline
+
+ task = {"task_id": "task", "status": "completed", "result": "done"}
+ if admitted_job is None:
+ task["team_id"] = "managed-team"
+ context = {"workflow_id": "wf", "nodes": [{"id": "trigger", "type": "taskTrigger"}],
+ "outputs": {"trigger": task}}
+ if admitted_job:
+ context["employee_job_id"] = admitted_job
+ connections = AsyncMock(return_value=_connections(task_data=task, tool_data=[]))
+ with patch.object(inline, "collect_agent_connections", connections), \
+ patch("services.employees.team_runtime.attach_employee_job", AsyncMock(side_effect=ValueError(
+ "The review task does not belong to this employee job"))) as attach, \
+ pytest.raises(ValueError, match="does not belong"):
+ await inline.prepare_agent_call(node_id="lead", node_type="ai_employee",
+ parameters={"prompt": "review"}, context=context, database=object())
+ assert attach.await_args.args[2] == task
+ connections.assert_not_awaited()
+
+
+async def test_collected_review_for_admitted_job_preserves_missing_team_validation():
+ """A review found during edge walking cannot bypass admitted-job checks."""
+ import nodes.agent._inline as inline
+
+ task = {"task_id": "task", "status": "completed", "result": "done"}
+ context = {"workflow_id": "wf", "employee_job_id": "job"}
+ async def attach(database, scope, review):
+ if review:
+ raise ValueError("The review task does not belong to this employee job")
+ with patch.object(inline, "collect_agent_connections", AsyncMock(return_value=_connections(
+ task_data=task, tool_data=[]))), \
+ patch("services.employees.team_runtime.attach_employee_job", AsyncMock(side_effect=attach)), \
+ patch("services.employees.team_runtime.employee_job_parameters", AsyncMock(return_value={})), \
+ patch("services.employees.team_runtime.employee_lead_prompt", AsyncMock(return_value="review")), \
+ pytest.raises(ValueError, match="does not belong"):
+ await inline.prepare_agent_call(node_id="lead", node_type="ai_employee",
+ parameters={"prompt": "review"}, context=context, database=object())
diff --git a/server/tests/services/employees/conftest.py b/server/tests/services/employees/conftest.py
index 38f56758..9480d205 100644
--- a/server/tests/services/employees/conftest.py
+++ b/server/tests/services/employees/conftest.py
@@ -1,71 +1,6 @@
-"""Fixtures for the Normal-mode employees package tests."""
+"""Employee tests inherit the shared real_database fixture from root conftest.
-from __future__ import annotations
-
-import importlib.util
-import os
-import sys
-import uuid
-from pathlib import Path
-from types import SimpleNamespace
-
-import pytest
-
-
-async def real_database(tmp_path: Path):
- """A real ``core.database.Database`` on a throwaway SQLite file.
-
- The root conftest stubs ``core.database`` for fast plugin tests, so the
- real module is loaded privately (tests/services/agent_context does the
- same)."""
- module_name = f"tests._employees_database_{uuid.uuid4().hex}"
- spec = importlib.util.spec_from_file_location(
- module_name,
- Path(__file__).resolve().parents[3] / "core" / "database.py",
- )
- assert spec is not None and spec.loader is not None
- module = importlib.util.module_from_spec(spec)
- sys.modules[module_name] = module
- spec.loader.exec_module(module)
-
- db_path = tmp_path / f"employees-{uuid.uuid4().hex}.db"
- admin = None
- postgres_name = "employee_test_" + uuid.uuid4().hex
- postgres_url = os.environ.get("TEST_POSTGRES_URL")
- database_url = f"sqlite+aiosqlite:///{db_path.as_posix()}"
- if postgres_url:
- # The root test harness stubs core as a package without a search path.
- # Load this small production compatibility module explicitly, as above.
- if "core.shared_database" not in sys.modules:
- shared_spec = importlib.util.spec_from_file_location("core.shared_database",
- Path(__file__).resolve().parents[3] / "core" / "shared_database.py")
- shared = importlib.util.module_from_spec(shared_spec)
- sys.modules["core.shared_database"] = shared
- shared_spec.loader.exec_module(shared)
- from sqlalchemy.engine import make_url
- from sqlalchemy.ext.asyncio import create_async_engine
- from sqlalchemy import text
- admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")
- async with admin.connect() as connection:
- await connection.execute(text(f'CREATE DATABASE "{postgres_name}"'))
- database_url = make_url(postgres_url).set(database=postgres_name).render_as_string(hide_password=False)
- settings = SimpleNamespace(
- database_url=database_url,
- database_echo=False,
- database_pool_size=5,
- database_max_overflow=5,
- )
- database = module.Database(settings)
- try:
- await database.startup()
- yield database
- finally:
- await database.shutdown()
- if admin:
- async with admin.connect() as connection:
- await connection.execute(text(f'DROP DATABASE "{postgres_name}" WITH (FORCE)'))
- await admin.dispose()
- sys.modules.pop(module_name, None)
- for candidate in (db_path, Path(f"{db_path}-wal"), Path(f"{db_path}-shm")):
- candidate.unlink(missing_ok=True)
+Its implementation lives in tests.database_fixtures, registered as a pytest
+plugin so controller queue tests and other sibling packages can share the same
+isolated SQLite/PostgreSQL setup without importing this directory's conftest.
+"""
diff --git a/server/tests/services/employees/test_reconcile_cli.py b/server/tests/services/employees/test_reconcile_cli.py
new file mode 100644
index 00000000..75aede05
--- /dev/null
+++ b/server/tests/services/employees/test_reconcile_cli.py
@@ -0,0 +1,67 @@
+"""The maintenance command reports NDJSON without invoking app startup."""
+from __future__ import annotations
+
+import argparse
+import json
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from services.employees import reconcile_jobs as reconcile
+
+
+def command(monkeypatch):
+ import core.config
+ import core.database
+ import sqlalchemy.ext.asyncio
+ from temporalio.client import Client
+
+ database = SimpleNamespace(startup=AsyncMock())
+ engine = SimpleNamespace(dispose=AsyncMock())
+ client = object()
+ connect = AsyncMock(return_value=client)
+ repair = AsyncMock(return_value=[])
+ monkeypatch.setattr(core.config, "Settings", lambda: SimpleNamespace(
+ database_url="sqlite+aiosqlite:///:memory:",
+ temporal_server_address="unused", temporal_namespace="default"))
+ monkeypatch.setattr(core.database, "Database", lambda _: database)
+ monkeypatch.setattr(sqlalchemy.ext.asyncio, "create_async_engine", lambda *args, **kwargs: engine)
+ monkeypatch.setattr(sqlalchemy.ext.asyncio, "async_sessionmaker", lambda *args, **kwargs: object())
+ monkeypatch.setattr(Client, "connect", connect)
+ monkeypatch.setattr(reconcile, "reconcile_jobs", repair)
+ return SimpleNamespace(database=database, engine=engine, client=client, connect=connect, repair=repair,
+ arguments=argparse.Namespace(workflow_id="graph", job_id=None, apply=False))
+
+
[email protected]("decisions", [[], [
+ {"workflow_id": "graph", "job_id": "job", "decision": "skip", "reason": "generation_paused_or_changed"},
+]])
+async def test_command_emits_parseable_reports_and_remains_dry_run(command, decisions, capsys):
+ command.repair.return_value = decisions
+
+ assert await reconcile._run_cli(command.arguments) == 0
+
+ lines = capsys.readouterr().out.splitlines()
+ reports = [json.loads(line) for line in lines]
+ assert reports == (decisions or [{"workflow_id": "graph", "job_id": None,
+ "decision": "skip", "reason": "no_matching_jobs"}])
+ command.repair.assert_awaited_once_with(command.database, command.client,
+ workflow_id="graph", job_id=None, apply=False)
+ command.database.startup.assert_not_awaited()
+ command.engine.dispose.assert_awaited_once()
+
+
+async def test_command_failure_reports_only_category_and_disposes(command, capsys):
+ command.connect.side_effect = RuntimeError("PRIVATE EMAIL CONTENT")
+
+ assert await reconcile._run_cli(command.arguments) == 1
+
+ output = capsys.readouterr().out
+ assert "PRIVATE" not in output
+ assert json.loads(output) == {"workflow_id": "graph", "job_id": None,
+ "decision": "skip", "reason": "connection_or_database_unavailable"}
+ command.repair.assert_not_awaited()
+ command.database.startup.assert_not_awaited()
+ command.engine.dispose.assert_awaited_once()
diff --git a/server/tests/services/test_versioned_workflow_control.py b/server/tests/services/test_versioned_workflow_control.py
index 9be8d6f6..d7a8d8ed 100644
--- a/server/tests/services/test_versioned_workflow_control.py
+++ b/server/tests/services/test_versioned_workflow_control.py
@@ -14,12 +14,13 @@ from services.deployment import execution_control
@pytest_asyncio.fixture(autouse=True)
async def drain_supervised_transitions():
yield
- tasks = list(handlers._control_transition_tasks.values())
+ tasks = [*handlers._control_transition_tasks.values(), *handlers._boot_reconciliation_tasks.values()]
for task in tasks:
task.cancel()
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
handlers._control_transition_tasks.clear()
+ handlers._boot_reconciliation_tasks.clear()
def control(state="pausing"):
@@ -507,3 +508,242 @@ async def test_workspace_observation_timeout_omits_unavailable_counts(monkeypatc
assert "workspace_active_count" not in snapshot
assert "generation_in_flight_count" not in snapshot
assert snapshot["in_flight_count"] == 2
+
+
+def boot_plane(monkeypatch, record, *, clean=True, policy="pause", additional=None):
+ from core.container import container
+
+ record.service.database.list_active_workflow_controls = AsyncMock(return_value=[copy(record.row), *(additional or [])])
+ monkeypatch.setattr(container, "database", lambda: record.service.database)
+ monkeypatch.setattr(handlers, "WorkflowControlService", lambda database: record.service)
+ monkeypatch.setattr(handlers, "_consume_shutdown_state", AsyncMock(return_value=clean))
+ monkeypatch.setattr(handlers, "_crash_recovery_policy", lambda: policy)
+ monkeypatch.setattr(handlers, "_BOOT_RETRY_SECONDS", 0.001)
+
+
[email protected]("intent,stable", [("pausing", "paused"), ("resuming", "running")])
+async def test_boot_pending_transition_restores_collectors_without_blocking_other_rows(monkeypatch, intent, stable):
+ record = lifecycle(monkeypatch, intent)
+ healthy = control("running")
+ healthy.id, healthy.workflow_id = "healthy-control", "healthy"
+ boot_plane(monkeypatch, record, additional=[healthy])
+ started, release = asyncio.Event(), asyncio.Event()
+ collectors = {}
+
+ async def transition(*args, **kwargs):
+ started.set()
+ await release.wait()
+ return {"controller_status": {}, "controlled_executions": 3}
+
+ async def rearm(current):
+ collectors[current.workflow_id] = current.status
+
+ monkeypatch.setattr(execution_control, "transition_generation", AsyncMock(side_effect=transition))
+ monkeypatch.setattr(handlers, "_rearm_generation", AsyncMock(side_effect=rearm))
+ assert await asyncio.wait_for(handlers.reconcile_active_controls_on_boot(), 0.2) == 2
+ await asyncio.wait_for(started.wait(), 0.2)
+ assert collectors == {"healthy": "running"}
+ boot_task = handlers._boot_reconciliation_tasks[(record.row.id, record.row.generation)]
+ release.set()
+ await asyncio.wait_for(asyncio.shield(boot_task), 0.5)
+ assert collectors == {"healthy": "running", "canvas": stable}
+ assert record.row.status == stable
+
+
[email protected]("policy,stable", [("pause", "paused"), ("resume", "running")])
+async def test_boot_interrupted_resume_obeys_unclean_shutdown_policy(monkeypatch, policy, stable):
+ record = lifecycle(monkeypatch, "resuming")
+ boot_plane(monkeypatch, record, clean=False, policy=policy)
+ started, release = asyncio.Event(), asyncio.Event()
+ collectors = []
+
+ async def transition(*args, **kwargs):
+ started.set()
+ await release.wait()
+ return {"controller_status": {}, "controlled_executions": 3}
+
+ async def rearm(current):
+ collectors.append(current.status)
+
+ monkeypatch.setattr(execution_control, "transition_generation", AsyncMock(side_effect=transition))
+ monkeypatch.setattr(handlers, "_rearm_generation", AsyncMock(side_effect=rearm))
+ assert await handlers.reconcile_active_controls_on_boot() == 1
+ await asyncio.wait_for(started.wait(), 0.2)
+ boot_task = handlers._boot_reconciliation_tasks[(record.row.id, record.row.generation)]
+ release.set()
+ await asyncio.wait_for(asyncio.shield(boot_task), 0.5)
+ assert collectors == [stable]
+ assert record.row.status == stable
+ if policy == "pause":
+ assert record.row.pause_reason == "recovery"
+
+
[email protected]("new_generation", [False, True])
+async def test_boot_continuation_cannot_rearm_reset_or_a_later_start(monkeypatch, new_generation):
+ record = lifecycle(monkeypatch, "pausing")
+ boot_plane(monkeypatch, record)
+ started, release = asyncio.Event(), asyncio.Event()
+
+ async def transition(*args, **kwargs):
+ started.set()
+ await release.wait()
+ return {"controller_status": {}, "controlled_executions": 3}
+
+ monkeypatch.setattr(execution_control, "transition_generation", AsyncMock(side_effect=transition))
+ rearm = AsyncMock()
+ monkeypatch.setattr(handlers, "_rearm_generation", rearm)
+ await handlers.reconcile_active_controls_on_boot()
+ await asyncio.wait_for(started.wait(), 0.2)
+ boot_task = handlers._boot_reconciliation_tasks[(record.row.id, record.row.generation)]
+ record.row = copy(record.row)
+ record.row.revision = 5
+ if new_generation:
+ record.row.id, record.row.generation, record.row.root_execution_id = "next-control", 2, "next-root"
+ record.row.status = "running"
+ else:
+ record.row.status = "reset"
+ release.set()
+ await asyncio.wait_for(asyncio.shield(boot_task), 0.5)
+ rearm.assert_not_awaited()
+ assert record.broadcasts == []
+
+
+async def test_boot_rearm_failure_keeps_admission_closed_and_retries_collectors(monkeypatch):
+ record = lifecycle(monkeypatch, "pausing")
+ boot_plane(monkeypatch, record)
+ started, release = asyncio.Event(), asyncio.Event()
+ effects = []
+
+ async def transition(*args, **kwargs):
+ started.set()
+ await release.wait()
+ return {"controller_status": {}, "controlled_executions": 3}
+
+ async def rearm(current):
+ effects.append("rearm")
+ if len(effects) == 1:
+ raise RuntimeError("collector startup failed")
+ effects.append("restored")
+
+ monkeypatch.setattr(execution_control, "transition_generation", AsyncMock(side_effect=transition))
+ monkeypatch.setattr(handlers, "_rearm_generation", AsyncMock(side_effect=rearm))
+ await handlers.reconcile_active_controls_on_boot()
+ await asyncio.wait_for(started.wait(), 0.2)
+ boot_task = handlers._boot_reconciliation_tasks[(record.row.id, record.row.generation)]
+ release.set()
+ await asyncio.wait_for(asyncio.shield(boot_task), 0.5)
+ assert effects == ["rearm", "rearm", "restored"]
+ assert record.row.status == "paused"
+ record.runtime.resume_deployment.assert_not_awaited()
+ handlers.handle_cancel_deployment.assert_not_awaited()
+
+
+async def test_boot_rearm_wait_is_bounded_and_reset_can_take_over(monkeypatch):
+ record = lifecycle(monkeypatch, "pausing")
+ boot_plane(monkeypatch, record)
+ monkeypatch.setattr(handlers, "_BOOT_REARM_TIMEOUT_SECONDS", 0.02)
+ restoring, retired = asyncio.Event(), asyncio.Event()
+
+ async def rearm(current):
+ restoring.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ retired.set()
+
+ monkeypatch.setattr(execution_control, "transition_generation",
+ AsyncMock(return_value={"controller_status": {}, "controlled_executions": 3}))
+ monkeypatch.setattr(handlers, "_rearm_generation", rearm)
+ await handlers.reconcile_active_controls_on_boot()
+ await asyncio.wait_for(restoring.wait(), 0.2)
+ boot_task = handlers._boot_reconciliation_tasks[(record.row.id, record.row.generation)]
+ reset = await asyncio.wait_for(handlers.handle_reset_workflow({
+ "workflow_id": "canvas", "expected_revision": 4,
+ }, None), 0.5)
+ assert reset["success"] and record.row.status == "reset"
+ assert retired.is_set()
+ await asyncio.gather(boot_task, return_exceptions=True)
+
+
+async def test_generation_scoped_reset_preempts_a_blocked_boot_setup_immediately(monkeypatch):
+ record = lifecycle(monkeypatch, "pausing")
+ boot_plane(monkeypatch, record)
+ restoring, retired = asyncio.Event(), asyncio.Event()
+
+ async def rearm(current):
+ restoring.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ retired.set()
+
+ monkeypatch.setattr(execution_control, "transition_generation",
+ AsyncMock(return_value={"controller_status": {}, "controlled_executions": 3}))
+ monkeypatch.setattr(handlers, "_rearm_generation", rearm)
+ await handlers.reconcile_active_controls_on_boot()
+ await asyncio.wait_for(restoring.wait(), 0.2)
+ boot_task = handlers._boot_reconciliation_tasks[(record.row.id, record.row.generation)]
+ reset = await asyncio.wait_for(handlers.handle_reset_workflow({
+ "workflow_id": "canvas", "expected_root_execution_id": "generation-root",
+ }, None), 0.2)
+ assert reset["success"] and record.row.status == "reset"
+ assert retired.is_set()
+ await asyncio.gather(boot_task, return_exceptions=True)
+
+
+async def test_boot_retry_awaits_existing_setup_receipt_instead_of_claiming_it_restored(monkeypatch):
+ record = lifecycle(monkeypatch, "pausing")
+ record.row.graph_snapshot = {"nodes": [{"id": "trigger", "type": "webhookTrigger"}], "edges": []}
+ boot_plane(monkeypatch, record)
+ monkeypatch.setattr(handlers, "_BOOT_REARM_TIMEOUT_SECONDS", 0.02)
+ deployed = False
+ setup_started, release_setup, gated = asyncio.Event(), asyncio.Event(), asyncio.Event()
+ previous_setup = handlers._deployment_tasks.pop("canvas", None)
+
+ async def setup():
+ setup_started.set()
+ await release_setup.wait()
+ return {"success": True}
+
+ async def deploy(*args, **kwargs):
+ nonlocal deployed
+ deployed = True
+ handlers._deployment_tasks["canvas"] = asyncio.create_task(setup())
+ return {"success": True}
+
+ def pause(_workflow_id):
+ if deployed:
+ gated.set()
+
+ record.runtime.is_workflow_deployed = lambda _: deployed
+ record.runtime.pause_deployment = pause
+ monkeypatch.setattr(handlers, "handle_deploy_workflow", AsyncMock(side_effect=deploy))
+ monkeypatch.setattr(execution_control, "transition_generation",
+ AsyncMock(return_value={"controller_status": {}, "controlled_executions": 3}))
+ try:
+ await handlers.reconcile_active_controls_on_boot()
+ boot_task = handlers._boot_reconciliation_tasks[(record.row.id, record.row.generation)]
+ await asyncio.wait_for(setup_started.wait(), 0.2)
+ await asyncio.wait_for(gated.wait(), 0.2)
+ setup_task = handlers._deployment_tasks["canvas"]
+ assert not setup_task.done() and not boot_task.done()
+ handlers.handle_cancel_deployment.assert_not_awaited()
+ release_setup.set()
+ await asyncio.wait_for(asyncio.shield(boot_task), 0.5)
+ handlers.handle_deploy_workflow.assert_awaited_once()
+ assert setup_task.done() and record.row.status == "paused"
+ record.runtime.update_trigger_pause_status.assert_awaited_with("canvas", paused=True)
+ finally:
+ setup_task = handlers._deployment_tasks.pop("canvas", None)
+ if setup_task is not None and not setup_task.done():
+ setup_task.cancel()
+ await asyncio.gather(setup_task, return_exceptions=True)
+ if previous_setup is not None:
+ handlers._deployment_tasks["canvas"] = previous_setup
diff --git a/server/tests/temporal/test_controller_queue.py b/server/tests/temporal/test_controller_queue.py
index fc2f69bb..685e9dd1 100644
--- a/server/tests/temporal/test_controller_queue.py
+++ b/server/tests/temporal/test_controller_queue.py
@@ -6,9 +6,9 @@ from unittest.mock import MagicMock
import pytest
from services.temporal.controller_queue import event_batches, spill_controller_events, read_controller_events
from services.temporal.workflow_control_workflow import WorkflowControlWorkflow
-from tests.services.employees.test_jobs import database as database
-async def test_durable_spill_is_idempotent_and_review_scan_reaches_buried_task(database, monkeypatch):
+async def test_durable_spill_is_idempotent_and_review_scan_reaches_buried_task(real_database, monkeypatch):
+ database = real_database
monkeypatch.setattr("core.container.container", SimpleNamespace(database=lambda: database))
ordinary = [["mail", {"id": str(i), "type": "mail"}] for i in range(150)]
payload = {"controller_id": "controller", "events": ordinary + [["review", {"id": "review", "type": "task"}]]}
@@ -31,7 +31,8 @@ def test_batches_are_bounded_by_bytes_not_only_event_count():
assert [item[1]["id"] for chunk in chunks for item in chunk] == [str(i) for i in range(12)]
-async def test_large_accepted_event_survives_chunked_rollover_once(database, wf, monkeypatch):
+async def test_large_accepted_event_survives_chunked_rollover_once(real_database, wf, monkeypatch):
+ database = real_database
monkeypatch.setattr("core.container.container", SimpleNamespace(database=lambda: database))
controller = WorkflowControlWorkflow()
item = ["mail", {"id": "large", "body": "x" * 1_700_000}]
diff --git a/server/tests/test_no_raw_prints.py b/server/tests/test_no_raw_prints.py
index bf024895..7c2cab26 100644
--- a/server/tests/test_no_raw_prints.py
+++ b/server/tests/test_no_raw_prints.py
@@ -7,12 +7,14 @@ processor chain — they don't get the level tag, don't get
``contextvars`` (``workflow_id`` / ``node_id``), don't go to the
RotatingFileHandler, and don't surface in the WebSocket Terminal panel.
-Three sanctioned exemptions, each documented in its own module:
+Sanctioned exemptions include, each documented in its own module:
1. ``main._startup_log`` — pre-logger boot-progress markers.
2. ``core.container._clog`` — same role for DI-container bootstrap.
3. ``nodes.code.python_executor.captured_print`` — the sandboxed
``print`` builtin we hand to user code (the user's print, not ours).
+4. ``services.employees.reconcile_jobs._run_cli`` — content-free NDJSON
+ command output consumed by maintenance scripts, rather than runtime logs.
Anything else must go through ``logger = get_logger(__name__)``. This
test parses every backend ``.py`` file under ``server/`` (excluding the
@@ -55,6 +57,9 @@ _SANCTIONED: List[Tuple[str, str]] = [
("nodes/browser/_pin.py", "main"),
# JSON wire replies to the parent process, not application log messages.
("nodes/mobile/runtime/device_server.py", "main"),
+ # One-shot maintenance CLI: stdout is its content-free NDJSON report,
+ # consumed by operators/scripts, rather than application log messages.
+ ("services/employees/reconcile_jobs.py", "_run_cli"),
]