bma-executor-sdk 1.0.2__tar.gz → 1.0.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/PKG-INFO +21 -2
  2. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/README.md +20 -1
  3. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/pyproject.toml +1 -1
  4. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/src/bma_executor_sdk/__init__.py +2 -0
  5. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/src/bma_executor_sdk/_rpc.py +4 -0
  6. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/src/bma_executor_sdk/client.py +86 -1
  7. bma_executor_sdk-1.0.5/tests/test_registration_refused.py +170 -0
  8. bma_executor_sdk-1.0.5/tests/test_rpc_unretrieved_future.py +60 -0
  9. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/.gitignore +0 -0
  10. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/examples/agent_minimal.py +0 -0
  11. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/examples/executor_minimal.py +0 -0
  12. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/examples/harness_loopback.py +0 -0
  13. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/src/bma_executor_sdk/_methods.py +0 -0
  14. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/src/bma_executor_sdk/_npipe.py +0 -0
  15. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/src/bma_executor_sdk/agent.py +0 -0
  16. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/src/bma_executor_sdk/generated.py +0 -0
  17. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/src/bma_executor_sdk/harness.py +0 -0
  18. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/src/bma_executor_sdk/methods.py +0 -0
  19. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/src/bma_executor_sdk/py.typed +0 -0
  20. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/src/bma_executor_sdk/tools.py +0 -0
  21. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/src/bma_executor_sdk/transport.py +0 -0
  22. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/executor_helpers.py +0 -0
  23. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/test_base_url.py +0 -0
  24. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/test_close_codes.py +0 -0
  25. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/test_executor_conformance.py +0 -0
  26. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/test_executor_contract.py +0 -0
  27. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/test_executor_interop.py +0 -0
  28. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/test_executor_runtime.py +0 -0
  29. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/test_executor_token_refresh.py +0 -0
  30. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/test_npipe.py +0 -0
  31. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/test_reconnect.py +0 -0
  32. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/test_review.py +0 -0
  33. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/test_typed_tools.py +0 -0
  34. {bma_executor_sdk-1.0.2 → bma_executor_sdk-1.0.5}/tests/typecheck/typed_tools.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bma-executor-sdk
3
- Version: 1.0.2
3
+ Version: 1.0.5
4
4
  Summary: BMA executor protocol (bma.executor.v1.1): executor, harness and agent ends on asyncio with WebSocket, Unix socket and in-process transports.
5
5
  Project-URL: Repository, https://github.com/beeos-ai/bma-executor-sdk
6
6
  License-Expression: Apache-2.0
@@ -60,6 +60,25 @@ asyncio.run(main())
60
60
 
61
61
  Set `base_url` to your BMA deployment: the hosted service is in early access and the default `DEFAULT_BASE_URL` (`https://api.bma.beeos.ai`) does not resolve yet. It is the deployment origin, the same value as `BMA_BASE_URL` in bma-sdk (for example `https://api.staging.bma.beeos.ai`); the client posts the environment key to `{base_url}/v1/executors/token` and drops a trailing `/api/v1`. The SDK does not read `BMA_BASE_URL` itself. A `token_source` carries its own channel URL.
62
62
 
63
+ ### A machine-scoped executor must declare `process` or `agent`
64
+
65
+ With an empty `environment_id` (a machine token) the platform binds the connection as the machine's runtime and **refuses the registration of an executor that advertises neither the `process` nor the `agent` capability**: it answers `executor.register`, then closes with `4002` "runtime registration refused". Shell and files alone are such an executor. Declare `process` and serve `process.*` (or `serve_agent`), with `executor["version"]` as `MAJOR.MINOR.PATCH`:
66
+
67
+ ```python
68
+ client = ExecutorClient(
69
+ base_url=os.environ["BMA_BASE_URL"],
70
+ environment_key=os.environ["BMA_MACHINE_TOKEN"], # the machine token
71
+ environment_id="", # machine scope
72
+ executor={"name": "my-machine", "os": "linux", "arch": "arm64", "version": "1.0.0"},
73
+ capabilities={"process": {"enabled": True}},
74
+ )
75
+ client.on_request(methods.PROCESS_START, handle_process_start) # and process.read / write / interrupt / terminate / list
76
+ await client.start()
77
+ await client.wait_ready(30) # registered and still open one heartbeat later
78
+ ```
79
+
80
+ The SDK treats a refusal as a configuration error: after 3 registrations in a row refused right after `executor.register` (close `4002` "runtime registration refused", or an `executor.register` error `capability_unavailable` / `invalid_params`), `wait_closed()` raises `RegistrationRefusedError`; other `4002` closes (for example "daemon runtime ended") reconnect as before. `state` is Ready as soon as `executor.register` returns, which a refused registration also does; `wait_ready(timeout=None)` returns only after the registration stayed open for one heartbeat interval, and raises the error of a client that ended (`TimeoutError` after `timeout`).
81
+
63
82
  A complete version that runs bash and stops the process on cancellation is [`examples/executor_minimal.py`](examples/executor_minimal.py); set `BMA_HARNESS_URL` (`ws://…` or `unix:///path.sock`) to connect it to a local harness instead of BMA.
64
83
 
65
84
  Behavior matches the Go SDK:
@@ -67,7 +86,7 @@ Behavior matches the Go SDK:
67
86
  - A handler returns a string, content blocks, `ToolResult(content, is_error, artifacts)` or (bash) `BashResult`, rendered like the Go `Core`; `raise ToolError(text)` reports a tool-level error (`is_error: true`), any other exception is `outcome: "failed"`. The harness calls tools as `await session.tools.bash.call({"command": "ls"})`.
68
87
  - `tool.cancel` cancels the handler's task and reports `outcome: "canceled"`; duplicate `tool.call` ids run once.
69
88
  - `tool.result` retries `-32009` / `-32004` / `retryable` errors and hands a lost result to `on_tool_result_lost`.
70
- - Reconnect resumes with `resume.executor_id` / `active_sessions`, until `stop()` by default (backoff 1 s doubling to 60 s, jitter); only close codes 4003 and 4004 stop the client. A positive `max_reconnect_attempts` bounds the attempts. `await client.wait_closed()` returns after `stop()` / `executor.close` and raises `ChannelClosed` (4003/4004), `CredentialRejectedError` (the token endpoint answered 401/403 on reconnect: revoked or invalid credential, not retried) or `ReconnectExhaustedError`; let it end the process so a supervisor can restart it.
89
+ - Reconnect resumes with `resume.executor_id` / `active_sessions`, until `stop()` by default (backoff 1 s doubling to 60 s, jitter); only close codes 4003 and 4004 stop the client, and so does `RegistrationRefusedError` (3 refused registrations in a row). A positive `max_reconnect_attempts` bounds the attempts. `await client.wait_closed()` returns after `stop()` / `executor.close` and raises `ChannelClosed` (4003/4004), `RegistrationRefusedError`, `CredentialRejectedError` (the token endpoint answered 401/403 on reconnect: revoked or invalid credential, not retried) or `ReconnectExhaustedError`; let it end the process so a supervisor can restart it.
71
90
  - Call `session_ready` after setup and `session_ended` after cleanup. `client.on_request(methods.PROCESS_START, handler)` serves `process.*`, `terminal.*`, `skill.install` or `workspace.backup` yourself with the contract's TypedDicts; `await client.call(methods.SESSION_EVENT, params)` / `await client.notify(methods.TOOL_PROGRESS, params)` send typed methods (`bma_executor_sdk.methods`). There is no execution `Core` in Python.
72
91
  - Input missing a required member fails the call before the handler runs; a `tool.call` for a tool without a handler is refused with `-32012` before the ack; `shell` / `files` are enabled while a handler of the group is registered unless set `enabled: False`, and a handler registered after `start()` sends `executor.capabilities.update`. `BashResult` beyond `INLINE_RESULT_BYTES` (or `truncated=True`) is cut to Go Core's preview. The `computer_*` tools get slots once the contract defines their input.
73
92
 
@@ -49,6 +49,25 @@ asyncio.run(main())
49
49
 
