holon-sh 0.0.1.dev15__tar.gz → 0.0.1.dev16__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 (27) hide show
  1. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/PKG-INFO +1 -1
  2. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/ext/events/_server.py +18 -26
  3. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/pyproject.toml +1 -1
  4. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/tests/test_events.py +60 -54
  5. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/.gitignore +0 -0
  6. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/LICENSE +0 -0
  7. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/README.md +0 -0
  8. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/client.py +0 -0
  9. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/context.py +0 -0
  10. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/ext/__init__.py +0 -0
  11. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/ext/events/__init__.py +0 -0
  12. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/ext/events/_client.py +0 -0
  13. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/ext/events/_wire.py +0 -0
  14. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/ext/files/__init__.py +0 -0
  15. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/ext/files/_client.py +0 -0
  16. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/ext/files/_server.py +0 -0
  17. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/ext/files/_wire.py +0 -0
  18. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/py.typed +0 -0
  19. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/holon/serve.py +0 -0
  20. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/scripts/verify_distribution.py +0 -0
  21. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/tests/fixtures/caller/holon/apps/__init__.py +0 -0
  22. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/tests/test_context.py +0 -0
  23. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/tests/test_elicit.py +0 -0
  24. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/tests/test_files.py +0 -0
  25. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/tests/test_package.py +0 -0
  26. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/tests/test_runtime.py +0 -0
  27. {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev16}/tests/test_serve.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: holon-sh
3
- Version: 0.0.1.dev15
3
+ Version: 0.0.1.dev16
4
4
  Summary: Typed MCP clients and the caller of an MCP request
5
5
  Project-URL: Repository, https://github.com/holon-sh/sdk-py
6
6
  License-Expression: Apache-2.0
@@ -77,7 +77,10 @@ T = TypeVar("T")
77
77
  Match: TypeAlias = Callable[[RequestContext, Event[D], A], bool]
78
78
  Transform: TypeAlias = Callable[[RequestContext, Event[D], A], object]
79
79
  Authorize: TypeAlias = Callable[[RequestContext, A], bool | Awaitable[bool]]
80
- SubscriptionHook: TypeAlias = Callable[[RequestContext, A, str], None | Awaitable[None]]
80
+ Cleanup: TypeAlias = Callable[[], None | Awaitable[None]]
81
+ SubscriptionHook: TypeAlias = Callable[
82
+ [RequestContext, A, str], Cleanup | None | Awaitable[Cleanup | None]
83
+ ]
81
84
 
82
85
 
83
86
  class _SubscribeParams(RequestParams):
@@ -138,9 +141,7 @@ class _Kept:
138
141
  class _Entry:
139
142
  """A subscription, held by one or more streams or poll leases."""
140
143
 
141
- request: _Request
142
- """The request that began it."""
143
- setup: asyncio.Future[None]
144
+ setup: asyncio.Future[Cleanup | None]
144
145
  holds: set[_Hold] = field(default_factory=set)
145
146
  teardown: asyncio.Future[None] | None = None
146
147
 
@@ -171,7 +172,6 @@ class EventType(Generic[A, D]):
171
172
  _delivery: list[Delivery]
172
173
  _authorize: Authorize[A] | None
173
174
  _on_subscribe: SubscriptionHook[A] | None
174
- _on_unsubscribe: SubscriptionHook[A] | None
175
175
  # Emitted events, oldest first; `_dropped` is the last sequence evicted.
176
176
  _kept: list[_Kept] = field(default_factory=list)
177
177
  _sequence: int = 0
@@ -420,7 +420,6 @@ class Events(Extension):
420
420
  delivery: Sequence[Delivery] = ("poll", "push"),
421
421
  authorize: Authorize[A] | None = None,
422
422
  on_subscribe: SubscriptionHook[A] | None = None,
423
- on_unsubscribe: SubscriptionHook[A] | None = None,
424
423
  ) -> EventType[A, D]:
425
424
  """Declare an event type.
426
425
 
@@ -434,7 +433,7 @@ class Events(Extension):
434
433
  delivery: The delivery modes offered.
435
434
  authorize: ``(context, arguments)``: whether the caller may subscribe, checked again while subscribed.
436
435
  on_subscribe: ``(context, arguments, subscription_id)``: called when a subscription begins.
437
- on_unsubscribe: ``(context, arguments, subscription_id)``: called when it ends.
436
+ May return a zero-argument cleanup function, called when the subscription ends.
438
437
  """
439
438
  if name in self._types:
440
439
  raise ValueError(f"Event {name} is already declared.")
@@ -461,7 +460,6 @@ class Events(Extension):
461
460
  list(delivery),
462
461
  authorize,
463
462
  on_subscribe,
464
- on_unsubscribe,
465
463
  )
466
464
  self._types[name] = declared
467
465
  return declared
@@ -661,16 +659,16 @@ class Events(Extension):
661
659
  entry = subscriptions.get(request.id)
662
660
  if entry is None:
663
661
  setup = asyncio.ensure_future(self._set_up(request))
664
- entry = subscriptions[request.id] = _Entry(request, setup)
662
+ entry = subscriptions[request.id] = _Entry(setup)
665
663
  hold = _Hold(request, entry)
666
664
  entry.holds.add(hold)
667
665
  return hold
668
666
 
669
- async def _set_up(self, request: _Request) -> None:
667
+ async def _set_up(self, request: _Request) -> Cleanup | None:
670
668
  if request.type._on_subscribe is None:
671
- return
669
+ return None
672
670
  async with asyncio.timeout(_SUBSCRIBE_TIMEOUT):
673
- await _settle(
671
+ return await _settle(
674
672
  request.type._on_subscribe(
675
673
  request.context, request.arguments, request.id
676
674
  )
@@ -688,23 +686,17 @@ class Events(Extension):
688
686
  entry.holds.discard(hold)
689
687
  _release(self._held, hold.request.caller, 1)
690
688
  if not entry.holds:
691
- entry.teardown = asyncio.ensure_future(self._tear_down(entry))
689
+ entry.teardown = asyncio.ensure_future(self._tear_down(hold))
692
690
 
693
- # on_unsubscribe follows only a setup that succeeded; a failing hook is logged.
694
- async def _tear_down(self, entry: _Entry) -> None:
695
- request = entry.request
691
+ # Cleanup follows only a setup that succeeded; a failing hook is logged.
692
+ async def _tear_down(self, hold: _Hold) -> None:
693
+ request = hold.request
696
694
  try:
697
- await entry.setup
698
- if request.type._on_unsubscribe is not None:
699
- await _settle(
700
- request.type._on_unsubscribe(
701
- request.context, request.arguments, request.id
702
- )
703
- )
695
+ cleanup = await hold.entry.setup
696
+ if cleanup is not None:
697
+ await _settle(cleanup())
704
698
  except Exception:
705
- logger.exception(
706
- "An event subscription's on_subscribe or on_unsubscribe failed"
707
- )
699
+ logger.exception("An event subscription's setup or cleanup failed")
708
700
  finally:
709
701
  del request.type._subscriptions[request.id]
710
702
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "holon-sh"
7
- version = "0.0.1.dev15"
7
+ version = "0.0.1.dev16"
8
8
  description = "Typed MCP clients and the caller of an MCP request"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -187,25 +187,25 @@ async def test_a_subscription_hears_what_its_arguments_match_as_shaped_across_a_
187
187
  await stop()
188
188
 
189
189
 
190
+ @pytest.mark.parametrize("user", ["ann", None])
190
191
  @asynchronous
191
- async def test_a_signed_in_caller_has_one_subscription_per_arguments_and_a_caller_without_an_identity_its_own():
192
- began, ended = [], []
193
- events, _ = declare(
194
- on_subscribe=lambda context, arguments, id: began.append(id),
195
- on_unsubscribe=lambda context, arguments, id: ended.append(id),
192
+ async def test_targeted_events_follow_shared_identity_but_isolate_anonymous_readers(
193
+ user,
194
+ ):
195
+ subscribed = asyncio.Queue()
196
+ events, changed = declare(
197
+ on_subscribe=lambda context, arguments, id: subscribed.put_nowait(id)
196
198
  )
197
199
  async with served(events) as port:
198
- ann, anonymous = client(port, user="ann"), client(port)
199
- async with (
200
- ann.subscribe("board.changed", {"board": "b1"}),
201
- ann.subscribe("board.changed", {"board": "b1"}),
202
- anonymous.subscribe("board.changed", {"board": "b1"}),
203
- anonymous.subscribe("board.changed", {"board": "b1"}),
204
- ):
205
- assert len(set(began)) == len(began) == 3
206
- await until(lambda: len(ended) == 3)
207
- async with ann.subscribe("board.changed", {"board": "b1"}):
208
- assert began[3] == began[0]
200
+ reader = client(port, user=user)
201
+ async with reader.subscribe("board.changed", {"board": "b1"}) as first:
202
+ subscription_id = await subscribed.get()
203
+ async with reader.subscribe("board.changed", {"board": "b1"}) as second:
204
+ say(changed, "b1", "private", to=subscription_id)
205
+ say(changed, "b1", "public")
206
+ assert await take(first, 2) == ["private", "public"]
207
+ for expected in ["private", "public"] if user else ["public"]:
208
+ assert (await anext(second)).event_id == expected
209
209
 
210
210
 
211
211
  @pytest.mark.parametrize("targeted", [False, True])
@@ -215,9 +215,9 @@ async def test_a_subscription_behind_what_is_kept_is_told_of_the_gap_and_carries
215
215
  monkeypatch, delivery, targeted
216
216
  ):
217
217
  monkeypatch.setattr(_server, "_KEEP_EVENTS", 2)
218
- ids, heard = [], []
218
+ subscribed, heard = asyncio.Queue(), []
219
219
  events, changed = declare(
220
- on_subscribe=lambda context, arguments, id: ids.append(id)
220
+ on_subscribe=lambda context, arguments, id: subscribed.put_nowait(id)
221
221
  )
222
222
  owed = delivery == "push" and targeted
223
223
  async with (
@@ -229,8 +229,9 @@ async def test_a_subscription_behind_what_is_kept_is_told_of_the_gap_and_carries
229
229
  on_gap=lambda: heard.append("gap"),
230
230
  ) as changes,
231
231
  ):
232
+ subscription_id = await subscribed.get()
232
233
  for text in ["a", "b", "c", "d"]:
233
- say(changed, "b1", text, to=ids[0] if targeted else None)
234
+ say(changed, "b1", text, to=subscription_id if targeted else None)
234
235
  heard.extend(await take(changes, 2))
235
236
  assert heard == (["a", "b"] if owed else ["gap", "c", "d"])
236
237
 
@@ -263,9 +264,11 @@ async def test_what_a_subscribe_hook_emits_reaches_its_subscription_first_and_a_
263
264
  @asynchronous
264
265
  async def test_a_subscription_the_app_ends_is_sent_what_was_emitted_to_it_unless_it_lost_access():
265
266
  ids = {}
266
- events, changed = declare(
267
- on_subscribe=lambda context, arguments, id: ids.setdefault(arguments.board, id)
268
- )
267
+
268
+ def on_subscribe(context, arguments, id):
269
+ ids[arguments.board] = id
270
+
271
+ events, changed = declare(on_subscribe=on_subscribe)
269
272
  async with served(events) as port:
270
273
  boards = client(port, user="ann")
271
274
  async with (
@@ -324,25 +327,25 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
324
327
  )
325
328
  async with served(events) as port, httpx2.AsyncClient(timeout=10) as http:
326
329
  discovered = await call(http, port, "server/discover", {})
327
- assert discovered["result"]["capabilities"]["events"] == {"listChanged": False}
328
- [listed, locked] = (await call(http, port, "events/list", {}))["result"][
329
- "events"
330
- ]
331
- assert locked["payloadSchema"] == recursive
332
- assert listed == {
333
- "name": "board.changed",
330
+ assert discovered["result"]["capabilities"]["events"]["listChanged"] is False
331
+ listed = {
332
+ event["name"]: event
333
+ for event in (await call(http, port, "events/list", {}))["result"]["events"]
334
+ }
335
+ assert listed["board.locked"]["payloadSchema"] == recursive
336
+ assert set(listed["board.changed"]["delivery"]) == {"poll", "push"}
337
+ expected = {
334
338
  "description": "A board changed",
335
- "delivery": ["poll", "push"],
336
339
  "inputSchema": Board.model_json_schema(),
337
340
  "payloadSchema": Change.model_json_schema(),
338
341
  }
342
+ assert {key: listed["board.changed"][key] for key in expected} == expected
339
343
  # A poll from null has no events, and a cursor from before its setup's welcome.
340
344
  now = (await call(http, port, "events/poll", changed_on("b1")))["result"]
341
- assert (now["events"], now["truncated"], now["hasMore"], now["nextPollMs"]) == (
345
+ assert (now["events"], now["truncated"], now["hasMore"]) == (
342
346
  [],
343
347
  False,
344
348
  False,
345
- 1000,
346
349
  )
347
350
  for text in ["one", "bad", "two", "three"]:
348
351
  say(changed, "b1", text)
@@ -358,7 +361,6 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
358
361
  "one",
359
362
  True,
360
363
  )
361
- assert set(one) == {"eventId", "name", "timestamp", "data"}
362
364
  rest = await call(
363
365
  http, port, "events/poll", changed_on("b1", page["result"]["cursor"])
364
366
  )
@@ -391,9 +393,11 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
391
393
  frames = (
392
394
  json.loads(frame.data) async for frame in httpx2.EventSource(stream)
393
395
  )
394
- meta = {"_meta": {SUBSCRIPTION_ID_META_KEY: 7}}
395
396
  active = await anext(frames)
396
- assert active["params"] == {"cursor": opened, "truncated": False, **meta}
397
+ assert (active["params"]["cursor"], active["params"]["truncated"]) == (
398
+ opened,
399
+ False,
400
+ )
397
401
  assert (await anext(frames))["params"]["eventId"] == "welcome"
398
402
  say(changed, "b1", "bad")
399
403
  say(changed, "b1", "four")
@@ -403,19 +407,19 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
403
407
  INTERNAL_ERROR,
404
408
  )
405
409
  event = (await anext(frames))["params"]
406
- assert event == {
410
+ expected = {
407
411
  "eventId": "four",
408
412
  "name": "board.changed",
409
- "timestamp": event["timestamp"],
410
413
  "data": {"board": "b1", "text": "four"},
411
414
  "cursor": changed.cursor(),
412
- **meta,
413
415
  }
416
+ assert {key: event[key] for key in expected} == expected
417
+ assert event["_meta"][SUBSCRIPTION_ID_META_KEY] == 7
414
418
  changed.terminate()
415
419
  terminated = await anext(frames)
416
- assert (terminated["method"], terminated["params"]["error"]) == (
420
+ assert (terminated["method"], terminated["params"]["error"]["code"]) == (
417
421
  "notifications/events/terminated",
418
- {"code": -32024, "message": "Forbidden"},
422
+ -32024,
419
423
  )
420
424
  assert "result" in await anext(frames)
421
425
 
@@ -426,16 +430,18 @@ async def test_a_poll_that_gives_up_while_it_is_set_up_holds_its_place_until_its
426
430
  ):
427
431
  monkeypatch.setattr(_server, "_POLL_SUBSCRIPTION_TTL", 0.1)
428
432
  monkeypatch.setattr(_server, "_MAX_SUBSCRIPTIONS", 1)
429
- setting_up, release, ended = asyncio.Event(), asyncio.Event(), []
433
+ setting_up, release, ended = asyncio.Event(), asyncio.Event(), asyncio.Event()
430
434
 
431
435
  async def on_subscribe(context, arguments, id):
432
436
  setting_up.set()
433
437
  await release.wait()
434
438
 
435
- events, _ = declare(
436
- on_subscribe=on_subscribe,
437
- on_unsubscribe=lambda context, arguments, id: ended.append(id),
438
- )
439
+ async def cleanup():
440
+ ended.set()
441
+
442
+ return cleanup
443
+
444
+ events, _ = declare(on_subscribe=on_subscribe)
439
445
  app, left = mounted(events), asyncio.Event()
440
446
 
441
447
  # Tells when the server sees the poll that gives up disconnect.
@@ -458,33 +464,32 @@ async def test_a_poll_that_gives_up_while_it_is_set_up_holds_its_place_until_its
458
464
  await setting_up.wait()
459
465
  async with httpx2.AsyncClient(timeout=10) as http:
460
466
  exhausted = await call(http, port, "events/poll", changed_on("b2"))
461
- assert exhausted["error"]["data"] == {"limit": "subscriptions", "max": 1}
467
+ limit = exhausted["error"]["data"]
468
+ assert (limit["limit"], limit["max"]) == ("subscriptions", 1)
462
469
  giving_up.cancel()
463
470
  await left.wait()
464
471
  release.set()
465
- await until(lambda: ended)
472
+ await ended.wait()
466
473
  assert "result" in await call(http, port, "events/poll", changed_on("b2"))
467
474
  await stop()
468
475
 
469
476
 
470
477
  @asynchronous
471
- async def test_a_subscribe_hook_that_does_not_return_in_time_refuses_and_releases_the_id(
478
+ async def test_a_subscription_can_be_retried_after_setup_times_out(
472
479
  monkeypatch,
473
480
  ):
474
481
  monkeypatch.setattr(_server, "_SUBSCRIBE_TIMEOUT", 0.1)
475
- calls = []
482
+ ready = asyncio.Event()
476
483
 
477
484
  async def on_subscribe(context, arguments, id):
478
- calls.append(id)
479
- if len(calls) == 1:
480
- await asyncio.Event().wait()
485
+ await ready.wait()
481
486
 
482
487
  events, _ = declare(on_subscribe=on_subscribe)
483
488
  async with served(events) as port, httpx2.AsyncClient(timeout=10) as http:
484
489
  refused = await call(http, port, "events/poll", changed_on("b1"))
485
490
  assert refused["error"]["code"] == INTERNAL_ERROR
491
+ ready.set()
486
492
  assert "result" in await call(http, port, "events/poll", changed_on("b1"))
487
- assert calls[0] == calls[1]
488
493
 
489
494
 
490
495
  @asynchronous
@@ -556,5 +561,6 @@ async def test_a_subscription_from_the_cursor_read_with_a_snapshot_hears_every_c
556
561
  ) as changes:
557
562
  assert changes.delivery == "push"
558
563
  tell("once subscribed")
559
- assert state["said"] + await take(changes, 2) == said
564
+ assert state["said"] == ["in the snapshot"]
565
+ assert await take(changes, 2) == ["after the snapshot", "once subscribed"]
560
566
  await stop()
File without changes
File without changes