Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(temporal): run the dev server with fairness and one task-queue partition
trohitg1ffb3f698a9a
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex 27b4b0d9..d35562f5 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -958,9 +958,9 @@ client = await Client.connect(server_address, namespace=namespace, runtime=runtiThe Temporal binary + persistence are managed in-process by the plugin-folder pattern at [`server/services/temporal/`](../server/services/temporal/). Single supervised process — the official `temporal` CLI's `server start-dev` mode, per [docs.temporal.io/develop/python/set-up-your-local-python](https://docs.temporal.io/develop/python/set-up-your-local-python). The server-management sibling files (`_install.py`, `_runtime.py`, `_handlers.py`, `_refresh.py`, `lifecycle.py`, `client.py`, plus `__init__.py` for registry wiring) match the [Wave 11 plugin-folder pattern](./plugin_system.md#self-contained-plugin-folders) that `server/nodes/whatsapp/` uses for its Go binary; the rest of the package (see the file structure above) is the execution engine itself.-**What runs**: one process — `temporal server start-dev --port $TEMPORAL_FRONTEND_GRPC_PORT --ui-port $TEMPORAL_UI_PORT --db-filename ~/.opencompany/temporal.db --namespace default`. Both gRPC + Web UI bind to the same process (per docs.temporal.io/cli/server — "all running in a single process"). SQLite-backed durability; history persisted across restarts.+**What runs**: one process — `temporal server start-dev --port $TEMPORAL_FRONTEND_GRPC_PORT --ui-port $TEMPORAL_UI_PORT --db-filename ~/.opencompany/temporal.db --namespace default`, plus the pin's `dynamic_config` as `--dynamic-config-value` flags on every boot, because start-dev reads dynamic config only from its flags: `matching.enableFairness=true` and one task-queue partition (`matching.numTaskqueueReadPartitions=1`, `matching.numTaskqueueWritePartitions=1`; RFC-0006 T17). Both gRPC + Web UI bind to the same process (per docs.temporal.io/cli/server — "all running in a single process"). SQLite-backed durability; history persisted across restarts.-**A new server minor starts from an empty database** (RFC-0005 E16). `temporal.db.server.json` beside the database names the server that created it, and `_install.prepare_database` runs before every spawn. A database with no marker, or with one naming another server minor than the pin, is deleted together with its `-wal` and `-shm` files, so the pinned server starts empty; a patch release of the same minor keeps the database. Nothing is migrated:+**A new server minor starts from an empty database** (RFC-0005 E16). `temporal.db.server.json` beside the database names the server that created it and its task-queue partition values, and `_install.prepare_database` runs before every spawn. A database with no marker, with one naming another server minor than the pin, or with other partition values than the pin's (partitions can be lowered safely only on a new database), is deleted together with its `-wal` and `-shm` files, and every CLI file that is not the pin's goes with it, so the pinned server starts empty; a patch release of the same minor keeps the database. Nothing is migrated:- Every generation whose controller lived in the old database fails at boot with `controller_execution_missing`, and its owner resets and starts it, which clears its chat thread and Context.- In-flight runs, Schedules, queued controller events and Temporal history are gone.- The first release with the pin does this on every install, because no database before it has a marker. Its release notes must say so: it breaks the N-1 upgrade contract (RFC-0004 Q1) once, by the owner's choice of 2026-10-23.diff --git a/server/config/temporal_cli.json b/server/config/temporal_cli.jsonindex 70815b53..aaf222d8 100644--- a/server/config/temporal_cli.json+++ b/server/config/temporal_cli.json@@ -1,7 +1,12 @@{- "_comment": "The Temporal CLI pin (services/temporal/_install.py). Asset keys are <os>_<arch> in the CLI release's spellings. Bump the version, server_version and all checksums together from the official checksums.txt. A new server minor starts every install from an empty Temporal database: at the next start, a database the pinned server minor did not create is deleted with every older CLI file (RFC-0005 E16). A patch bump of the same minor keeps the database.",+ "_comment": "The Temporal CLI pin (services/temporal/_install.py). Asset keys are <os>_<arch> in the CLI release's spellings. Bump the version, server_version and all checksums together from the official checksums.txt. A new server minor starts every install from an empty Temporal database: at the next start, a database the pinned server minor did not create is deleted with every older CLI file (RFC-0005 E16). A patch bump of the same minor keeps the database. dynamic_config is passed to start-dev on every boot (RFC-0006 T17): fairness on and one task-queue partition. The marker records the partition values, and a database created with others starts from new, because partitions can be lowered safely only on a new database.","version": "1.9.1","server_version": "1.32.0",+ "dynamic_config": {+ "matching.enableFairness": true,+ "matching.numTaskqueueReadPartitions": 1,+ "matching.numTaskqueueWritePartitions": 1+ },"base": "https://github.com/temporalio/cli/releases/download/v{version}/","assets": {"linux_amd64": { "file": "temporal_cli_1.9.1_linux_amd64.tar.gz", "sha256": "09a0326a51db84d02735e53542b9ebd8c4758daf47482a9ab0abce15844e60d5" },diff --git a/server/services/temporal/_install.py b/server/services/temporal/_install.pyindex f49e7a16..7691af20 100644--- a/server/services/temporal/_install.py+++ b/server/services/temporal/_install.py@@ -10,13 +10,15 @@ a re-run is a cache hit and a tampered or truncated download fails.A new Temporal server minor starts from an empty database (RFC-0005 E16).``temporal.db.server.json`` beside the database names the server that-created it, and :func:`prepare_database` runs before every spawn. A-database with no marker, or with one naming another server minor than the-pin, is deleted together with its ``-wal`` and ``-shm`` files, and every-CLI file that is not the pin's goes with it. Nothing is migrated:-generations whose controller lived in the old database fail with-``controller_execution_missing``, and owners Reset and Start them. A patch-release of the same minor keeps the database.+created it and the task-queue partitions it was created with, and+:func:`prepare_database` runs before every spawn. A database with no+marker, with one naming another server minor than the pin, or with other+partition values than the pin's ``dynamic_config`` (partitions can be+lowered safely only on a new database, RFC-0006 T17), is deleted together+with its ``-wal`` and ``-shm`` files, and every CLI file that is not the+pin's goes with it. Nothing is migrated: generations whose controller lived+in the old database fail with ``controller_execution_missing``, and owners+Reset and Start them. A patch release of the same minor keeps the database.The downloaded ``temporal`` CLI powers ``temporal server start-dev``(the SQLite dev server) and ad-hoc workflow / operator commands.@@ -154,19 +156,33 @@ def marker_path(db_path: Path) -> Path:return db_path.with_name(db_path.name + ".server.json")+# The dynamic-config values a database keeps from its creation: lowering read+# partitions on an existing database strands the tasks in the removed ones.+_CREATION_KEYS = ("matching.numTaskqueueReadPartitions", "matching.numTaskqueueWritePartitions")+++def _partitions(pin: dict[str, Any]) -> dict[str, Any]:+ return {key: pin["dynamic_config"][key] for key in _CREATION_KEYS}++def prepare_database(db_path: Path) -> None:"""Start from an empty database unless the pin's server minor created it.Runs before every spawn. A database whose marker names the pin's server- minor is kept. Otherwise the database, its ``-wal`` and ``-shm`` files and- every CLI file that is not the pin's are deleted, and the pin's marker is- written, so ``start-dev`` creates an empty database for the pinned server.- A database that cannot be deleted stops the start: the pinned server must- never open another minor's schema.+ minor and partition values is kept. Otherwise the database, its ``-wal``+ and ``-shm`` files and every CLI file that is not the pin's are deleted,+ and the pin's marker is written, so ``start-dev`` creates an empty+ database for the pinned server. A database that cannot be deleted stops+ the start: the pinned server must never open another minor's schema."""pin = cli_pin()marker = marker_path(db_path)- if _server_minor(_recorded_server(marker)) == _server_minor(pin["server_version"]):+ recorded = _read_marker(marker)+ if (+ recorded is not None+ and _server_minor(recorded.get("server_version")) == _server_minor(pin["server_version"])+ and recorded.get("partitions") == _partitions(pin)+ ):returnstale = [path for path in (db_path, Path(f"{db_path}-wal"), Path(f"{db_path}-shm")) if path.exists()]for path in stale:@@ -180,7 +196,12 @@ def prepare_database(db_path: Path) -> None:)_remove_unpinned_clis(pin["version"])db_path.parent.mkdir(parents=True, exist_ok=True)- record = {"cli_version": pin["version"], "server_version": pin["server_version"], "created_at": datetime.now(timezone.utc).isoformat()}+ record = {+ "cli_version": pin["version"],+ "server_version": pin["server_version"],+ "partitions": _partitions(pin),+ "created_at": datetime.now(timezone.utc).isoformat(),+ }marker.write_text(json.dumps(record), encoding="utf-8")@@ -202,11 +223,13 @@ def _remove_unpinned_clis(version: str) -> None:logger.warning("[Temporal install] Could not delete an old Temporal CLI file %s: %s", entry, exc)-def _recorded_server(marker: Path) -> object:+def _read_marker(marker: Path) -> dict[str, Any] | None:+ """The marker's record, or ``None`` when it is missing or unreadable."""try:- return json.loads(marker.read_text(encoding="utf-8"))["server_version"]- except (OSError, ValueError, KeyError, TypeError):+ record = json.loads(marker.read_text(encoding="utf-8"))+ except (OSError, ValueError):return None+ return record if isinstance(record, dict) else Nonedef _server_minor(version: object) -> str | None:diff --git a/server/services/temporal/_runtime.py b/server/services/temporal/_runtime.pyindex ee0832d2..07938085 100644--- a/server/services/temporal/_runtime.py+++ b/server/services/temporal/_runtime.py@@ -16,6 +16,7 @@ Uses the singleton accessor pattern (``Class.get_instance()``) fromfrom __future__ import annotationsimport asyncio+import jsonimport osimport sysfrom pathlib import Path@@ -125,6 +126,15 @@ class TemporalServerRuntime(BaseProcessSupervisor):# --metrics-port 0 disables the Prometheus endpoint# --log-level warn keeps the supervisor log readable# --namespace default namespace bootstrapped at start+ # --dynamic-config-value the pin's dynamic_config+ # (server/config/temporal_cli.json), on every boot,+ # because start-dev reads dynamic config only from+ # its flags: fairness on and one task-queue+ # partition (RFC-0006 T17).+ # The database marker records the partitions,+ # which can be lowered safely only on a new+ # database, so ``_pre_spawn`` resets one created+ # with other values.# --sqlite-pragma SQLite tuning, repeatable PRAGMA=VALUE.# journal_mode=WAL + synchronous=NORMAL +# busy_timeout let the single-writer SQLite@@ -141,6 +151,11 @@ class TemporalServerRuntime(BaseProcessSupervisor):# WAL is durable and synchronous=NORMAL is# WAL-safe (no corruption). See SQLite WAL# docs + https://docs.temporal.io/cli/server.+ from services.temporal._install import cli_pin++ dynamic_config: list[str] = []+ for key, value in cli_pin()["dynamic_config"].items():+ dynamic_config += ["--dynamic-config-value", f"{key}={json.dumps(value)}"]return [str(self.binary_path()),"server",@@ -157,6 +172,7 @@ class TemporalServerRuntime(BaseProcessSupervisor):"warn","--namespace",self.settings.temporal_namespace,+ *dynamic_config,"--sqlite-pragma","journal_mode=WAL","--sqlite-pragma",diff --git a/server/tests/temporal/test_cli_pin.py b/server/tests/temporal/test_cli_pin.pyindex 5c8ba594..bbdcb217 100644--- a/server/tests/temporal/test_cli_pin.py+++ b/server/tests/temporal/test_cli_pin.py@@ -2,7 +2,9 @@RFC-0004 D1 and RFC-0005 E16: the CLI is a checksum pin, and a databasethe pinned server minor did not create is deleted with every older CLI-file, so the pinned server starts from an empty database.+file, so the pinned server starts from an empty database. RFC-0006 T17:+the dev server runs with fairness and one task-queue partition, and a+database created with other partition values starts from new too."""from __future__ import annotations@@ -25,8 +27,14 @@ def _write_db(db: Path) -> None:path.write_bytes(b"temporal state")-def _write_marker(db: Path, server_version: str) -> None:- _install.marker_path(db).write_text(json.dumps({"server_version": server_version}), encoding="utf-8")+ONE_PARTITION = {"matching.numTaskqueueReadPartitions": 1, "matching.numTaskqueueWritePartitions": 1}+++def _write_marker(db: Path, server_version: str, partitions: dict | None = ONE_PARTITION) -> None:+ record = {"server_version": server_version}+ if partitions is not None:+ record["partitions"] = partitions+ _install.marker_path(db).write_text(json.dumps(record), encoding="utf-8")def _read_marker(db: Path) -> dict:@@ -73,6 +81,32 @@ def test_pin_names_one_exact_release_with_a_hash_for_every_platform():assert re.fullmatch(r"[0-9a-f]{64}", asset["sha256"])+def test_pin_turns_on_fairness_with_one_task_queue_partition():+ assert _install.cli_pin()["dynamic_config"] == {"matching.enableFairness": True, **ONE_PARTITION}+++def test_the_dev_server_passes_the_pin_dynamic_config_on_every_start(tmp_path):+ settings = SimpleNamespace(+ temporal_graceful_shutdown_seconds=5,+ temporal_sqlite_path="temporal.db",+ temporal_frontend_grpc_port=7233,+ temporal_ui_port=8233,+ temporal_namespace="default",+ _resolve_under_data=lambda path: str(tmp_path / path),+ )+ runtime = _runtime.TemporalServerRuntime(settings=settings)+ runtime._binaries = {"temporal": tmp_path / "temporal"}++ argv = runtime.argv()++ values = [argv[index + 1] for index, arg in enumerate(argv) if arg == "--dynamic-config-value"]+ assert values == [+ "matching.enableFairness=true",+ "matching.numTaskqueueReadPartitions=1",+ "matching.numTaskqueueWritePartitions=1",+ ]++def test_fetch_verifies_the_pinned_archive_into_its_versioned_folder(tmp_path, monkeypatch):monkeypatch.setattr(_install, "_cache_dir", lambda: tmp_path)monkeypatch.setattr(_install.platform, "system", lambda: "Linux")@@ -129,6 +163,7 @@ def test_a_new_install_records_the_pinned_server_beside_its_database(tmp_path, mmarker = _read_marker(db)assert marker["cli_version"] == pin["version"]assert marker["server_version"] == pin["server_version"]+ assert marker["partitions"] == ONE_PARTITIONassert marker["created_at"]@@ -162,6 +197,22 @@ def test_another_server_minor_starts_from_new(tmp_path, monkeypatch):assert _read_marker(db)["server_version"] == _install.cli_pin()["server_version"]+def test_a_database_created_with_other_partitions_starts_from_new(tmp_path, monkeypatch):+ root = tmp_path / "packages"+ root.mkdir()+ monkeypatch.setattr(_install, "_cache_dir", lambda: root)+ pinned_server = _install.cli_pin()["server_version"]+ for partitions in (None, {"matching.numTaskqueueReadPartitions": 4, "matching.numTaskqueueWritePartitions": 4}):+ db = tmp_path / "temporal.db"+ _write_db(db)+ _write_marker(db, pinned_server, partitions)++ _install.prepare_database(db)++ assert not any(path.exists() for path in _db_files(db))+ assert _read_marker(db)["partitions"] == ONE_PARTITION++def test_an_unreadable_marker_starts_from_new(tmp_path, monkeypatch):root = tmp_path / "packages"root.mkdir()