50
50
  Set `base_url` to your BMA deployment: the hosted service is in early access and the default `DEFAULT_BASE_URL` (`https://api.bma.beeos.ai`) does not resolve yet. It is the deployment origin, the same value as `BMA_BASE_URL` in bma-sdk (for example `https://api.staging.bma.beeos.ai`); the client posts the environment key to `{base_url}/v1/executors/token` and drops a trailing `/api/v1`. The SDK does not read `BMA_BASE_URL` itself. A `token_source` carries its own channel URL.
51
51
 
52
+ ### A machine-scoped executor must declare `process` or `agent`
53
+
54
+ With an empty `environment_id` (a machine token) the platform binds the connection as the machine's runtime and **refuses the registration of an executor that advertises neither the `process` nor the `agent` capability**: it answers `executor.register`, then closes with `4002` "runtime registration refused". Shell and files alone are such an executor. Declare `process` and serve `process.*` (or `serve_agent`), with `executor["version"]` as `MAJOR.MINOR.PATCH`:
55
+
56
+ ```python
57
+ client = ExecutorClient(
58
+ base_url=os.environ["BMA_BASE_URL"],
59
+ environment_key=os.environ["BMA_MACHINE_TOKEN"], # the machine token
60
+ environment_id="", # machine scope
61
+ executor={"name": "my-machine", "os": "linux", "arch": "arm64", "version": "1.0.0"},
62
+ capabilities={"process": {"enabled": True}},
63
+ )
64
+ client.on_request(methods.PROCESS_START, handle_process_start) # and process.read / write / interrupt / terminate / list
65
+ await client.start()
66
+ await client.wait_ready(30) # registered and still open one heartbeat later
67
+ ```
68
+
69
+ The SDK treats a refusal as a configuration error: after 3 registrations in a row refused right after `executor.register` (close `4002` "runtime registration refused", or an `executor.register` error `capability_unavailable` / `invalid_params`), `wait_closed()` raises `RegistrationRefusedError`; other `4002` closes (for example "daemon runtime ended") reconnect as before. `state` is Ready as soon as `executor.register` returns, which a refused registration also does; `wait_ready(timeout=None)` returns only after the registration stayed open for one heartbeat interval, and raises the error of a client that ended (`TimeoutError` after `timeout`).
70
+
52
71
  A complete version that runs bash and stops the process on cancellation is [`examples/executor_minimal.py`](examples/executor_minimal.py); set `BMA_HARNESS_URL` (`ws://…` or `unix:///path.sock`) to connect it to a local harness instead of BMA.
53
72
 
54
73
  Behavior matches the Go SDK:
@@ -56,7 +75,7 @@ Behavior matches the Go SDK:
56
75
  - A handler returns a string, content blocks, `ToolResult(content, is_error, artifacts)` or (bash) `BashResult`, rendered like the Go `Core`; `raise ToolError(text)` reports a tool-level error (`is_error: true`), any other exception is `outcome: "failed"`. The harness calls tools as `await session.tools.bash.call({"command": "ls"})`.
57
76
  - `tool.cancel` cancels the handler's task and reports `outcome: "canceled"`; duplicate `tool.call` ids run once.
58
77
  - `tool.result` retries `-32009` / `-32004` / `retryable` errors and hands a lost result to `on_tool_result_lost`.
59
- - Reconnect resumes with `resume.executor_id` / `active_sessions`, until `stop()` by default (backoff 1 s doubling to 60 s, jitter); only close codes 4003 and 4004 stop the client. A positive `max_reconnect_attempts` bounds the attempts. `await client.wait_closed()` returns after `stop()` / `executor.close` and raises `ChannelClosed` (4003/4004), `CredentialRejectedError` (the token endpoint answered 401/403 on reconnect: revoked or invalid credential, not retried) or `ReconnectExhaustedError`; let it end the process so a supervisor can restart it.
78
+ - Reconnect resumes with `resume.executor_id` / `active_sessions`, until `stop()` by default (backoff 1 s doubling to 60 s, jitter); only close codes 4003 and 4004 stop the client, and so does `RegistrationRefusedError` (3 refused registrations in a row). A positive `max_reconnect_attempts` bounds the attempts. `await client.wait_closed()` returns after `stop()` / `executor.close` and raises `ChannelClosed` (4003/4004), `RegistrationRefusedError`, `CredentialRejectedError` (the token endpoint answered 401/403 on reconnect: revoked or invalid credential, not retried) or `ReconnectExhaustedError`; let it end the process so a supervisor can restart it.
60
79
  - Call `session_ready` after setup and `session_ended` after cleanup. `client.on_request(methods.PROCESS_START, handler)` serves `process.*`, `terminal.*`, `skill.install` or `workspace.backup` yourself with the contract's TypedDicts; `await client.call(methods.SESSION_EVENT, params)` / `await client.notify(methods.TOOL_PROGRESS, params)` send typed methods (`bma_executor_sdk.methods`). There is no execution `Core` in Python.
