Skip to content

Self-improving AI Employees for everyone

feat(temporal): _pop_matching_event helper on MachinaWorkflow (Wave 12 A7 completion)

trohitg0e835e200381
diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.py
index 4d1e594e..b14c5562 100644
--- a/server/services/temporal/workflow.py
+++ b/server/services/temporal/workflow.py
@@ -12,7 +12,7 @@ This enables massive horizontal scaling and multi-tenant distribution.
"""
from datetime import timedelta
-from typing import Any, Dict, List, Set
+from typing import Any, Dict, List, Optional, Set
from temporalio import workflow
from temporalio.common import RetryPolicy
@@ -148,6 +148,32 @@ class MachinaWorkflow:
return True
return any(predicate(e) for e in self._matched_events)
+ def _pop_matching_event(self, predicate=None) -> Optional[Dict[str, Any]]:
+ """Wave 12 A7: dequeue the first event that satisfies ``predicate``.
+
+ Pairs with :meth:`_has_event_matching` — Phase C1 trigger
+ waiters call ``wait_condition`` on the predicate, then pop the
+ actual envelope here. FIFO order: the predicate is evaluated
+ against the head of ``_matched_events`` first, so events
+ arrive in the order Temporal delivered the signals (and on
+ replay, the order Event History records them — deterministic).
+
+ Returns ``None`` if no queued event matches; callers should
+ only reach this method after ``wait_condition`` resolves, in
+ which case at least one match exists. The ``None`` return path
+ exists for defensive symmetry — never silently raises mid-
+ replay.
+
+ Determinism note: list mutation inside a workflow is safe per
+ Temporal's Python SDK contract (the workflow's local state is
+ rebuilt from Event History on replay; the same signals deliver
+ the same envelopes, so the same pops happen in the same order).
+ """
+ for idx, event in enumerate(self._matched_events):
+ if predicate is None or predicate(event):
+ return self._matched_events.pop(idx)
+ return None
+
@workflow.run
async def run(self, workflow_data: Dict[str, Any]) -> Dict[str, Any]:
"""Execute workflow by orchestrating node activities.
diff --git a/server/tests/test_event_framework_phase_a.py b/server/tests/test_event_framework_phase_a.py
index 37960648..d6ee659b 100644
--- a/server/tests/test_event_framework_phase_a.py
+++ b/server/tests/test_event_framework_phase_a.py
@@ -265,6 +265,53 @@ class TestA7MachinaWorkflowSignalHandler:
lambda e: e["type"].endswith(".nope")
) is False
+ def test_pop_matching_event_empty_returns_none(self):
+ from services.temporal.workflow import MachinaWorkflow
+
+ wf = MachinaWorkflow()
+ assert wf._pop_matching_event() is None
+ assert wf._pop_matching_event(lambda e: True) is None
+
+ def test_pop_matching_event_no_predicate_returns_fifo_head(self):
+ from services.temporal.workflow import MachinaWorkflow
+
+ wf = MachinaWorkflow()
+ first = {"id": "e1", "type": "com.machinaos.x.received"}
+ second = {"id": "e2", "type": "com.machinaos.y.received"}
+ wf._matched_events.extend([first, second])
+
+ popped = wf._pop_matching_event()
+ assert popped is first
+ assert wf._matched_events == [second]
+
+ def test_pop_matching_event_predicate_picks_first_match(self):
+ from services.temporal.workflow import MachinaWorkflow
+
+ wf = MachinaWorkflow()
+ first = {"id": "e1", "type": "com.machinaos.x.received"}
+ second = {"id": "e2", "type": "com.machinaos.y.received"}
+ third = {"id": "e3", "type": "com.machinaos.x.delivered"}
+ wf._matched_events.extend([first, second, third])
+
+ popped = wf._pop_matching_event(
+ lambda e: e["type"].startswith("com.machinaos.y")
+ )
+ assert popped is second
+ # Order preserved for non-matching siblings.
+ assert wf._matched_events == [first, third]
+
+ def test_pop_matching_event_no_predicate_match_returns_none(self):
+ from services.temporal.workflow import MachinaWorkflow
+
+ wf = MachinaWorkflow()
+ wf._matched_events.append(
+ {"id": "e1", "type": "com.machinaos.x.received"}
+ )
+ result = wf._pop_matching_event(lambda e: e["type"].endswith(".nope"))
+ assert result is None
+ # Queue untouched on miss.
+ assert len(wf._matched_events) == 1
+
class TestA8EmitEventActivity:
"""A8: activity wrapper validates the envelope and forwards to emit."""