Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
test(temporal): lock message handler names and the patch-marker lifecycle
trohitgd3f8e873d908
diff --git a/RFC-0005-EVENT-OS-ON-TEMPORAL.md b/RFC-0005-EVENT-OS-ON-TEMPORAL.mdindex fe0785b4..477a23e4 100644--- a/RFC-0005-EVENT-OS-ON-TEMPORAL.md+++ b/RFC-0005-EVENT-OS-ON-TEMPORAL.md@@ -1149,8 +1149,12 @@ Commit hashes are filled in when the phase ends.| Step | Commit | Notes ||---|---|---|-| 1.1 Pinned CLI | — | CLI v1.9.1 (server 1.32.0) is pinned in `server/config/temporal_cli.json` and verified with pooch's `known_hash`. It is installed under `packages/temporal/<version>/`, and every other CLI file there is deleted. `_install.prepare_database` deletes a `temporal.db` without the pinned server minor's marker. **Release note:** the first release with the pin starts every install on an empty Temporal database, so every employee needs Reset and Start. |-| 1.2 CI | — | `backend-tests` runs on ubuntu, windows and macos with full history. The app's installer puts the pinned CLI into a throwaway `DATA_DIR` and exports it as `TEMPORAL_TEST_CLI`, so the real-server tests run instead of skipping. Locally on Windows, all 8 of those items passed against the pinned binary. The first CI run on macOS is the first on that OS. |+| 1.1 Pinned CLI | — | CLI v1.9.1 (server 1.32.0) is pinned in `server/config/temporal_cli.json` and verified with pooch's `known_hash`. It is installed under `packages/temporal/<version>/`, and every other CLI file there is deleted. `_install.prepare_database` deletes a `temporal.db` without the pinned server minor's marker. The dev server also gets fairness and one task-queue partition from the pin's `dynamic_config` (T17); the marker records the partitions, and a database created with others starts from new. Commit 49177427 (another session) had replaced the deletion with keep-and-refuse; that was reverted after T5. **Release note:** the first release with the pin starts every install on an empty Temporal database, so every employee needs Reset and Start. |+| 1.2 CI | — | `backend-tests` runs on ubuntu, windows and macos with full history. The app's installer puts the pinned CLI into a throwaway `DATA_DIR` and exports it as `TEMPORAL_TEST_CLI`, so the real-server tests run instead of skipping. Locally on Windows, all 8 of those items passed against the pinned binary. The first CI run on macOS is the first on that OS. A gate step runs the replay and identity tests before the full suite, with `TEMPORAL_REQUIRE_NATIVE_REPLAY=1`. |+| 1.3 Fixture recorder | — | `server/tests/temporal/record_fixtures.py` records all 14 production types along 21 scenarios on a throwaway dev server, from a git archive of `--source-commit`. The 0.3.1 set, first recorded on CLI 1.8.0, was recorded again on the pinned 1.9.1 from the same commit: 51 histories. |+| 1.4 Replay gate | — | `test_replay_corpus.py` replays every set with `workflow_registry.replay_workflows()`, checking source provenance and coverage of all 14 types. A release-pipeline check fails a version without `fixtures/<version>/` or with a set recorded on another CLI than its pin. |+| 1.5 Golden identity test | — | `fixtures/workflow_identities.json` holds the release's commands and ids, handler names and plugin activity names. The test fails on unreviewed command changes, a patched marker that vanishes without a release of `deprecate_patch`, and a renamed or removed handler. |+| 1.6 temporalio 1.34.0 | — | Not started. |## 25. Defaults chosen and open itemsdiff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex d35562f5..52efbcaf 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -777,6 +777,53 @@ scratch data directory, never your own:`TEMPORAL_TEST_CLI=<the printed path>` and the same `DATA_DIR`, because thetests' child processes write under it.+### The replay safety net (RFC-0005 Phase 1)++Every change to workflow code must replay the previous release's histories and+keep that release's command identities:+- **Recorder.** `server/tests/temporal/record_fixtures.py` drives all 14+ production workflow types through 21 scenarios on a throwaway dev server+ running the pinned CLI, with fake activities under the production names. It+ writes `server/tests/temporal/fixtures/<package.json version>/`: one JSON+ file per scenario plus `manifest.json`, which names the origin commit, the+ SDK and the CLI. It loads the app from a git archive of `--source-commit`,+ never from the working tree, sets its own `DATA_DIR`, replays each history+ once before writing it, and refuses to overwrite a set. It runs when a+ release is cut ([ci_cd.md -> Cutting a release](./ci_cd.md#cutting-a-release)).+- **Replay gate.** `server/tests/temporal/test_replay_corpus.py` replays every+ set in a child process with `workflow_registry.replay_workflows()`: the+ framework list the workers register (`workflow_registry.framework_workflows`,+ imported by `worker.py` as `_framework_workflows`) plus the plugin workflows+ from the same plugin registry. It checks each workflow module's source hash+ against the set's origin commit, and fails when a production type has no+ history.+- **Golden identities.** `server/tests/temporal/fixtures/workflow_identities.json`+ holds the release's:+ - workflow types;+ - activity, child-workflow and patch commands with their ids+ (`workflow_identities.identity_snapshot`);+ - Signal, Update and Query handler names (`handler_snapshot`);+ - plugin activity names.++ `test_workflow_identity_golden.py` fails when:+ - commands change without a reviewed patch entry;+ - a patched marker vanishes before a release has shipped it as+ `deprecate_patch` (RFC-0005 §24.3);+ - a handler is renamed or removed;+ - a plugin activity name changes.++ New handlers and node types are fine.+ `record_fixtures --golden-only --source-commit <commit>` refreshes the file+ at each release.+- **Release check.** `test_the_current_version_has_its_replay_histories` in+ `cli/tests/test_release_pipeline_config.py` fails a version that has no+ `fixtures/<version>/`. It also fails a set recorded on another CLI than the+ one pinned when it was recorded.+- **CI.** `backend-tests` runs the gate as its own step before the full suite.+ That step first checks that `TEMPORAL_TEST_CLI` reports the pinned version+ (`_install.binary_versions`). The job sets `TEMPORAL_REQUIRE_NATIVE_REPLAY=1`,+ so a missing CLI fails the gate instead of skipping it.+What the user sees is documented in [Mobile workspace](../docs/mobile-workspace.md#resetting-phone-tasks)and [Browser workspace](browser_workspace.md#direct-browser-tasks).diff --git a/docs-internal/ci_cd.md b/docs-internal/ci_cd.mdindex a4b42783..4dadcad5 100644--- a/docs-internal/ci_cd.md+++ b/docs-internal/ci_cd.md@@ -97,6 +97,7 @@ Reusable `workflow_call` workflow with four independent jobs (no plan/change-det- `backend-tests` — cross-OS matrix (`ubuntu-latest`, `windows-latest`, `macos-latest`, `fail-fast: false`; RFC-0005 Phase 1). On Linux only, `uv lock --check` (the committed `server/uv.lock` must match `pyproject.toml`; the desktop app installs from it with `--frozen`) and a pinned `pip-audit` check of the locked Python dependencies including all extras. Then, on every OS:- **Pinned Temporal CLI.** The app's own installer (`services.temporal._install.ensure_temporal_binaries`) puts the CLI pinned in `server/config/temporal_cli.json` into a throwaway `DATA_DIR`, and the step writes its path to `$GITHUB_ENV` as `TEMPORAL_TEST_CLI`. The real-server tests that skip without it then run.- **Full history.** The checkout uses `fetch-depth: 0`, because two replay tests `git show` older commits.+ - **N-1 replay and identity gate.** Before the full suite, a step checks that `TEMPORAL_TEST_CLI` reports the pinned version (`_install.binary_versions`), then runs `test_replay_corpus.py`, `test_workflow_identity_golden.py` and `test_run_graph_replay.py`. The job sets `TEMPORAL_REQUIRE_NATIVE_REPLAY=1` (a missing CLI fails the gate instead of skipping it) and `DEBUG=false`. What the gate checks is in [TEMPORAL_ARCHITECTURE.md -> The replay safety net](./TEMPORAL_ARCHITECTURE.md#the-replay-safety-net-rfc-0005-phase-1).- **Tests.** `uv sync` + `uv run pytest tests/ -v` in `server/`, the whole suite, unsharded, under `shell: bash` on every OS.- **Lock.** `test_backend_tests_run_on_every_os_with_the_pinned_temporal_cli` locks this.- `cli-tests` — `uv pip install --system pytest pytest-asyncio pyyaml` + `python -m pytest cli/tests/ -v`. Runs on `ubuntu-latest`.@@ -181,6 +182,9 @@ had lapsed or one registry failed.`server/tests/temporal/fixtures/X.Y.Z/` and refuses to overwrite anexisting set. `test_the_current_version_has_its_replay_histories` in`cli/tests/test_release_pipeline_config.py` fails a version without one.+ Then the same command with `--golden-only` rewrites+ `fixtures/workflow_identities.json` from that commit, so the next cycle's+ identity checks compare against this release.3. **Tag.** `git tag -a vX.Y.Z -F notes.md` on that commit, the notes in theshape of the previous tags (`git tag -l --format='%(contents)' v0.1.0`).4. **Push** the branch, then the tag. The tag starts `release.yml` (predeploydiff --git a/server/tests/temporal/fixtures/workflow_identities.json b/server/tests/temporal/fixtures/workflow_identities.jsonindex 9bb575c3..507d22e5 100644--- a/server/tests/temporal/fixtures/workflow_identities.json+++ b/server/tests/temporal/fixtures/workflow_identities.json@@ -940,6 +940,90 @@}},"patch_entries": [],+ "handlers": {+ "DelegatedTaskWorkflow": [+ "query:execution_control_status",+ "signal:pause",+ "signal:resume",+ "update:set_control_state",+ "update:wait_for_checkpoint"+ ],+ "AgentWorkflow": [+ "query:execution_control_status",+ "signal:pause",+ "signal:resume",+ "update:set_control_state",+ "update:wait_for_checkpoint"+ ],+ "ApprovedToolCallWorkflow": [],+ "EmployeeJobWorkflow": [+ "query:execution_control_status",+ "update:set_control_state",+ "update:wait_for_checkpoint"+ ],+ "EmployeeJobDeliveryWorkflow": [],+ "NodeInvocationWorkflow": [+ "query:describe"+ ],+ "PiInlineDelegationWorkflow": [+ "query:execution_control_status",+ "update:set_control_state",+ "update:wait_for_checkpoint"+ ],+ "PiCodingAgentWorkflow": [+ "query:operation_status",+ "signal:pause",+ "signal:resume",+ "update:assistant_ready",+ "update:register_driver",+ "update:submit_operation",+ "update:wait_for_checkpoint"+ ],+ "PollingTriggerWorkflow": [+ "signal:pause",+ "signal:resume"+ ],+ "TriggerListenerWorkflow": [+ "signal:on_event",+ "signal:pause",+ "signal:resume"+ ],+ "MachinaWorkflow": [+ "query:execution_control_status",+ "signal:on_event",+ "signal:pause",+ "signal:resume",+ "update:set_control_state",+ "update:wait_for_checkpoint"+ ],+ "WorkflowControlWorkflow": [+ "query:execution_control_status",+ "query:status",+ "signal:on_event",+ "signal:pause",+ "signal:register_trigger",+ "signal:reset",+ "signal:resume",+ "update:pause_admissions",+ "update:register_execution",+ "update:replace_graph",+ "update:set_control_state",+ "update:unregister_execution",+ "update:wait_for_checkpoint"+ ],+ "WorkspaceTaskControllerWorkflow": [+ "query:describe",+ "update:reset",+ "update:submit"+ ],+ "CronTriggerWorkflow": [+ "query:execution_control_status",+ "signal:pause",+ "signal:resume",+ "update:set_control_state",+ "update:wait_for_checkpoint"+ ]+ },"plugin_activity_types": {"aiAgent": "node.aiAgent.v1","ai_employee": "node.ai_employee.v1",diff --git a/server/tests/temporal/record_fixtures.py b/server/tests/temporal/record_fixtures.pyindex 6de8c542..71c34cfd 100644--- a/server/tests/temporal/record_fixtures.py+++ b/server/tests/temporal/record_fixtures.py@@ -1107,7 +1107,7 @@ def write_golden(source_root: Path, commit: str) -> None:from services.node_registry import registered_node_classesfrom services.temporal.worker import _framework_workflowsfrom services.temporal.plugin_registry import temporal_plugins- from tests.temporal.workflow_identities import identity_snapshot+ from tests.temporal.workflow_identities import handler_snapshot, identity_snapshotregistrations = {"workflows": _framework_workflows()}for plugin in temporal_plugins():@@ -1116,6 +1116,7 @@ def write_golden(source_root: Path, commit: str) -> None:"origin_commit": commit,"workflow_types": sorted(item.__temporal_workflow_definition.name for item in registrations["workflows"]),"identities": identity_snapshot(source_root), "patch_entries": [],+ "handlers": handler_snapshot(source_root),"plugin_activity_types": {name: f"node.{cls.type}.v{cls.version}" for name, cls in registered_node_classes().items()},}, indent=2) + "\n", encoding="utf-8")diff --git a/server/tests/temporal/test_workflow_identity_golden.py b/server/tests/temporal/test_workflow_identity_golden.pyindex 1ec3ef16..6a006ba8 100644--- a/server/tests/temporal/test_workflow_identity_golden.py+++ b/server/tests/temporal/test_workflow_identity_golden.py@@ -2,13 +2,27 @@from __future__ import annotationsimport json+import textwrapfrom pathlib import Path-from tests.temporal.workflow_identities import digest, identity_snapshot+from tests.temporal.workflow_identities import digest, handler_snapshot, identity_snapshotGOLDEN = Path(__file__).with_name("fixtures") / "workflow_identities.json"+def _markers(snapshot: dict, command: str) -> set[str]:+ return {item["type"].strip("'\"") for module in snapshot.values() for item in module["commands"] if item["command"] == command}+++def _vanished_markers(release: dict, current: dict) -> set[str]:+ return _markers(release, "patched") - _markers(current, "patched") - _markers(current, "deprecate_patch")+++def _missing_handlers(release: dict, current: dict) -> dict[str, list[str]]:+ missing = {name: sorted(set(handlers) - set(current.get(name, []))) for name, handlers in release.items()}+ return {name: handlers for name, handlers in missing.items() if handlers}++def test_workflow_command_identities_match_release_or_explicit_patch_entry():golden = json.loads(GOLDEN.read_text(encoding="utf-8"))current = identity_snapshot()@@ -17,11 +31,74 @@ def test_workflow_command_identities_match_release_or_explicit_patch_entry():before, after = digest(golden["identities"]), digest(current)entries = [entry for entry in golden.get("patch_entries", []) if entry["before"] == before and entry["after"] == after]assert entries, "Temporal activity names/child IDs/markers changed: add a reviewed versioning patch entry and replay N-1 histories"- markers = {command["type"].strip("'\"") for module in current.values() for command in module["commands"]- if command["command"] in {"patched", "deprecate_patch"}}+ markers = _markers(current, "patched") | _markers(current, "deprecate_patch")assert all(entry.get("patch") in markers and entry.get("reason") for entry in entries)+def test_patch_markers_move_to_deprecated_before_they_vanish():+ """RFC-0005 §24.3: a marker the release patches stays in the code, as+ ``workflow.patched`` or ``workflow.deprecate_patch``; only one the release+ already deprecated may be removed, a release later."""+ golden = json.loads(GOLDEN.read_text(encoding="utf-8"))+ vanished = _vanished_markers(golden["identities"], identity_snapshot())+ assert not vanished, f"Patch markers removed without a release of deprecate_patch: {sorted(vanished)}"+++def test_the_marker_rule_allows_deprecation_and_catches_removal():+ def snapshot(*commands):+ return {"m.py": {"commands": [{"command": command, "type": f'"{marker}"'} for command, marker in commands]}}++ release = snapshot(("patched", "x-v1"), ("deprecate_patch", "y-v1"))+ assert not _vanished_markers(release, snapshot(("patched", "x-v1")))+ assert not _vanished_markers(release, snapshot(("deprecate_patch", "x-v1")))+ assert _vanished_markers(release, snapshot(("deprecate_patch", "y-v1"))) == {"x-v1"}+++def test_message_handlers_are_never_renamed_or_removed():+ """A recorded Signal or Update names its handler, so open runs of the+ release would lose one that is renamed or removed. New handlers are fine."""+ golden = json.loads(GOLDEN.read_text(encoding="utf-8"))+ missing = _missing_handlers(golden["handlers"], handler_snapshot())+ assert not missing, f"Message handlers renamed or removed: {missing}"+++def test_the_handler_rule_allows_additions_and_catches_renames():+ release = {"W": ["signal:pause", "update:set_control_state"]}+ assert not _missing_handlers(release, {"W": ["signal:pause", "signal:wake", "update:set_control_state"]})+ assert _missing_handlers(release, {"W": ["signal:pause", "update:set_state"]}) == {"W": ["update:set_control_state"]}+ assert _missing_handlers(release, {}) == {"W": ["signal:pause", "update:set_control_state"]}+++def test_the_handler_inventory_reads_names_from_the_decorators(tmp_path):+ temporal = tmp_path / "services" / "temporal"+ temporal.mkdir(parents=True)+ cron = tmp_path / "nodes" / "scheduler" / "cron_scheduler"+ cron.mkdir(parents=True)+ (cron / "_workflow.py").write_text("", encoding="utf-8")+ (temporal / "probe.py").write_text(textwrap.dedent('''\+ from temporalio import workflow++ NAME = "ProbeWorkflow"+++ @workflow.defn(name=NAME, sandboxed=False)+ class Probe:+ @workflow.signal+ def pause(self): ...++ @workflow.update(name="apply")+ async def apply_change(self): ...++ @workflow.query+ def status(self): ...++ @workflow.signal(dynamic=True)+ def other(self, name, args): ...+ '''), encoding="utf-8")++ assert handler_snapshot(tmp_path) == {"ProbeWorkflow": ["query:status", "signal:<dynamic>", "signal:pause", "update:apply"]}++def test_worker_and_replayer_use_the_shared_production_registry():from services.temporal.worker import _framework_workflowsfrom services.temporal.workflow_registry import framework_workflows, replay_workflowsdiff --git a/server/tests/temporal/workflow_identities.py b/server/tests/temporal/workflow_identities.pyindex 7263c25a..db8db786 100644--- a/server/tests/temporal/workflow_identities.py+++ b/server/tests/temporal/workflow_identities.py@@ -8,13 +8,70 @@ from pathlib import PathSERVER = Path(__file__).resolve().parents[2]COMMANDS = {"execute_activity", "start_activity", "execute_child_workflow", "start_child_workflow", "patched", "deprecate_patch"}+HANDLERS = {"signal", "update", "query"}-def identity_snapshot(source_root: Path = SERVER) -> dict:+def _workflow_modules(source_root: Path) -> list[Path]:paths = sorted((source_root / "services" / "temporal").glob("*.py"))paths.append(source_root / "nodes" / "scheduler" / "cron_scheduler" / "_workflow.py")+ return paths+++def _is_workflow_attr(node: ast.expr, names: set[str]) -> bool:+ return isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == "workflow" and node.attr in names+++def handler_snapshot(source_root: Path = SERVER) -> dict:+ """Signal, Update and Query handler names per workflow type.++ A recorded Signal or Update names its handler, so renaming or removing+ one breaks open runs; adding one does not. Names default to the method+ name, as in the SDK.+ """+ result = {}+ for path in _workflow_modules(source_root):+ tree = ast.parse(path.read_text(encoding="utf-8"))+ strings = _module_strings(tree)++ def option(call: ast.expr, key: str) -> object:+ for kw in getattr(call, "keywords", []):+ if kw.arg == key:+ if isinstance(kw.value, ast.Constant):+ return kw.value.value+ return strings.get(kw.value.id, ast.unparse(kw.value)) if isinstance(kw.value, ast.Name) else ast.unparse(kw.value)+ return None++ for cls in tree.body:+ if not isinstance(cls, ast.ClassDef):+ continue+ defn = next((dec for dec in cls.decorator_list if _is_workflow_attr(dec.func if isinstance(dec, ast.Call) else dec, {"defn"})), None)+ if defn is None:+ continue+ handlers = []+ for method in cls.body:+ if not isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)):+ continue+ for dec in method.decorator_list:+ target = dec.func if isinstance(dec, ast.Call) else dec+ if _is_workflow_attr(target, HANDLERS):+ name = "<dynamic>" if option(dec, "dynamic") else option(dec, "name") or method.name+ handlers.append(f"{target.attr}:{name}")+ result[option(defn, "name") or cls.name] = sorted(handlers)+ return result+++def _module_strings(tree: ast.Module) -> dict[str, str]:+ """Module-level ``NAME = "text"`` constants, which commands and decorators reference by name."""+ strings = {}+ for node in tree.body:+ if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):+ strings.update({target.id: node.value.value for target in node.targets if isinstance(target, ast.Name)})+ return strings+++def identity_snapshot(source_root: Path = SERVER) -> dict:result = {}- for path in paths:+ for path in _workflow_modules(source_root):tree = ast.parse(path.read_text(encoding="utf-8"))has_workflow = any(isinstance(node, ast.ClassDef) and any(isinstance(dec, ast.Call) and isinstance(dec.func, ast.Attribute) and dec.func.attr == "defn"@@ -25,10 +82,7 @@ def identity_snapshot(source_root: Path = SERVER) -> dict:and node.func.attr in COMMANDS for node in ast.walk(tree))if not has_workflow and not has_commands:continue- strings = {}- for node in tree.body:- if isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):- strings.update({target.id: node.value.value for target in node.targets if isinstance(target, ast.Name)})+ strings = _module_strings(tree)commands, identifiers, bindings = [], [], []for node in ast.walk(tree):if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr in COMMANDS: