statewire 0.21.2__tar.gz → 0.22.1__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 (53) hide show
  1. {statewire-0.21.2 → statewire-0.22.1}/PKG-INFO +1 -1
  2. {statewire-0.21.2 → statewire-0.22.1}/pyproject.toml +1 -1
  3. {statewire-0.21.2 → statewire-0.22.1}/src/statewire/api.py +80 -4
  4. {statewire-0.21.2 → statewire-0.22.1}/src/statewire/client.py +5 -4
  5. {statewire-0.21.2 → statewire-0.22.1}/src/statewire/ops.py +1 -0
  6. {statewire-0.21.2 → statewire-0.22.1}/src/statewire/protocol.py +4 -2
  7. {statewire-0.21.2 → statewire-0.22.1}/tests/statewire_helpers.py +2 -2
  8. statewire-0.22.1/tests/test_attach_fence.py +196 -0
  9. {statewire-0.21.2 → statewire-0.22.1}/tests/test_context.py +2 -2
  10. {statewire-0.21.2 → statewire-0.22.1}/tests/test_gap_fill.py +2 -2
  11. {statewire-0.21.2 → statewire-0.22.1}/tests/test_lanes.py +2 -2
  12. {statewire-0.21.2 → statewire-0.22.1}/tests/test_protocol_negotiation.py +46 -6
  13. {statewire-0.21.2 → statewire-0.22.1}/.gitignore +0 -0
  14. {statewire-0.21.2 → statewire-0.22.1}/README.md +0 -0
  15. {statewire-0.21.2 → statewire-0.22.1}/examples/__init__.py +0 -0
  16. {statewire-0.21.2 → statewire-0.22.1}/examples/demo_app.py +0 -0
  17. {statewire-0.21.2 → statewire-0.22.1}/src/statewire/__init__.py +0 -0
  18. {statewire-0.21.2 → statewire-0.22.1}/src/statewire/document.py +0 -0
  19. {statewire-0.21.2 → statewire-0.22.1}/src/statewire/documents.py +0 -0
  20. {statewire-0.21.2 → statewire-0.22.1}/src/statewire/langgraph.py +0 -0
  21. {statewire-0.21.2 → statewire-0.22.1}/src/statewire/limits.py +0 -0
  22. {statewire-0.21.2 → statewire-0.22.1}/src/statewire/metrics.py +0 -0
  23. {statewire-0.21.2 → statewire-0.22.1}/src/statewire/state.py +0 -0
  24. {statewire-0.21.2 → statewire-0.22.1}/src/statewire/testing.py +0 -0
  25. {statewire-0.21.2 → statewire-0.22.1}/tests/client_helpers.py +0 -0
  26. {statewire-0.21.2 → statewire-0.22.1}/tests/storage_probe.py +0 -0
  27. {statewire-0.21.2 → statewire-0.22.1}/tests/test_attach_guardrail.py +0 -0
  28. {statewire-0.21.2 → statewire-0.22.1}/tests/test_attached_hook.py +0 -0
  29. {statewire-0.21.2 → statewire-0.22.1}/tests/test_authorize.py +0 -0
  30. {statewire-0.21.2 → statewire-0.22.1}/tests/test_client.py +0 -0
  31. {statewire-0.21.2 → statewire-0.22.1}/tests/test_client_binding.py +0 -0
  32. {statewire-0.21.2 → statewire-0.22.1}/tests/test_client_ws.py +0 -0
  33. {statewire-0.21.2 → statewire-0.22.1}/tests/test_date_registry.py +0 -0
  34. {statewire-0.21.2 → statewire-0.22.1}/tests/test_departure.py +0 -0
  35. {statewire-0.21.2 → statewire-0.22.1}/tests/test_document.py +0 -0
  36. {statewire-0.21.2 → statewire-0.22.1}/tests/test_durable_admission.py +0 -0
  37. {statewire-0.21.2 → statewire-0.22.1}/tests/test_eviction.py +0 -0
  38. {statewire-0.21.2 → statewire-0.22.1}/tests/test_frames.py +0 -0
  39. {statewire-0.21.2 → statewire-0.22.1}/tests/test_idle.py +0 -0
  40. {statewire-0.21.2 → statewire-0.22.1}/tests/test_langgraph.py +0 -0
  41. {statewire-0.21.2 → statewire-0.22.1}/tests/test_lifespan.py +0 -0
  42. {statewire-0.21.2 → statewire-0.22.1}/tests/test_meta.py +0 -0
  43. {statewire-0.21.2 → statewire-0.22.1}/tests/test_observer.py +0 -0
  44. {statewire-0.21.2 → statewire-0.22.1}/tests/test_ops.py +0 -0
  45. {statewire-0.21.2 → statewire-0.22.1}/tests/test_route_auth.py +0 -0
  46. {statewire-0.21.2 → statewire-0.22.1}/tests/test_start_session.py +0 -0
  47. {statewire-0.21.2 → statewire-0.22.1}/tests/test_state_proxy.py +0 -0
  48. {statewire-0.21.2 → statewire-0.22.1}/tests/test_statewire_hostable.py +0 -0
  49. {statewire-0.21.2 → statewire-0.22.1}/tests/test_storage_bridge.py +0 -0
  50. {statewire-0.21.2 → statewire-0.22.1}/tests/test_stream.py +0 -0
  51. {statewire-0.21.2 → statewire-0.22.1}/tests/test_testing.py +0 -0
  52. {statewire-0.21.2 → statewire-0.22.1}/tests/test_writer_lease.py +0 -0
  53. {statewire-0.21.2 → statewire-0.22.1}/tests/test_ws.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: statewire
3
- Version: 0.21.2
3
+ Version: 0.22.1
4
4
  Summary: Replicate one JSON object over an SSE op stream + a command endpoint
5
5
  Project-URL: Repository, https://github.com/assistant-ui/harness-sdk
6
6
  License-Expression: MIT
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "statewire"
3
- version = "0.21.2"
3
+ version = "0.22.1"
4
4
  description = "Replicate one JSON object over an SSE op stream + a command endpoint"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -170,6 +170,7 @@ from statepatch import (
170
170
 
171
171
  from . import metrics, ops
172
172
  from .protocol import (
173
+ FENCE_VERSION,
173
174
  GAP_FILL_VERSION,
174
175
  VERSION,
175
176
  WIRE_VERSION,
@@ -205,6 +206,7 @@ _HEADER_NAME = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+")
205
206
 
206
207
  CLIENT_ID_HEADER = ops.CLIENT_ID_HEADER
207
208
  LEASE_HEADER = ops.LEASE_HEADER
209
+ ATTACHER_HEADER = ops.ATTACHER_HEADER
208
210
 
209
211
  RESULT_CACHE_TTL = 30.0
210
212
  TRAY_RETIRING_RETRY_MS = 1000
@@ -932,6 +934,12 @@ class _Lease:
932
934
  handle: "StatewireAttach | None" = None
933
935
  expires_at: float | None = None
934
936
  expiry_timer: asyncio.TimerHandle | None = None
937
+ # the client-minted token every attach of one connection carries (2026-11-02)
938
+ attacher: str | None = None
939
+ # a later attach of the same attacher replaced this one: no frame is admitted under it again
940
+ retired: bool = False
941
+ admitting: int = 0
942
+ admitted: asyncio.Event = field(default_factory=asyncio.Event)
935
943
 
936
944
 
937
945
  def _key_of(key: Sequence[str] | None) -> tuple[str, ...] | None:
@@ -1417,6 +1425,14 @@ class Statewire(PinnedAPI):
1417
1425
  f"{cls.__name__}.max_inflight_commands must be a positive int: "
1418
1426
  f"{cls.max_inflight_commands!r}"
1419
1427
  )
1428
+ if (
1429
+ not isinstance(cls.wire_version, VersionRange)
1430
+ or cls.wire_version.version > WIRE_VERSION
1431
+ ):
1432
+ raise ValueError(
1433
+ f"{cls.__name__}.wire_version must be a VersionRange no newer than "
1434
+ f"{WIRE_VERSION}: {cls.wire_version!r}"
1435
+ )
1420
1436
  if cls.admission_record not in ("list", "envelope"):
1421
1437
  raise ValueError(
1422
1438
  f"{cls.__name__}.admission_record must be 'list' or 'envelope': "
@@ -2132,9 +2148,13 @@ class Statewire(PinnedAPI):
2132
2148
  selection: Selection | None = None,
2133
2149
  frame: _Frame | None = None,
2134
2150
  received: float = 0.0,
2151
+ attacher: str | None = None,
2135
2152
  ) -> tuple[asyncio.Queue[Any], bytes, str]:
2136
2153
  """Register one attach and build its hello; ``frame``'s ephemeral
2137
- statements are admitted first so their documents and answers ride it."""
2154
+ statements are admitted first so their documents and answers ride it.
2155
+ ``attacher`` names the connection: this client's earlier attaches of the
2156
+ same attacher are retired, and their admissions finish, before the hello
2157
+ reads a watermark."""
2138
2158
  expires_at = (
2139
2159
  None
2140
2160
  if self.max_lease_lifetime is None
@@ -2148,7 +2168,18 @@ class Statewire(PinnedAPI):
2148
2168
  if reserved_websocket:
2149
2169
  assert self._pending_websockets > 0
2150
2170
  pending_websockets = self._pending_websockets - int(reserved_websocket)
2151
- if len(self._subscribers) + pending_websockets >= self.max_subscribers:
2171
+ known = self._clients.get(client_id)
2172
+ replaced = [
2173
+ entry
2174
+ for entry in (known.leases.values() if known is not None else ())
2175
+ if attacher is not None
2176
+ and entry.attacher == attacher
2177
+ and entry.queue in self._subscribers
2178
+ ]
2179
+ if (
2180
+ len(self._subscribers) - len(replaced) + pending_websockets
2181
+ >= self.max_subscribers
2182
+ ):
2152
2183
  raise HTTPException(
2153
2184
  status_code=503, detail="stream subscriber limit reached"
2154
2185
  )
@@ -2161,7 +2192,10 @@ class Statewire(PinnedAPI):
2161
2192
  if expires_at is not None and time.monotonic() >= expires_at:
2162
2193
  raise _LeaseExpired
2163
2194
  if (
2164
- len(self._subscribers) + self._pending_websockets - int(reserved_websocket)
2195
+ len(self._subscribers)
2196
+ - len(replaced)
2197
+ + self._pending_websockets
2198
+ - int(reserved_websocket)
2165
2199
  >= self.max_subscribers
2166
2200
  ):
2167
2201
  raise HTTPException(
@@ -2194,6 +2228,10 @@ class Statewire(PinnedAPI):
2194
2228
  client.tray = commands_tray
2195
2229
  if client.principal is not _UNBOUND and client.principal != auth_result:
2196
2230
  raise _PrincipalMismatch
2231
+ if attacher is not None:
2232
+ for entry in list(client.leases.values()):
2233
+ if entry.attacher == attacher and entry.queue in self._subscribers:
2234
+ await self._retire_lease(entry)
2197
2235
  q: asyncio.Queue[Any] = asyncio.Queue(maxsize=self.stream_queue_size)
2198
2236
  lease = _Lease(
2199
2237
  secrets.token_urlsafe(16),
@@ -2209,6 +2247,7 @@ class Statewire(PinnedAPI):
2209
2247
  client,
2210
2248
  )
2211
2249
  lease.expires_at = expires_at
2250
+ lease.attacher = attacher
2212
2251
  contexts = self._validated_contexts(frame or _Frame([]), lease)
2213
2252
  self._clients[client_id] = client
2214
2253
  if client.principal is _UNBOUND:
@@ -2475,6 +2514,24 @@ class Statewire(PinnedAPI):
2475
2514
  raise WebSocketException(code=1011, reason="authorization failed") from exc
2476
2515
  return _Attach(resolved_auth, connection, client_id, frame)
2477
2516
 
2517
+ async def _retire_lease(self, lease: _Lease) -> None:
2518
+ lease.retired = True
2519
+ self._remove_subscriber(lease.queue)
2520
+ while not lease.queue.empty():
2521
+ lease.queue.get_nowait()
2522
+ lease.queue.put_nowait(
2523
+ (
2524
+ [
2525
+ ops.encode_envelope(
2526
+ {"fin": {"reason": "reconnect", "code": "replaced"}}
2527
+ )
2528
+ ],
2529
+ True,
2530
+ )
2531
+ )
2532
+ while lease.admitting:
2533
+ await lease.admitted.wait()
2534
+
2478
2535
  def _expire_lease(self, lease: _Lease) -> None:
2479
2536
  self._remove_subscriber(lease.queue)
2480
2537
  while not lease.queue.empty():
@@ -2587,6 +2644,11 @@ class Statewire(PinnedAPI):
2587
2644
  selection=selection,
2588
2645
  frame=attach.frame,
2589
2646
  received=received,
2647
+ attacher=(
2648
+ attach.connection.headers.get(ATTACHER_HEADER)
2649
+ if selection.version >= FENCE_VERSION
2650
+ else None
2651
+ ),
2590
2652
  )
2591
2653
  except (_Violation, _IdentityUnavailable, _PrincipalMismatch, _LeaseExpired):
2592
2654
  raise
@@ -2821,6 +2883,20 @@ class Statewire(PinnedAPI):
2821
2883
 
2822
2884
  async def _admit_frame(
2823
2885
  self, client: _Client, frame: _Frame, received: float, lease: _Lease
2886
+ ) -> tuple[str, int | None]:
2887
+ if lease.retired:
2888
+ raise _LeaseExpired
2889
+ lease.admitting += 1
2890
+ lease.admitted.clear()
2891
+ try:
2892
+ return await self._admit_frame_once(client, frame, received, lease)
2893
+ finally:
2894
+ lease.admitting -= 1
2895
+ if not lease.admitting:
2896
+ lease.admitted.set()
2897
+
2898
+ async def _admit_frame_once(
2899
+ self, client: _Client, frame: _Frame, received: float, lease: _Lease
2824
2900
  ) -> tuple[str, int | None]:
2825
2901
  """One admission law, every lane: absorbed statements answer from the
2826
2902
  record, then the new suffix is admitted whole or the frame is refused
@@ -3517,7 +3593,7 @@ class Statewire(PinnedAPI):
3517
3593
  websocket,
3518
3594
  {
3519
3595
  "reason": "reconnect",
3520
- "code": "evicted",
3596
+ "code": "replaced" if lease.retired else "evicted",
3521
3597
  "message": "attach is gone",
3522
3598
  },
3523
3599
  code=1008,
@@ -20,6 +20,7 @@ from urllib.parse import quote, urlencode
20
20
  import httpx
21
21
 
22
22
  from .protocol import (
23
+ VERSION,
23
24
  VersionRange,
24
25
  Offer,
25
26
  Selection,
@@ -532,12 +533,12 @@ class StatewireHttp:
532
533
  application_protocols: tuple[Offer, ...] | str | None = None,
533
534
  ):
534
535
  self.protocol = protocol
535
- self.wire_version = wire_version or VersionRange()
536
+ self.wire_version = wire_version or VersionRange(VERSION)
536
537
  self.application_protocols = (
537
538
  None
538
539
  if application_protocols == "*"
539
540
  else (
540
- (Offer(protocol, VersionRange()),)
541
+ (Offer(protocol, VersionRange(VERSION)),)
541
542
  if application_protocols is None
542
543
  else application_protocols
543
544
  )
@@ -679,12 +680,12 @@ class StatewireWebsocket:
679
680
  application_protocols: tuple[Offer, ...] | str | None = None,
680
681
  ):
681
682
  self.protocol = protocol
682
- self.wire_version = wire_version or VersionRange()
683
+ self.wire_version = wire_version or VersionRange(VERSION)
683
684
  self.application_protocols = (
684
685
  None
685
686
  if application_protocols == "*"
686
687
  else (
687
- (Offer(protocol, VersionRange()),)
688
+ (Offer(protocol, VersionRange(VERSION)),)
688
689
  if application_protocols is None
689
690
  else application_protocols
690
691
  )
@@ -56,6 +56,7 @@ def remove_op(path: Path) -> Op:
56
56
  WS_SUBPROTOCOL = "statewire.v1"
57
57
  CLIENT_ID_HEADER = "Statewire-Client-Id"
58
58
  LEASE_HEADER = "Statewire-Lease"
59
+ ATTACHER_HEADER = "Statewire-Attacher"
59
60
 
60
61
 
61
62
  def _wire_default(value: Any) -> Any:
@@ -5,9 +5,11 @@ import re
5
5
  from typing import Any, Callable, Mapping
6
6
 
7
7
  VERSION = "2026-09-30"
8
- WIRE_VERSION = "2026-11-01"
8
+ WIRE_VERSION = "2026-11-02"
9
9
  # attach carries a results cursor; a re-sent seq at or below the watermark is a violation
10
10
  GAP_FILL_VERSION = "2026-11-01"
11
+ # an attach names its attacher; a new attach retires the same attacher's earlier ones first
12
+ FENCE_VERSION = "2026-11-02"
11
13
  TOKEN = re.compile(r"[A-Za-z*][A-Za-z0-9!#$%&'*+.^_`|~:/-]*")
12
14
 
13
15
 
@@ -20,7 +22,7 @@ def version(value: Any) -> str:
20
22
 
21
23
  @dataclass(frozen=True)
22
24
  class VersionRange:
23
- version: str = VERSION
25
+ version: str
24
26
  min_version: str | None = None
25
27
 
26
28
  def __post_init__(self) -> None:
@@ -8,9 +8,9 @@ from fastapi import FastAPI
8
8
  from pinned import Lease, PinnedContext, PinnedHost, PinnedWorker, RealDomain
9
9
  from statewire.api import CLIENT_ID_HEADER, LEASE_HEADER
10
10
  from statewire.client import apply_ops as client_apply_ops
11
- from statewire.protocol import headers as protocol_headers, VersionRange, Offer
11
+ from statewire.protocol import VERSION, headers as protocol_headers, VersionRange, Offer
12
12
 
13
- NEGOTIATION = protocol_headers(VersionRange(), (Offer("default", VersionRange()),))
13
+ NEGOTIATION = protocol_headers(VersionRange(VERSION), (Offer("default", VersionRange(VERSION)),))
14
14
 
15
15
  leases: dict[tuple[str, str], str] = {}
16
16
  _AUTO = object()
@@ -0,0 +1,196 @@
1
+ """Contract: under wire 2026-11-02 every attach of one client connection carries
2
+ its `Statewire-Attacher` token, and a new attach first retires the client id's
3
+ earlier attaches of the same attacher: their admissions in progress finish
4
+ before the hello reads a watermark, and nothing is admitted under them again.
5
+ Another attacher (another tab on the same client id) is untouched. Earlier
6
+ wires keep the race: a frame on the replaced attach can land after the hello."""
7
+
8
+ import asyncio
9
+
10
+ import pytest
11
+ from statewire_helpers import attach_of, post_frame, statewire_client
12
+
13
+ import statewire.api as api
14
+ from statewire import Statewire, command
15
+ from statewire.protocol import (
16
+ FENCE_VERSION,
17
+ GAP_FILL_VERSION,
18
+ VERSION,
19
+ Offer,
20
+ VersionRange,
21
+ headers,
22
+ )
23
+
24
+ FENCE = headers(VersionRange(FENCE_VERSION), (Offer("default", VersionRange(VERSION)),))
25
+ GAP_FILL = headers(
26
+ VersionRange(GAP_FILL_VERSION), (Offer("default", VersionRange(VERSION)),)
27
+ )
28
+
29
+
30
+ class Host(Statewire):
31
+ async def lifespan(self):
32
+ self.state = {"count": 0}
33
+ yield
34
+
35
+ async def authorize(self, request):
36
+ return request.headers.get("x-user", "alice")
37
+
38
+ @command
39
+ async def inc(self):
40
+ self.state["count"] += 1
41
+ return self.state["count"]
42
+
43
+
44
+ def statement(seq):
45
+ return {"protocol": "default", "method": "inc", "params": [], "seq": seq}
46
+
47
+
48
+ def tab(negotiation, attacher, **extra):
49
+ return {**negotiation, "Statewire-Attacher": attacher, **extra}
50
+
51
+
52
+ @pytest.fixture
53
+ def held_first_admission(monkeypatch):
54
+ """Holds the admission of seq 1 until `gate` is set; `entered` once it waits."""
55
+ gate, entered = asyncio.Event(), asyncio.Event()
56
+ original = api.Statewire._admit_frame_once
57
+
58
+ async def held(self, client, frame, received, lease):
59
+ if any(s["seq"] == 1 for s in frame.cmd) and not gate.is_set():
60
+ entered.set()
61
+ await gate.wait()
62
+ return await original(self, client, frame, received, lease)
63
+
64
+ monkeypatch.setattr(api.Statewire, "_admit_frame_once", held)
65
+ return gate, entered
66
+
67
+
68
+ async def hello_after_release(app, negotiation, gate, frame=None):
69
+ """The hello of a new attach, with the held admission released mid-attach;
70
+ `waited`: the attach had not answered before the release."""
71
+ attach = attach_of(app, frame or {"headers": {}}, headers=negotiation)
72
+ entering = asyncio.create_task(attach.__aenter__())
73
+ await asyncio.sleep(0.05)
74
+ waited = not entering.done()
75
+ gate.set()
76
+ stream = await entering
77
+ try:
78
+ return waited, await stream.next_event()
79
+ finally:
80
+ await attach.__aexit__(None, None, None)
81
+
82
+
83
+ async def test_a_reattach_retires_the_attacher_s_earlier_attach(held_first_admission):
84
+ gate, entered = held_first_admission
85
+ async with statewire_client(Host) as (app, client):
86
+ async with attach_of(
87
+ app, {"headers": {}}, headers=tab(FENCE, "tab-1")
88
+ ) as first:
89
+ hello = await first.next_event()
90
+ assert hello["syn"]["version"] == FENCE_VERSION
91
+ replaced = first.headers["statewire-lease"]
92
+ posted = asyncio.create_task(
93
+ post_frame(client, {"cmd": [statement(1)]}, lease=replaced)
94
+ )
95
+ await entered.wait()
96
+ waited, hello = await hello_after_release(app, tab(FENCE, "tab-1"), gate)
97
+ assert waited
98
+ assert hello["syn"]["protocols"][0]["seq"] == 1
99
+ assert (await posted).status_code == 200
100
+ late = await post_frame(client, {"cmd": [statement(2)]}, lease=replaced)
101
+ assert late.status_code == 423
102
+ assert (await first.next_event())["fin"] == {
103
+ "reason": "reconnect",
104
+ "code": "replaced",
105
+ }
106
+
107
+
108
+ async def test_a_retry_whose_previous_hello_was_lost_still_waits(held_first_admission):
109
+ gate, entered = held_first_admission
110
+ async with statewire_client(Host) as (app, client):
111
+ async with attach_of(
112
+ app, {"headers": {}}, headers=tab(FENCE, "tab-1")
113
+ ) as first:
114
+ await first.next_event()
115
+ lost = attach_of(app, {"cmd": [statement(1)]}, headers=tab(FENCE, "tab-1"))
116
+ lost_task = asyncio.create_task(lost.__aenter__())
117
+ await entered.wait()
118
+ waited, hello = await hello_after_release(app, tab(FENCE, "tab-1"), gate)
119
+ assert waited
120
+ assert hello["syn"]["protocols"][0]["seq"] == 1
121
+ await (await lost_task).__aexit__(None, None, None)
122
+
123
+
124
+ async def test_another_attacher_on_the_client_id_is_untouched(held_first_admission):
125
+ gate, entered = held_first_admission
126
+ async with statewire_client(Host) as (app, client):
127
+ async with attach_of(
128
+ app, {"headers": {}}, headers=tab(FENCE, "tab-1")
129
+ ) as first:
130
+ await first.next_event()
131
+ posted = asyncio.create_task(
132
+ post_frame(
133
+ client,
134
+ {"cmd": [statement(1)]},
135
+ lease=first.headers["statewire-lease"],
136
+ )
137
+ )
138
+ await entered.wait()
139
+ waited, hello = await hello_after_release(app, tab(FENCE, "tab-2"), gate)
140
+ assert not waited
141
+ assert (await posted).status_code == 200
142
+ second = await post_frame(
143
+ client, {"cmd": [statement(2)]}, lease=first.headers["statewire-lease"]
144
+ )
145
+ assert second.status_code == 200
146
+
147
+
148
+ async def test_without_the_fence_the_hello_can_predate_a_frame(held_first_admission):
149
+ gate, entered = held_first_admission
150
+ async with statewire_client(Host) as (app, client):
151
+ async with attach_of(
152
+ app, {"headers": {}}, headers=tab(GAP_FILL, "tab-1")
153
+ ) as first:
154
+ await first.next_event()
155
+ posted = asyncio.create_task(
156
+ post_frame(
157
+ client,
158
+ {"cmd": [statement(1)]},
159
+ lease=first.headers["statewire-lease"],
160
+ )
161
+ )
162
+ await entered.wait()
163
+ waited, hello = await hello_after_release(app, tab(GAP_FILL, "tab-1"), gate)
164
+ assert not waited
165
+ assert hello["syn"]["protocols"][0]["seq"] == 0
166
+ assert (await posted).status_code == 200
167
+
168
+
169
+ async def test_another_principal_naming_the_attacher_retires_nothing():
170
+ async with statewire_client(Host) as (app, client):
171
+ async with attach_of(
172
+ app, {"headers": {}}, headers=tab(FENCE, "tab-1")
173
+ ) as first:
174
+ await first.next_event()
175
+ async with attach_of(
176
+ app, {"headers": {}}, headers=tab(FENCE, "tab-1", **{"x-user": "bob"})
177
+ ) as intruder:
178
+ assert intruder.status == 403
179
+ ok = await post_frame(
180
+ client, {"cmd": [statement(1)]}, lease=first.headers["statewire-lease"]
181
+ )
182
+ assert ok.status_code == 200
183
+
184
+
185
+ async def test_a_replacement_fits_under_the_subscriber_limit():
186
+ class OneAttach(Host):
187
+ max_subscribers = 1
188
+
189
+ async with statewire_client(OneAttach) as (app, client):
190
+ async with attach_of(app, {"headers": {}}, headers=tab(FENCE, "tab-1")) as first:
191
+ await first.next_event()
192
+ async with attach_of(
193
+ app, {"headers": {}}, headers=tab(FENCE, "tab-1")
194
+ ) as second:
195
+ assert second.status == 200
196
+ assert "syn" in await second.next_event()
@@ -236,9 +236,9 @@ async def test_preserved_socket_hello_reseeds_context_without_command_work():
236
236
 
237
237
  class Transport:
238
238
  def __init__(self):
239
- from statewire.protocol import Offer, VersionRange
239
+ from statewire.protocol import VERSION, Offer, VersionRange
240
240
 
241
- self._negotiation = (VersionRange(), (Offer("default", VersionRange()),))
241
+ self._negotiation = (VersionRange(VERSION), (Offer("default", VersionRange(VERSION)),))
242
242
  self.incoming = asyncio.Queue()
243
243
  self.frames = []
244
244
  self.attached = None
@@ -15,9 +15,9 @@ from statewire_helpers import (
15
15
 
16
16
  import statewire.api as api
17
17
  from statewire import Statewire, command
18
- from statewire.protocol import WIRE_VERSION, Offer, VersionRange, headers
18
+ from statewire.protocol import VERSION, WIRE_VERSION, Offer, VersionRange, headers
19
19
 
20
- GAP_FILL = headers(VersionRange(WIRE_VERSION), (Offer("default", VersionRange()),))
20
+ GAP_FILL = headers(VersionRange(WIRE_VERSION), (Offer("default", VersionRange(VERSION)),))
21
21
 
22
22
 
23
23
  def make_host():
@@ -23,7 +23,7 @@ from statewire import (
23
23
  )
24
24
  from statewire.client import StatewireClient, Timing
25
25
  from statewire.limits import MAX_EPHEMERAL_DOCUMENT_BYTES
26
- from statewire.protocol import Offer, Protocol, VersionRange, validate_selection
26
+ from statewire.protocol import VERSION, Offer, Protocol, VersionRange, validate_selection
27
27
  from statewire.testing import command_context
28
28
 
29
29
  INTEREST = "default/interest"
@@ -414,7 +414,7 @@ async def test_client_selects_the_child_lane_and_resets_it_on_reattach(sse_clien
414
414
 
415
415
 
416
416
  def test_client_accepts_only_offered_parents_and_their_children():
417
- wire = VersionRange()
417
+ wire = VersionRange(VERSION)
418
418
  offers = (Offer("default", wire),)
419
419
  syn = {
420
420
  "version": "2026-09-30",
@@ -1,6 +1,9 @@
1
1
  import pytest
2
2
 
3
+ from statewire import Statewire
3
4
  from statewire.protocol import (
5
+ VERSION,
6
+ WIRE_VERSION,
4
7
  Adapter,
5
8
  NegotiationError,
6
9
  Offer,
@@ -47,13 +50,41 @@ def test_required_optional_and_wildcard():
47
50
  ],
48
51
  )
49
52
  def test_invalid_negotiation(field, value):
50
- request = headers(VersionRange(), (Offer("harness-sdk", VersionRange()),))
53
+ request = headers(
54
+ VersionRange(VERSION), (Offer("harness-sdk", VersionRange(VERSION)),)
55
+ )
51
56
  request[field] = value
52
57
  with pytest.raises(NegotiationError) as error:
53
- negotiate(request, VersionRange(), (Protocol("harness-sdk"),))
58
+ negotiate(request, VersionRange(VERSION), (Protocol("harness-sdk"),))
54
59
  assert error.value.status == 400
55
60
 
56
61
 
62
+ def test_a_wire_range_names_its_newest_version():
63
+ with pytest.raises(TypeError):
64
+ VersionRange(min_version="2026-09-13")
65
+
66
+
67
+ def test_a_host_floor_serves_clients_that_offer_only_the_current_wire():
68
+ class Host(Statewire):
69
+ wire_version = Statewire.VersionRange(WIRE_VERSION, "2026-09-13")
70
+
71
+ current = headers(VersionRange(WIRE_VERSION), None)
72
+ assert negotiate(current, Host.wire_version, (Protocol("default"),)).version == (
73
+ WIRE_VERSION
74
+ )
75
+ older = headers(VersionRange(VERSION), None)
76
+ assert (
77
+ negotiate(older, Host.wire_version, (Protocol("default"),)).version == VERSION
78
+ )
79
+
80
+
81
+ def test_a_host_cannot_serve_a_wire_newer_than_the_library():
82
+ with pytest.raises(ValueError, match="wire_version"):
83
+
84
+ class Host(Statewire):
85
+ wire_version = Statewire.VersionRange("2099-01-01", VERSION)
86
+
87
+
57
88
  def test_dependency_can_constrain_selected_version():
58
89
  broad = VersionRange("2026-09-30", "2026-08-01")
59
90
  protocols = (
@@ -61,7 +92,7 @@ def test_dependency_can_constrain_selected_version():
61
92
  Protocol("extra", requires={"base": VersionRange("2026-09-01", "2026-08-01")}),
62
93
  )
63
94
  selected = negotiate(
64
- headers(broad, (Offer("base", broad), Offer("extra", VersionRange()))),
95
+ headers(broad, (Offer("base", broad), Offer("extra", VersionRange(VERSION)))),
65
96
  broad,
66
97
  protocols,
67
98
  )
@@ -241,7 +272,7 @@ async def test_http_and_websocket_negotiate_before_prepare_or_initial_commands()
241
272
  ctx.attach.include("extra", [".", "messages", "m1"])
242
273
  return {"count": self.state["count"]}
243
274
 
244
- request = headers(VersionRange(), (Offer("missing", VersionRange()),))
275
+ request = headers(VersionRange(VERSION), (Offer("missing", VersionRange(VERSION)),))
245
276
  async with statewire_client(Host) as (app, client):
246
277
  async with attach_of(
247
278
  app,
@@ -256,7 +287,7 @@ async def test_http_and_websocket_negotiate_before_prepare_or_initial_commands()
256
287
  assert await socket.next_frame() is None
257
288
  assert socket.close_code == 1008
258
289
  assert prepared == [] and commands == []
259
- async with ws_of(app, headers=headers(VersionRange(), None)) as socket:
290
+ async with ws_of(app, headers=headers(VersionRange(VERSION), None)) as socket:
260
291
  hello = await socket.next_frame()
261
292
  assert hello["syn"]["protocols"] == [
262
293
  {"name": "base", "version": "2026-09-30", "seq": 0},
@@ -383,7 +414,16 @@ async def test_command_context_exposes_the_negotiated_protocol_version():
383
414
  q2, _, lease2 = await host._register("old", None, selection=older)
384
415
  frame = _ingest(
385
416
  json.dumps(
386
- {"cmd": [{"seq": 1, "protocol": "counter", "method": "increment", "params": []}]}
417
+ {
418
+ "cmd": [
419
+ {
420
+ "seq": 1,
421
+ "protocol": "counter",
422
+ "method": "increment",
423
+ "params": [],
424
+ }
425
+ ]
426
+ }
387
427
  )
388
428
  )
389
429
  await host._admit_frame(
File without changes
File without changes
File without changes
File without changes