61
80
  - Input missing a required member fails the call before the handler runs; a `tool.call` for a tool without a handler is refused with `-32012` before the ack; `shell` / `files` are enabled while a handler of the group is registered unless set `enabled: False`, and a handler registered after `start()` sends `executor.capabilities.update`. `BashResult` beyond `INLINE_RESULT_BYTES` (or `truncated=True`) is cut to Go Core's preview. The `computer_*` tools get slots once the contract defines their input.
62
81
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "bma-executor-sdk"
3
- version = "1.0.2"
3
+ version = "1.0.5"
4
4
  description = "BMA executor protocol (bma.executor.v1.1): executor, harness and agent ends on asyncio with WebSocket, Unix socket and in-process transports."
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -19,6 +19,7 @@ from .client import (
19
19
  LogEvent,
20
20
  MCPChannel,
21
21
  ReconnectExhaustedError,
22
+ RegistrationRefusedError,
22
23
  static_token,
23
24
  )
24
25
  from .generated import (
@@ -102,6 +103,7 @@ __all__ = [
102
103
  "NotConnectedError",
103
104
  "Principal",
104
105
  "ReconnectExhaustedError",
106
+ "RegistrationRefusedError",
105
107
  "RPCError",
106
108
  "ReadInput",
107
109
  "Session",
@@ -99,6 +99,10 @@ class Peer:
99
99
  raise TimeoutError(f"{method}: no response within {timeout}s") from error
100
100
  finally:
101
101
  self._pending.pop(request_id, None)
102
+ if future.done() and not future.cancelled():
103
+ # The channel can fail the call while it is still being written; that error
104
+ # surfaces from the write, so retrieve the Future's own (asyncio would log it).
105
+ future.exception()
102
106
 
103
107
  async def notify(self, method: str, params: Any) -> None:
104
108
  if self.closed is not None:
@@ -76,6 +76,8 @@ PROTOCOL_V11 = ProtocolVersion.BmaExecutorV11.value
76
76
  _MAX_TRACKED_TOOL_RESULTS = 8192
77
77
  _MAX_TOOL_RESULT_RETRY_DELAY = 10.0
78
78
  _MAX_RECONNECT_DELAY = 60.0
79
+ # Registrations the platform may refuse in a row before the client gives up.
80
+ _MAX_REFUSED_REGISTRATIONS = 3
79
81
  # Fraction of a token's lifetime after which executor.token.refresh is sent.
80
82
  _TOKEN_REFRESH_AT = 0.7
81
83
 
@@ -183,6 +185,11 @@ class ExecutorClient:
183
185
  self._heartbeat_interval = heartbeat_interval
184
186
  self._sessions: set[str] = set()
185
187
  self._reconnect_attempts = 0
188
+ # Registrations refused in a row; the peer that stayed registered for
189
+ # one heartbeat interval; set (then replaced) whenever one does.
190
+ self._refused_streak = 0
191
+ self._stable_peer: Peer | None = None
192
+ self._stable = asyncio.Event()
186
193
  self._completed_tool_results: dict[str, None] = {}
187
194
  self._seen_tool_calls: dict[str, None] = {}
188
195
  self._running_tool_calls: dict[str, _RunningToolCall] = {}
@@ -241,11 +248,41 @@ class ExecutorClient:
241
248
  if self._tasks:
242
249
  await asyncio.gather(*self._tasks, return_exceptions=True)
243
250
 
251
+ async def wait_ready(self, timeout: float | None = None) -> None:
252
+ """Wait until the executor is registered and the registration stayed
253
+ open for one heartbeat interval. ``state`` is Ready as soon as
254
+ executor.register returns, but a machine-scoped executor that declared
255
+ neither the process nor the agent capability is closed with 4002 right
256
+ after that, so only wait_ready() separates a usable executor from a
257
+ registration about to be refused. Raises the error of a client that
258
+ ended (see wait_closed), ClientStoppedError after stop() and
259
+ TimeoutError after ``timeout`` seconds."""
260
+
261
+ async def wait() -> None:
262
+ while True:
263
+ if self._stopped:
264
+ raise self._close_error or ClientStoppedError()
265
+ if self._peer is not None and self._stable_peer is self._peer:
266
+ return
267
+ stable = asyncio.ensure_future(self._stable.wait())
268
+ closed = asyncio.ensure_future(self._closed.wait())
269
+ try:
270
+ await asyncio.wait({stable, closed}, return_when=asyncio.FIRST_COMPLETED)
271
+ finally:
272
+ stable.cancel()
273
+ closed.cancel()
274
+
275
+ try:
276
+ await asyncio.wait_for(wait(), timeout)
277
+ except asyncio.TimeoutError as error: # not the builtin TimeoutError before Python 3.11
278
+ raise TimeoutError("wait_ready timed out") from error
279
+
244
280
  async def wait_closed(self) -> None:
245
281
  """Wait until the client stops for good (Go: ``Done`` and ``Err``).
246
282
  Returns after stop() or executor.close; raises ChannelClosed for a
247
283
  terminal close code (4003, 4004), CredentialRejectedError when the
248
- token endpoint rejects the credential on reconnect, and
284
+ token endpoint rejects the credential on reconnect,
285
+ RegistrationRefusedError after 3 refused registrations in a row, and
249
286
  ReconnectExhaustedError after a positive max_reconnect_attempts."""
250
287
  await self._closed.wait()
251
288
  if self._close_error is not None:
@@ -475,6 +512,7 @@ class ExecutorClient:
475
512
  self._executor_id = result["executor_id"]
476
513
  self._state = ConnectionState.Ready
477
514
  self._reconnect_attempts = 0
515
+ self._spawn(self._mark_stable_later(peer, self._heartbeat_interval))
478
516
  registered, self._registered = self._registered, asyncio.Event()
479
517
  registered.set()
480
518
  self._log("info", f"executor registered as {result['executor_id']}")
@@ -528,6 +566,30 @@ class ExecutorClient:
528
566
  resume["last_connection_id"] = self._connection_id
529
567
  return resume
530
568
 
569
+ async def _mark_stable_later(self, peer: Peer, delay: float) -> None:
570
+ """peer stayed registered for one heartbeat interval: the platform did not refuse its runtime."""
571
+ await asyncio.sleep(delay)
572
+ if self._stopped or self._peer is not peer:
573
+ return
574
+ self._stable_peer = peer
575
+ self._refused_streak = 0
576
+ stable, self._stable = self._stable, asyncio.Event()
577
+ stable.set()
578
+
579
+ def _count_refused_registration(self, cause: BaseException) -> bool:
580
+ """Record one refused registration; end the client at the limit."""
581
+ self._refused_streak += 1
582
+ if self._refused_streak < _MAX_REFUSED_REGISTRATIONS:
583
+ return False
584
+ error = RegistrationRefusedError(
585
+ f"executor registration refused {self._refused_streak} times in a row "
586
+ "(a machine-scoped executor must declare the process or agent capability)"
587
+ )
588
+ error.__cause__ = cause
589
+ self._log("error", "executor registration refused; not reconnecting", cause)
590
+ self._end(error)
591
+ return True
592
+
531
593
  async def _read(self, peer: Peer) -> None:
532
594
  closed = await peer.run()
533
595
  await self._disconnected(peer, closed)
@@ -535,6 +597,7 @@ class ExecutorClient:
535
597
  async def _disconnected(self, peer: Peer, closed: ChannelClosed) -> None:
536
598
  if self._peer is not peer:
537
599
  return
600
+ was_stable = self._stable_peer is peer
538
601
  self._peer = None
539
602
  if self._stopped:
540
603
  return
@@ -542,6 +605,11 @@ class ExecutorClient:
542
605
  self._log("error", f"executor channel closed with terminal code {closed.code}: {closed.reason}")
543
606
  self._end(closed)
544
607
  return
608
+ if not was_stable and _is_registration_refusal(closed):
609
+ if self._count_refused_registration(closed):
610
+ return
611
+ else:
612
+ self._refused_streak = 0
545
613
  self._state = ConnectionState.Disconnected
546
614
  self._spawn(self._reconnect_loop())
547
615
 
@@ -575,6 +643,8 @@ class ExecutorClient:
575
643
  self._end(error)
576
644
  return
577
645
  except Exception as error:
646
+ if _is_registration_refusal(error) and self._count_refused_registration(error):
647
+ return
578
648
  cause = error
579
649
  self._state = ConnectionState.Disconnected
580
650
  self._log("warn", "executor reconnect failed", error)
@@ -760,6 +830,21 @@ class CredentialRejectedError(ExecutorTokenError):
760
830
  self.status_code = status_code
761
831
 
762
832
 
833
+ class RegistrationRefusedError(ExecutorError):
834
+ """The platform refused the executor's registration 3 times in a row: the
835
+ close 4002 "runtime registration refused" right after executor.register,
836
+ or an executor.register error for the executor's capabilities. A
837
+ configuration error (a machine-scoped executor must declare the process
838
+ or agent capability) that reconnecting cannot fix; ``__cause__`` is the
839
+ last refusal."""
840
+
841
+
842
+ def _is_registration_refusal(error: BaseException) -> bool:
843
+ if isinstance(error, RPCError):
844
+ return error.code in (JsonRpcErrorCode.CapabilityUnavailable, JsonRpcErrorCode.InvalidParams)
845
+ return isinstance(error, ChannelClosed) and error.code == 4002 and "registration refused" in error.reason.lower()
846
+
847
+
763
848
  class ReconnectExhaustedError(ExecutorError):
764
849
  """A positive max_reconnect_attempts failed in a row; ``__cause__`` is the
765
850
  last failure."""
@@ -0,0 +1,170 @@
1
+ """A machine-scoped executor that declares neither the process nor the agent
2
+ capability is closed with 4002 "runtime registration refused" right after
3
+ executor.register succeeds. Reconnecting cannot fix it: after 3 such refusals
4
+ in a row the client ends (wait_closed() raises RegistrationRefusedError), and
5
+ wait_ready() returns only for a registration that stayed open for one
6
+ heartbeat interval (Go registration_refused_test.go)."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import json
12
+ import time
13
+ from collections.abc import Awaitable, Callable, Sequence
14
+ from typing import Any
15
+
16
+ import httpx
17
+ import pytest
18
+
19
+ import bma_executor_sdk as bx
20
+ from bma_executor_sdk.transport import Connection, pipe
21
+
22
+ EXECUTOR = {"name": "py-test", "os": "linux", "arch": "arm64", "version": "0.1.0"}
23
+ REFUSED = "runtime registration refused"
24
+
25
+
26
+ class FakeHarness:
27
+ """Answers executor.register on every dialed channel, then runs after(n, harness_end)."""
28
+
29
+ def __init__(
30
+ self,
31
+ after: Callable[[int, Connection], Awaitable[None]] | None = None,
32
+ *,
33
+ register_error: int = 0,
34
+ heartbeat_ms: int = 60000,
35
+ ) -> None:
36
+ self.registrations = 0
37
+ self._after = after
38
+ self._register_error = register_error
39
+ self._heartbeat_ms = heartbeat_ms
40
+ self._tasks: set[asyncio.Task[None]] = set()
41
+
42
+ async def dial(self, url: str, token: str, subprotocols: Sequence[str]) -> Connection:
43
+ executor_end, harness_end = pipe(bx.PROTOCOL_V11)
44
+ task = asyncio.ensure_future(self._serve(harness_end))
45
+ self._tasks.add(task)
46
+ task.add_done_callback(self._tasks.discard)
47
+ return executor_end
48
+
49
+ async def _serve(self, conn: Connection) -> None:
50
+ try:
51
+ while True:
52
+ frame = json.loads(await conn.recv())
53
+ if frame.get("method") != "executor.register":
54
+ continue
55
+ self.registrations += 1
56
+ n = self.registrations
57
+ if self._register_error and n > 1:
58
+ reply: dict[str, Any] = {"jsonrpc": "2.0", "id": frame["id"], "error": {"code": self._register_error, "message": "capability not available"}}
59
+ await conn.send(json.dumps(reply))
60
+ continue
61
+ result = {
62
+ "protocol": bx.PROTOCOL_V11, "executor_id": "exec_test", "connection_id": f"conn_{n}",
63
+ "server_time": "2026-11-07T00:00:00Z", "heartbeat_interval_ms": self._heartbeat_ms,
64
+ "lease_ttl_ms": 60000, "max_control_frame_bytes": 65536, "max_mcp_frame_bytes": 1 << 20,
65
+ }
66
+ await conn.send(json.dumps({"jsonrpc": "2.0", "id": frame["id"], "result": result}))
67
+ if self._after is not None:
68
+ await self._after(n, conn)
69
+ except bx.ChannelClosed:
70
+ return
71
+
72
+ def cancel(self) -> None:
73
+ for task in list(self._tasks):
74
+ task.cancel()
75
+
76
+
77
+ def token_endpoint(request: httpx.Request) -> httpx.Response:
78
+ return httpx.Response(200, json={"executor_id": "", "token": "jwt", "expires_in": 300, "ws_url": "inprocess://harness"})
79
+
80
+
81
+ async def start_client(harness: FakeHarness) -> bx.ExecutorClient:
82
+ client = bx.ExecutorClient(
83
+ environment_id="", executor=EXECUTOR, environment_key="env_key", base_url="http://bma.test",
84
+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(token_endpoint)), dialer=harness.dial,
85
+ request_timeout=2.0, reconnect_base_delay=0.001, reconnect_max_delay=0.002,
86
+ )
87
+ await client.start()
88
+ return client
89
+
90
+
91
+ def close_after(delay: float, code: int, reason: str) -> Callable[[int, Connection], Awaitable[None]]:
92
+ async def after(n: int, conn: Connection) -> None:
93
+ await asyncio.sleep(delay)
94
+ await conn.close(code, reason)
95
+
96
+ return after
97
+
98
+
99
+ async def until(predicate: Callable[[], bool], timeout: float = 5.0) -> None:
100
+ deadline = time.monotonic() + timeout
101
+ while not predicate():
102
+ assert time.monotonic() < deadline, "timed out"
103
+ await asyncio.sleep(0.01)
104
+
105
+
106
+ async def test_three_refusals_in_a_row_end_the_client() -> None:
107
+ harness = FakeHarness(close_after(0.005, 4002, REFUSED))
108
+ client = await start_client(harness)
109
+ with pytest.raises(bx.RegistrationRefusedError) as raised:
110
+ await asyncio.wait_for(client.wait_closed(), 5)
111
+ assert isinstance(raised.value.__cause__, bx.ChannelClosed) and raised.value.__cause__.code == 4002
112
+ assert harness.registrations == 3
113
+ assert client.state == bx.generated.ConnectionState.Closed
114
+ harness.cancel()
115
+
116
+
117
+ async def test_runtime_ended_4002_is_not_a_configuration_error() -> None:
118
+ harness = FakeHarness(close_after(0.005, 4002, "daemon runtime ended"))
119
+ client = await start_client(harness)
120
+ await until(lambda: harness.registrations >= 8)
121
+ assert client.state != bx.generated.ConnectionState.Closed
122
+ await client.stop()
123
+ harness.cancel()
124
+
125
+
126
+ async def test_a_refusal_of_a_stable_connection_is_not_counted() -> None:
127
+ harness = FakeHarness(close_after(0.12, 4002, REFUSED), heartbeat_ms=20)
128
+ client = await start_client(harness)
129
+ await until(lambda: harness.registrations >= 6, 8)
130
+ assert client.state != bx.generated.ConnectionState.Closed
131
+ await client.stop()
132
+ harness.cancel()
133
+
134
+
135
+ @pytest.mark.parametrize("code", [-32012, -32602])
136
+ async def test_register_error_counts_as_a_refusal(code: int) -> None:
137
+ harness = FakeHarness(close_after(0.005, 1012, "node replaced"), register_error=code)
138
+ client = await start_client(harness)
139
+ with pytest.raises(bx.RegistrationRefusedError) as raised:
140
+ await asyncio.wait_for(client.wait_closed(), 5)
141
+ assert isinstance(raised.value.__cause__, bx.RPCError) and raised.value.__cause__.code == code
142
+ harness.cancel()
143
+
144
+
145
+ async def test_wait_ready_needs_one_heartbeat_interval() -> None:
146
+ harness = FakeHarness(heartbeat_ms=300)
147
+ started = time.monotonic()
148
+ client = await start_client(harness)
149
+ await client.wait_ready(5)
150
+ assert time.monotonic() - started >= 0.25
151
+ assert client.state == bx.generated.ConnectionState.Ready
152
+ await client.stop()
153
+ harness.cancel()
154
+
155
+
156
+ async def test_wait_ready_raises_the_configuration_error_for_refusals() -> None:
157
+ harness = FakeHarness(close_after(0.005, 4002, REFUSED))
158
+ client = await start_client(harness)
159
+ with pytest.raises(bx.RegistrationRefusedError):
160
+ await client.wait_ready(5)
161
+ harness.cancel()
162
+
163
+
164
+ async def test_wait_ready_times_out_while_the_registration_is_not_stable() -> None:
165
+ harness = FakeHarness()
166
+ client = await start_client(harness)
167
+ with pytest.raises(TimeoutError):
168
+ await client.wait_ready(0.05)
169
+ await client.stop()
170
+ harness.cancel()
@@ -0,0 +1,60 @@
1
+ """A channel that closes (4002 runtime ended) while a call is still being
2
+ written must not leave a failed Future nobody retrieves: asyncio logs
3
+ "Future exception was never retrieved" when such a Future is collected."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import gc
9
+ from typing import Any
10
+
11
+ import pytest
12
+
13
+ from bma_executor_sdk._rpc import NotConnectedError, Peer
14
+ from bma_executor_sdk.transport import CLOSE_FORBIDDEN, ChannelClosed
15
+
16
+
17
+ class ClosingConnection:
18
+ """send blocks until the channel is closed, then fails as a closed channel does."""
19
+
20
+ subprotocol = None
21
+
22
+ def __init__(self) -> None:
23
+ self.closed = asyncio.Event()
24
+
25
+ async def send(self, message: str) -> None:
26
+ await self.closed.wait()
27
+ raise ChannelClosed(CLOSE_FORBIDDEN, "runtime ended")
28
+
29
+ async def recv(self) -> str:
30
+ await self.closed.wait()
31
+ raise ChannelClosed(CLOSE_FORBIDDEN, "runtime ended")
32
+
33
+ async def close(self, code: int = 1000, reason: str = "") -> None:
34
+ self.closed.set()
35
+
36
+
37
+ async def test_close_during_send_leaves_no_unretrieved_future() -> None:
38
+ loop = asyncio.get_running_loop()
39
+ reported: list[dict[str, Any]] = []
40
+ loop.set_exception_handler(lambda _loop, context: reported.append(context))
41
+
42
+ conn = ClosingConnection()
43
+
44
+ async def no_request(*_: Any) -> Any:
45
+ return None
46
+
47
+ peer = Peer(conn, id_prefix="t", on_request=no_request, on_notification=lambda *_: None, on_log=lambda *_: None)
48
+ reader = asyncio.create_task(peer.run())
49
+ call = asyncio.create_task(peer.call("tool.call", {}, 5.0))
50
+ await asyncio.sleep(0) # the call is registered and blocked in send
51
+ conn.closed.set()
52
+ with pytest.raises(NotConnectedError):
53
+ await call
54
+ await reader
55
+ del call, reader, peer
56
+ for _ in range(3):
57
+ gc.collect()
58
+ await asyncio.sleep(0)
59
+
60
+ assert [c.get("message") for c in reported] == []