statewire 0.23.2__tar.gz → 0.23.4__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.
- {statewire-0.23.2 → statewire-0.23.4}/PKG-INFO +1 -1
- {statewire-0.23.2 → statewire-0.23.4}/pyproject.toml +1 -1
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/api.py +105 -27
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/client.py +23 -2
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/protocol.py +1 -1
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_client.py +38 -4
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_durable_admission.py +127 -18
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_frames.py +48 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_gap_fill.py +34 -28
- {statewire-0.23.2 → statewire-0.23.4}/.gitignore +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/README.md +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/examples/__init__.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/examples/demo_app.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/__init__.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/document.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/documents.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/filter.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/langgraph.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/limits.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/metrics.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/ops.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/state.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/src/statewire/testing.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/client_helpers.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/statewire_helpers.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/storage_probe.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_attach_fence.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_attach_guardrail.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_attached_hook.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_authorize.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_client_binding.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_client_ws.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_context.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_date_registry.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_departure.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_document.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_eviction.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_filter.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_idle.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_lanes.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_langgraph.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_lifespan.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_meta.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_observer.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_ops.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_protocol_negotiation.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_read_filters.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_route_auth.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_start_session.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_state_proxy.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_statewire_hostable.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_storage_bridge.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_stream.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_testing.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_writer_lease.py +0 -0
- {statewire-0.23.2 → statewire-0.23.4}/tests/test_ws.py +0 -0
|
@@ -18,9 +18,11 @@ statement re-emits its stored verdict — ``applied`` while still in flight
|
|
|
18
18
|
once the first applied entry was emitted, nothing before that (the answers
|
|
19
19
|
ride the stream when ready), ``expired`` once the outcome outlived
|
|
20
20
|
retention) and a gap refuses the frame whole via ``{syn}`` carrying every
|
|
21
|
-
lane's watermark, nothing consumed.
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
lane's watermark, nothing consumed. Every wire absorbs a re-sent seq this
|
|
22
|
+
way: another attach of the client id may have landed it first (a gone tab's
|
|
23
|
+
late frame, a sharer's resend). Under wire ``2026-11-01`` the attach frame's
|
|
24
|
+
``res`` cursor answers the same way, per durable lane, every seq above it on
|
|
25
|
+
the hello. Durable lanes belong to the client id
|
|
24
26
|
and continue across attaches; ephemeral lanes (subprotocols registered with
|
|
25
27
|
``record="ephemeral"``) belong to the attach, restart at 1, and answer on
|
|
26
28
|
that attach only. Ephemeral statements in the attach frame are admitted
|
|
@@ -193,7 +195,13 @@ from .limits import (
|
|
|
193
195
|
MAX_INFLIGHT_COMMANDS_PER_CLIENT,
|
|
194
196
|
MAX_INFLIGHT_COMMANDS_PER_HOST,
|
|
195
197
|
)
|
|
196
|
-
from .document import
|
|
198
|
+
from .document import (
|
|
199
|
+
StatewireDocument,
|
|
200
|
+
_decode_meta,
|
|
201
|
+
_frozen_encoded,
|
|
202
|
+
decode_document,
|
|
203
|
+
encode_document,
|
|
204
|
+
)
|
|
197
205
|
from .filter import ANY, UNFILTERED, Filter, FilterGroup, filter_value
|
|
198
206
|
from .state import (
|
|
199
207
|
collect_meta,
|
|
@@ -517,6 +525,7 @@ class _Invocation:
|
|
|
517
525
|
settled: bool = False
|
|
518
526
|
finalized: bool = False
|
|
519
527
|
faulted: bool = False
|
|
528
|
+
parked: bool = False
|
|
520
529
|
task: "asyncio.Task[None] | None" = None
|
|
521
530
|
tray_ctx: TrayCtx | None = None
|
|
522
531
|
release: "asyncio.Future[None]" = field(default_factory=asyncio.Future)
|
|
@@ -614,6 +623,20 @@ class _LeaseExpired(HTTPException):
|
|
|
614
623
|
super().__init__(status_code=423, detail="stale-lease")
|
|
615
624
|
|
|
616
625
|
|
|
626
|
+
class _IdentityUnencodable(HTTPException):
|
|
627
|
+
"""``authorize`` returned a value a durable host cannot store as the
|
|
628
|
+
client id's admission identity."""
|
|
629
|
+
|
|
630
|
+
fin = {
|
|
631
|
+
"reason": "error",
|
|
632
|
+
"code": "identity-unencodable",
|
|
633
|
+
"message": "authorization result is not wire-encodable",
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
def __init__(self) -> None:
|
|
637
|
+
super().__init__(status_code=500, detail=self.fin["message"])
|
|
638
|
+
|
|
639
|
+
|
|
617
640
|
class _FilterFailed(HTTPException):
|
|
618
641
|
"""A read-filter decider or rule failed: only the attaches it serves end."""
|
|
619
642
|
|
|
@@ -925,12 +948,12 @@ class _Client:
|
|
|
925
948
|
return lane
|
|
926
949
|
|
|
927
950
|
def command_load(self) -> int:
|
|
928
|
-
"""Durable commands
|
|
929
|
-
seqs =
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
for seq in lane.inflight
|
|
933
|
-
|
|
951
|
+
"""Durable commands holding admission capacity: pooled, or in flight and not parked."""
|
|
952
|
+
seqs: set[tuple[str, int]] = set()
|
|
953
|
+
parked: set[tuple[str, int]] = set()
|
|
954
|
+
for protocol, lane in self.lanes.items():
|
|
955
|
+
for seq, inv in lane.inflight.items():
|
|
956
|
+
(parked if inv.parked else seqs).add((protocol, seq))
|
|
934
957
|
if self.tray is not None:
|
|
935
958
|
seqs.update(
|
|
936
959
|
(statement["protocol"], statement["seq"])
|
|
@@ -938,7 +961,7 @@ class _Client:
|
|
|
938
961
|
if self.tray.attributed(frame)
|
|
939
962
|
for statement in _pool_statements(frame)
|
|
940
963
|
)
|
|
941
|
-
return len(seqs)
|
|
964
|
+
return len(seqs - parked)
|
|
942
965
|
|
|
943
966
|
|
|
944
967
|
@dataclass
|
|
@@ -1212,6 +1235,36 @@ class StatewireCommandContext:
|
|
|
1212
1235
|
)
|
|
1213
1236
|
|
|
1214
1237
|
|
|
1238
|
+
def _release_admission(applied: Callable[[], None]) -> None:
|
|
1239
|
+
"""Internal (harness_sdk's run manager): park a command without applying
|
|
1240
|
+
it. The client's later frames start while the handler keeps running, and
|
|
1241
|
+
the parked command leaves the client's and the host's in-flight capacity:
|
|
1242
|
+
the caller bounds its parked commands. ``applied`` is the command's
|
|
1243
|
+
``ctx.applied``; any other callable is ignored. On a durable host the
|
|
1244
|
+
caller must have durably recorded the command's intent first: a crash
|
|
1245
|
+
after the release no longer redelivers the frame. No-op after applied or
|
|
1246
|
+
settle."""
|
|
1247
|
+
ctx = getattr(applied, "__self__", None)
|
|
1248
|
+
if not isinstance(ctx, StatewireCommandContext):
|
|
1249
|
+
return
|
|
1250
|
+
inv = ctx._inv
|
|
1251
|
+
if inv.applied or inv.settled:
|
|
1252
|
+
return
|
|
1253
|
+
inv.parked = True
|
|
1254
|
+
inv.finish()
|
|
1255
|
+
|
|
1256
|
+
|
|
1257
|
+
def _admission_key(applied: Callable[[], None]) -> str | None:
|
|
1258
|
+
"""Internal (harness_sdk's run manager): a durable command's admission
|
|
1259
|
+
identity, ``client:protocol:seq``, from its ``ctx.applied``; stable across
|
|
1260
|
+
a redelivery of the frame. None on a memory host or for any other callable."""
|
|
1261
|
+
ctx = getattr(applied, "__self__", None)
|
|
1262
|
+
if not isinstance(ctx, StatewireCommandContext) or ctx._inv.tray_ctx is None:
|
|
1263
|
+
return None
|
|
1264
|
+
inv = ctx._inv
|
|
1265
|
+
return json.dumps([inv.client.id, inv.lane.protocol, inv.seq])
|
|
1266
|
+
|
|
1267
|
+
|
|
1215
1268
|
class StatewireReject(Exception):
|
|
1216
1269
|
"""Definitive handler rejection: a ``rejected`` verdict rides ``cmd`` on
|
|
1217
1270
|
the stream, the seq is consumed (no re-run on retry), and message/payload
|
|
@@ -2329,6 +2382,24 @@ class Statewire(PinnedAPI):
|
|
|
2329
2382
|
|
|
2330
2383
|
# ─── GET /stream ────────────────────────────────────────
|
|
2331
2384
|
|
|
2385
|
+
def _admission_identity(
|
|
2386
|
+
self, client_id: str, auth_result: Any
|
|
2387
|
+
) -> StatewireDocument.Encoded:
|
|
2388
|
+
"""The auth result as a durable admission identity, encoded."""
|
|
2389
|
+
try:
|
|
2390
|
+
return encode_document(auth_result)
|
|
2391
|
+
except (TypeError, ValueError) as exc:
|
|
2392
|
+
logger.error(
|
|
2393
|
+
"%s instance %r: authorize returned a result that is not "
|
|
2394
|
+
"wire-encodable, so it cannot be the durable admission "
|
|
2395
|
+
"identity of client %r: %s",
|
|
2396
|
+
type(self).__name__,
|
|
2397
|
+
self.id,
|
|
2398
|
+
client_id,
|
|
2399
|
+
exc,
|
|
2400
|
+
)
|
|
2401
|
+
raise _IdentityUnencodable from exc
|
|
2402
|
+
|
|
2332
2403
|
async def _register(
|
|
2333
2404
|
self,
|
|
2334
2405
|
client_id: str,
|
|
@@ -2391,15 +2462,14 @@ class Statewire(PinnedAPI):
|
|
|
2391
2462
|
raise HTTPException(
|
|
2392
2463
|
status_code=503, detail="stream subscriber limit reached"
|
|
2393
2464
|
)
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
not selection.ephemeral(statement["protocol"])
|
|
2399
|
-
for statement in frame.cmd
|
|
2400
|
-
)
|
|
2465
|
+
# A durable lane stores the auth result as the client id's admission
|
|
2466
|
+
# identity, both on a bind and on every admitted frame.
|
|
2467
|
+
if self._ctx.durability is not None and any(
|
|
2468
|
+
not selection.ephemeral(name) for name in selection.protocols
|
|
2401
2469
|
):
|
|
2402
|
-
|
|
2470
|
+
encoded_identity = self._admission_identity(client_id, auth_result)
|
|
2471
|
+
else:
|
|
2472
|
+
encoded_identity = None
|
|
2403
2473
|
client = self._clients.get(client_id) or _Client(self, client_id)
|
|
2404
2474
|
bind = False
|
|
2405
2475
|
if commands_tray is not None:
|
|
@@ -2409,6 +2479,8 @@ class Statewire(PinnedAPI):
|
|
|
2409
2479
|
raise _IdentityUnavailable
|
|
2410
2480
|
# an idle legacy record binds; held frames stay unattributed
|
|
2411
2481
|
bind = not commands_tray.holding()
|
|
2482
|
+
if bind and encoded_identity is None:
|
|
2483
|
+
encoded_identity = self._admission_identity(client_id, auth_result)
|
|
2412
2484
|
else:
|
|
2413
2485
|
if identity != auth_result:
|
|
2414
2486
|
raise _PrincipalMismatch
|
|
@@ -2534,7 +2606,8 @@ class Statewire(PinnedAPI):
|
|
|
2534
2606
|
and commands_tray.admission_identity() is _UNBOUND
|
|
2535
2607
|
and not commands_tray.pool.value
|
|
2536
2608
|
):
|
|
2537
|
-
|
|
2609
|
+
assert encoded_identity is not None
|
|
2610
|
+
commands_tray.bind(encoded_identity)
|
|
2538
2611
|
return q, snapshot, lease.id
|
|
2539
2612
|
|
|
2540
2613
|
def _gap_fill(
|
|
@@ -2571,7 +2644,11 @@ class Statewire(PinnedAPI):
|
|
|
2571
2644
|
):
|
|
2572
2645
|
if excess <= 0:
|
|
2573
2646
|
return
|
|
2574
|
-
if
|
|
2647
|
+
if (
|
|
2648
|
+
client_id in live
|
|
2649
|
+
or client.command_load() > 0
|
|
2650
|
+
or any(lane.inflight for lane in client.lanes.values())
|
|
2651
|
+
):
|
|
2575
2652
|
continue
|
|
2576
2653
|
del self._clients[client_id]
|
|
2577
2654
|
excess -= 1
|
|
@@ -2778,7 +2855,7 @@ class Statewire(PinnedAPI):
|
|
|
2778
2855
|
return JSONResponse({"fin": exc.fin}, status_code=403)
|
|
2779
2856
|
except _LeaseExpired as exc:
|
|
2780
2857
|
return JSONResponse({"fin": exc.fin}, status_code=423)
|
|
2781
|
-
except _FilterFailed as exc:
|
|
2858
|
+
except (_FilterFailed, _IdentityUnencodable) as exc:
|
|
2782
2859
|
return JSONResponse({"fin": exc.fin}, status_code=500)
|
|
2783
2860
|
except NegotiationError as exc:
|
|
2784
2861
|
return JSONResponse({"fin": exc.fin}, status_code=exc.status)
|
|
@@ -2794,7 +2871,7 @@ class Statewire(PinnedAPI):
|
|
|
2794
2871
|
return JSONResponse({"fin": exc.fin}, status_code=403)
|
|
2795
2872
|
except _LeaseExpired as exc:
|
|
2796
2873
|
return JSONResponse({"fin": exc.fin}, status_code=423)
|
|
2797
|
-
except _FilterFailed as exc:
|
|
2874
|
+
except (_FilterFailed, _IdentityUnencodable) as exc:
|
|
2798
2875
|
return JSONResponse({"fin": exc.fin}, status_code=500)
|
|
2799
2876
|
except NegotiationError as exc:
|
|
2800
2877
|
return JSONResponse({"fin": exc.fin}, status_code=exc.status)
|
|
@@ -2853,6 +2930,7 @@ class Statewire(PinnedAPI):
|
|
|
2853
2930
|
except (
|
|
2854
2931
|
_Violation,
|
|
2855
2932
|
_IdentityUnavailable,
|
|
2933
|
+
_IdentityUnencodable,
|
|
2856
2934
|
_PrincipalMismatch,
|
|
2857
2935
|
_LeaseExpired,
|
|
2858
2936
|
_FilterFailed,
|
|
@@ -2930,6 +3008,8 @@ class Statewire(PinnedAPI):
|
|
|
2930
3008
|
)
|
|
2931
3009
|
except _Violation as exc:
|
|
2932
3010
|
raise ValueError(exc.reason) from None
|
|
3011
|
+
except _IdentityUnencodable as exc:
|
|
3012
|
+
raise exc.__cause__ from None
|
|
2933
3013
|
except _FilterFailed as exc:
|
|
2934
3014
|
yield {"fin": exc.fin}
|
|
2935
3015
|
return
|
|
@@ -3150,8 +3230,6 @@ class Statewire(PinnedAPI):
|
|
|
3150
3230
|
for name in _by_protocol(frame.cmd)
|
|
3151
3231
|
}
|
|
3152
3232
|
new = [s for s in frame.cmd if s["seq"] > through[s["protocol"]]]
|
|
3153
|
-
if len(new) < len(frame.cmd) and selection.version >= GAP_FILL_VERSION:
|
|
3154
|
-
raise _Violation("re-sent seq at or below the watermark")
|
|
3155
3233
|
for statement in frame.cmd:
|
|
3156
3234
|
if statement["seq"] <= through[statement["protocol"]]:
|
|
3157
3235
|
# a re-asked seq gets its stored verdict re-emitted on the stream
|
|
@@ -3722,9 +3800,9 @@ class Statewire(PinnedAPI):
|
|
|
3722
3800
|
except _LeaseExpired as exc:
|
|
3723
3801
|
await self._ws_send_fin(websocket, exc.fin)
|
|
3724
3802
|
raise WebSocketException(code=1000, reason="lease-expired") from exc
|
|
3725
|
-
except _FilterFailed as exc:
|
|
3803
|
+
except (_FilterFailed, _IdentityUnencodable) as exc:
|
|
3726
3804
|
await self._ws_send_fin(websocket, exc.fin)
|
|
3727
|
-
raise WebSocketException(code=1011, reason="
|
|
3805
|
+
raise WebSocketException(code=1011, reason=exc.fin["code"]) from exc
|
|
3728
3806
|
except NegotiationError as exc:
|
|
3729
3807
|
await self._ws_send_fin(websocket, exc.fin)
|
|
3730
3808
|
raise WebSocketException(code=1008, reason=str(exc)) from exc
|
|
@@ -203,6 +203,8 @@ class Timing:
|
|
|
203
203
|
backoff_base: float = 0.25
|
|
204
204
|
backoff_max: float = 30.0
|
|
205
205
|
backoff_reset: float = 30.0
|
|
206
|
+
# refusals of this client's versions retry this long before the client stops
|
|
207
|
+
version_refusal: float = 600.0
|
|
206
208
|
heartbeat_timeout: float = 30.0
|
|
207
209
|
rng: random.Random = field(default_factory=random.Random)
|
|
208
210
|
|
|
@@ -853,6 +855,7 @@ class StatewireClient:
|
|
|
853
855
|
self._epoch = 0
|
|
854
856
|
self._attempt = 0
|
|
855
857
|
self._auth_denials = 0
|
|
858
|
+
self._refused_since: float | None = None
|
|
856
859
|
self._episode: str | None = None
|
|
857
860
|
self._finished: dict[str, Any] | None = None
|
|
858
861
|
self._connection: dict[str, Any] = {"status": "connecting"}
|
|
@@ -1336,6 +1339,7 @@ class StatewireClient:
|
|
|
1336
1339
|
self._attached = True
|
|
1337
1340
|
self._frame_failures = 0
|
|
1338
1341
|
self._auth_denials = 0
|
|
1342
|
+
self._refused_since = None
|
|
1339
1343
|
self._epoch += 1
|
|
1340
1344
|
self._resume_at = 0.0
|
|
1341
1345
|
self._live_at = time.time()
|
|
@@ -1401,8 +1405,25 @@ class StatewireClient:
|
|
|
1401
1405
|
self._set_idle(True)
|
|
1402
1406
|
return "idle"
|
|
1403
1407
|
denial = reason == "unauthorized"
|
|
1404
|
-
|
|
1405
|
-
|
|
1408
|
+
# Mid rolling deploy, an attach can reach a host that does not serve
|
|
1409
|
+
# this client's versions yet: retry with backoff for a while.
|
|
1410
|
+
refused = reason == "protocol-error" and fin.get("code") in (
|
|
1411
|
+
"unsupported-version",
|
|
1412
|
+
"unsupported-protocol",
|
|
1413
|
+
)
|
|
1414
|
+
if refused and self._refused_since is None:
|
|
1415
|
+
self._refused_since = time.time()
|
|
1416
|
+
terminal = (
|
|
1417
|
+
reason in ("gone", "forbidden")
|
|
1418
|
+
or (
|
|
1419
|
+
reason == "protocol-error"
|
|
1420
|
+
and not (
|
|
1421
|
+
refused
|
|
1422
|
+
and self._refused_since is not None
|
|
1423
|
+
and time.time() - self._refused_since < self._timing.version_refusal
|
|
1424
|
+
)
|
|
1425
|
+
)
|
|
1426
|
+
or (denial and self._auth_denials > 0)
|
|
1406
1427
|
)
|
|
1407
1428
|
if denial:
|
|
1408
1429
|
self._auth_denials += 1
|
|
@@ -6,7 +6,7 @@ from typing import Any, Callable, Mapping
|
|
|
6
6
|
|
|
7
7
|
VERSION = "2026-09-30"
|
|
8
8
|
WIRE_VERSION = "2026-11-02"
|
|
9
|
-
# attach carries a results cursor;
|
|
9
|
+
# attach carries a results cursor; the hello answers every seq above it
|
|
10
10
|
GAP_FILL_VERSION = "2026-11-01"
|
|
11
11
|
# an attach names its attacher; a new attach retires the same attacher's earlier ones first
|
|
12
12
|
FENCE_VERSION = "2026-11-02"
|
|
@@ -319,9 +319,7 @@ async def test_hello_clears_retry_pushback():
|
|
|
319
319
|
|
|
320
320
|
|
|
321
321
|
async def test_hello_fin_settles_without_a_refusal():
|
|
322
|
-
transport = ScriptedTransport(
|
|
323
|
-
[{**HELLO, "fin": {"reason": "idle"}}], [HELLO]
|
|
324
|
-
)
|
|
322
|
+
transport = ScriptedTransport([{**HELLO, "fin": {"reason": "idle"}}], [HELLO])
|
|
325
323
|
async with StatewireClient(transport, timing=TIMING) as client:
|
|
326
324
|
await wait_for(lambda: client.connection["status"] == "idle")
|
|
327
325
|
client.send("inc")
|
|
@@ -711,6 +709,38 @@ async def test_terminal_finish_reporting(reason, reported):
|
|
|
711
709
|
assert transport.attaches == count
|
|
712
710
|
|
|
713
711
|
|
|
712
|
+
REFUSED = {
|
|
713
|
+
"fin": {
|
|
714
|
+
"reason": "protocol-error",
|
|
715
|
+
"code": "unsupported-version",
|
|
716
|
+
"message": "Statewire versions do not overlap",
|
|
717
|
+
"status": 406,
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
@pytest.mark.parametrize("code", ["unsupported-version", "unsupported-protocol"])
|
|
723
|
+
async def test_a_refusal_of_the_client_s_versions_is_retried(code):
|
|
724
|
+
refused = {"fin": {**REFUSED["fin"], "code": code}}
|
|
725
|
+
errors = []
|
|
726
|
+
transport = ScriptedTransport([refused], [refused], [HELLO])
|
|
727
|
+
async with StatewireClient(
|
|
728
|
+
transport, timing=TIMING, on_error=errors.append
|
|
729
|
+
) as client:
|
|
730
|
+
await wait_for(lambda: client.connection["status"] == "live")
|
|
731
|
+
assert transport.attaches == 3
|
|
732
|
+
assert len(errors) == 2
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
async def test_refusals_of_the_client_s_versions_stop_after_the_window():
|
|
736
|
+
timing = Timing(backoff_base=0.02, backoff_max=0.02, version_refusal=0.05)
|
|
737
|
+
transport = ScriptedTransport(*([[REFUSED]] * 50))
|
|
738
|
+
async with StatewireClient(transport, timing=timing) as client:
|
|
739
|
+
await wait_for(lambda: client.connection["status"] == "gone")
|
|
740
|
+
assert client.connection["reason"] == "protocol-error"
|
|
741
|
+
assert 1 < transport.attaches < 50
|
|
742
|
+
|
|
743
|
+
|
|
714
744
|
@pytest.mark.parametrize(
|
|
715
745
|
"code", ["evicted", "overloaded", "client-fell-behind", "future-code"]
|
|
716
746
|
)
|
|
@@ -760,7 +790,11 @@ async def test_submit_retry_is_capped_at_the_backoff_ceiling():
|
|
|
760
790
|
|
|
761
791
|
async def test_stream_refusal_retry_is_capped_at_the_backoff_ceiling():
|
|
762
792
|
transport = ScriptedTransport(
|
|
763
|
-
[
|
|
793
|
+
[
|
|
794
|
+
HELLO,
|
|
795
|
+
SUBMITTED,
|
|
796
|
+
{"syn": {"protocols": [{"name": "default", "seq": 0}], "retry": 2**53 - 1}},
|
|
797
|
+
]
|
|
764
798
|
)
|
|
765
799
|
async with StatewireClient(transport, timing=TIMING) as client:
|
|
766
800
|
await client.wait_state()
|
|
@@ -18,7 +18,7 @@ import pytest
|
|
|
18
18
|
|
|
19
19
|
from pinned import PinnedWorker, Tray, inbox, persistent_queue, tray
|
|
20
20
|
from pinned.testing import BarrierStateStore, MemoryStateStore, instance
|
|
21
|
-
from statewire_helpers import attach_of, post_frame, statewire_client
|
|
21
|
+
from statewire_helpers import attach_of, post_frame, statewire_client, ws_of
|
|
22
22
|
|
|
23
23
|
from statewire import Statewire, command
|
|
24
24
|
|
|
@@ -922,24 +922,94 @@ async def test_invalid_persisted_command_contracts_are_rejected_without_stalling
|
|
|
922
922
|
assert calls == [8]
|
|
923
923
|
|
|
924
924
|
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
925
|
+
class UserModel:
|
|
926
|
+
"""An auth result that is not wire-encodable, as a pydantic model."""
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
UNENCODABLE_FIN = {
|
|
930
|
+
"reason": "error",
|
|
931
|
+
"code": "identity-unencodable",
|
|
932
|
+
"message": "authorization result is not wire-encodable",
|
|
933
|
+
}
|
|
929
934
|
|
|
935
|
+
|
|
936
|
+
class InvalidIdentity(Admitting):
|
|
937
|
+
async def authorize(self, request):
|
|
938
|
+
return {"user": UserModel()}
|
|
939
|
+
|
|
940
|
+
|
|
941
|
+
async def test_non_encodable_identity_refuses_every_durable_attach():
|
|
930
942
|
store = MemoryStateStore()
|
|
931
943
|
async with statewire_client(
|
|
932
944
|
InvalidIdentity, worker=PinnedWorker(state_store=store)
|
|
933
945
|
) as (app, client):
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
946
|
+
response = await client.get(
|
|
947
|
+
"/threads/t1/stream", headers={"Statewire-Client-Id": "c1"}
|
|
948
|
+
)
|
|
949
|
+
assert response.status_code == 500
|
|
950
|
+
assert response.json() == {"fin": UNENCODABLE_FIN}
|
|
951
|
+
host = await instance_of(app)
|
|
952
|
+
assert host.attaches() == []
|
|
953
|
+
assert host._clients == {}
|
|
954
|
+
assert host.client_commands.instances == {}
|
|
955
|
+
assert store.trays == {}
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
async def test_non_encodable_identity_refuses_the_rebind_of_an_idle_record():
|
|
959
|
+
"""An idle unbound record binds on attach, without durable statements: the
|
|
960
|
+
attach is refused before the hello and the record stays unbound."""
|
|
961
|
+
store = MemoryStateStore()
|
|
962
|
+
row = ("/threads", "t1", "client_commands", "c1")
|
|
963
|
+
idle = (False, {"seq": {"default": 3}})
|
|
964
|
+
store.trays[row] = idle
|
|
965
|
+
async with statewire_client(
|
|
966
|
+
InvalidIdentity, worker=PinnedWorker(state_store=store)
|
|
967
|
+
) as (app, client):
|
|
968
|
+
response = await client.get(
|
|
969
|
+
"/threads/t1/stream", headers={"Statewire-Client-Id": "c1"}
|
|
970
|
+
)
|
|
971
|
+
assert response.status_code == 500
|
|
972
|
+
assert response.json() == {"fin": UNENCODABLE_FIN}
|
|
973
|
+
host = await instance_of(app)
|
|
974
|
+
assert host.attaches() == []
|
|
975
|
+
assert store.trays[row] == idle
|
|
976
|
+
|
|
977
|
+
|
|
978
|
+
async def test_non_encodable_identity_fins_a_websocket_attach():
|
|
979
|
+
async with statewire_client(
|
|
980
|
+
InvalidIdentity, worker=PinnedWorker(state_store=MemoryStateStore())
|
|
981
|
+
) as (app, client):
|
|
982
|
+
async with ws_of(app) as ws:
|
|
983
|
+
assert await ws.next_frame() == {"fin": UNENCODABLE_FIN}
|
|
984
|
+
assert await ws.next_frame() is None
|
|
985
|
+
assert ws.close_code == 1011
|
|
986
|
+
assert ws.close_reason == "identity-unencodable"
|
|
987
|
+
|
|
988
|
+
|
|
989
|
+
async def test_an_invalid_identity_value_is_refused_the_same_way():
|
|
990
|
+
class NonFinite(Admitting):
|
|
991
|
+
async def authorize(self, request):
|
|
992
|
+
return {"score": float("nan")}
|
|
993
|
+
|
|
994
|
+
async with statewire_client(
|
|
995
|
+
NonFinite, worker=PinnedWorker(state_store=MemoryStateStore())
|
|
996
|
+
) as (app, client):
|
|
997
|
+
response = await client.get(
|
|
998
|
+
"/threads/t1/stream", headers={"Statewire-Client-Id": "c1"}
|
|
999
|
+
)
|
|
1000
|
+
assert response.status_code == 500
|
|
1001
|
+
assert response.json() == {"fin": UNENCODABLE_FIN}
|
|
1002
|
+
|
|
1003
|
+
|
|
1004
|
+
@pytest.mark.parametrize(
|
|
1005
|
+
"auth_result,error",
|
|
1006
|
+
[({"user": UserModel()}, TypeError), ({"score": float("inf")}, ValueError)],
|
|
1007
|
+
)
|
|
1008
|
+
async def test_start_session_raises_the_encoder_error(auth_result, error):
|
|
1009
|
+
async with instance(Admitting, state_store=MemoryStateStore()) as live:
|
|
1010
|
+
with pytest.raises(error, match="wire-encodable|finite"):
|
|
1011
|
+
await anext(live.start_session("c1", auth_result))
|
|
1012
|
+
assert live.attaches() == []
|
|
943
1013
|
|
|
944
1014
|
|
|
945
1015
|
async def test_admission_identity_is_detached_from_mutable_resolver_result():
|
|
@@ -1064,12 +1134,51 @@ async def test_initial_mixed_frame_invalid_identity_runs_no_ephemeral_handler():
|
|
|
1064
1134
|
statement(1, params=[9]),
|
|
1065
1135
|
]
|
|
1066
1136
|
}
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1137
|
+
response = await client.post(
|
|
1138
|
+
"/threads/t1/stream", json=frame, headers={"Statewire-Client-Id": "c1"}
|
|
1139
|
+
)
|
|
1140
|
+
assert response.status_code == 500
|
|
1141
|
+
assert response.json() == {"fin": UNENCODABLE_FIN}
|
|
1071
1142
|
host = await instance_of(app)
|
|
1072
1143
|
assert host.attaches() == []
|
|
1073
1144
|
assert host._clients == {}
|
|
1074
1145
|
assert calls == []
|
|
1075
1146
|
assert store.trays == {}
|
|
1147
|
+
|
|
1148
|
+
|
|
1149
|
+
async def test_a_released_admission_frees_the_pool_slot_before_the_handler_settles():
|
|
1150
|
+
"""``_release_admission`` (the run manager's seam): the pooled frame pops
|
|
1151
|
+
while its handler still runs, without an applied entry."""
|
|
1152
|
+
from statewire.api import _admission_key, _release_admission
|
|
1153
|
+
from statewire.protocol import VERSION
|
|
1154
|
+
|
|
1155
|
+
started = asyncio.Event()
|
|
1156
|
+
release = asyncio.Event()
|
|
1157
|
+
seen = []
|
|
1158
|
+
keys = []
|
|
1159
|
+
|
|
1160
|
+
class Restored(Admitting):
|
|
1161
|
+
@command
|
|
1162
|
+
async def ask(self, by, *, ctx):
|
|
1163
|
+
_release_admission(lambda: None) # not ctx.applied: ignored
|
|
1164
|
+
keys.append((_admission_key(ctx.applied), _admission_key(lambda: None)))
|
|
1165
|
+
_release_admission(ctx.applied)
|
|
1166
|
+
seen.append(ctx._inv.applied)
|
|
1167
|
+
started.set()
|
|
1168
|
+
await release.wait()
|
|
1169
|
+
|
|
1170
|
+
store = MemoryStateStore()
|
|
1171
|
+
row = ("/test", "test", "client_commands", "old-client")
|
|
1172
|
+
store.trays[row] = (True, {
|
|
1173
|
+
"seq": {"default": 1},
|
|
1174
|
+
"pool": [{"statewire_admission": 1, "auth": {"value": None}, "statements": [{**statement(1, params=[1]), "_statewire_version": VERSION}]}],
|
|
1175
|
+
})
|
|
1176
|
+
async with instance(Restored, state_store=store) as live:
|
|
1177
|
+
await asyncio.wait_for(started.wait(), 2)
|
|
1178
|
+
async with asyncio.timeout(2):
|
|
1179
|
+
while pooled_statements(store):
|
|
1180
|
+
await live.frontier.wait()
|
|
1181
|
+
await asyncio.sleep(0.01)
|
|
1182
|
+
assert seen == [False]
|
|
1183
|
+
assert keys == [('["old-client", "default", 1]', None)]
|
|
1184
|
+
release.set()
|
|
@@ -604,6 +604,54 @@ async def test_frames_pushes_back_before_exceeding_client_command_capacity():
|
|
|
604
604
|
assert admitted.status_code == 200
|
|
605
605
|
|
|
606
606
|
|
|
607
|
+
async def test_parked_commands_leave_the_client_command_capacity():
|
|
608
|
+
from statewire.api import _release_admission
|
|
609
|
+
|
|
610
|
+
gate = asyncio.Event()
|
|
611
|
+
|
|
612
|
+
class Parking(Statewire):
|
|
613
|
+
async def lifespan(self):
|
|
614
|
+
self.state = {"pinged": 0}
|
|
615
|
+
yield
|
|
616
|
+
|
|
617
|
+
@command
|
|
618
|
+
async def park(self, *, ctx):
|
|
619
|
+
_release_admission(ctx.applied)
|
|
620
|
+
await gate.wait()
|
|
621
|
+
|
|
622
|
+
@command
|
|
623
|
+
async def ping(self):
|
|
624
|
+
self.state["pinged"] += 1
|
|
625
|
+
|
|
626
|
+
async with statewire_client(Parking) as (app, client):
|
|
627
|
+
async with attach_of(app, {"headers": {}}) as stream:
|
|
628
|
+
await stream.next_event()
|
|
629
|
+
for start in (1, MAX_COMMANDS_PER_FRAME + 1):
|
|
630
|
+
response = await post_frame(
|
|
631
|
+
client,
|
|
632
|
+
{
|
|
633
|
+
"cmd": [
|
|
634
|
+
cmd_statement(seq, method="park")
|
|
635
|
+
for seq in range(start, start + MAX_COMMANDS_PER_FRAME)
|
|
636
|
+
]
|
|
637
|
+
},
|
|
638
|
+
)
|
|
639
|
+
assert response.status_code == 200
|
|
640
|
+
ping = 2 * MAX_COMMANDS_PER_FRAME + 1
|
|
641
|
+
response = await post_frame(
|
|
642
|
+
client, {"cmd": [cmd_statement(ping, method="ping")]}
|
|
643
|
+
)
|
|
644
|
+
assert response.status_code == 200
|
|
645
|
+
await events_until(
|
|
646
|
+
stream,
|
|
647
|
+
lambda e: any(c["seq"] == ping for c in e.get("cmd", ())),
|
|
648
|
+
)
|
|
649
|
+
instance = (await app.state.pinned_host.directory.get("t1")).instance
|
|
650
|
+
assert instance.state["pinged"] == 1
|
|
651
|
+
gate.set()
|
|
652
|
+
await instance.idle()
|
|
653
|
+
|
|
654
|
+
|
|
607
655
|
async def test_frames_ctx_lane_is_a_violation():
|
|
608
656
|
async with statewire_client(make_counter()) as (app, client):
|
|
609
657
|
async with attach_of(app, {"headers": {}}) as stream:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Contract: the 2026-11-01 attach results cursor (`res`) gap-fills the hello
|
|
2
|
-
`cmd
|
|
3
|
-
|
|
2
|
+
`cmd`. A re-sent seq at or below the watermark re-emits its verdict on every
|
|
3
|
+
wire, as 2026-09-30 always did."""
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
6
|
|
|
@@ -126,34 +126,40 @@ async def test_a_cursor_at_the_watermark_fills_nothing():
|
|
|
126
126
|
assert "cmd" not in await stream.next_event()
|
|
127
127
|
|
|
128
128
|
|
|
129
|
-
async def
|
|
129
|
+
async def test_a_resent_seq_reemits_under_the_gap_fill_contract():
|
|
130
|
+
"""Another attach of the client id may land a seq first (a gone tab's
|
|
131
|
+
late frame): the copy re-emits its verdict and never runs again."""
|
|
130
132
|
async with statewire_client(make_host()) as (app, client):
|
|
131
|
-
async with attach_of(app, {"headers": {}}, headers=GAP_FILL) as
|
|
133
|
+
async with attach_of(app, {"headers": {}}, headers=GAP_FILL) as gone:
|
|
134
|
+
await gone.next_event()
|
|
135
|
+
gone_lease = gone.headers["statewire-lease"]
|
|
136
|
+
async with attach_of(app, {"headers": {}}, headers=GAP_FILL) as stream:
|
|
137
|
+
hello = await stream.next_event()
|
|
138
|
+
assert hello["syn"]["protocols"][0]["seq"] == 0
|
|
139
|
+
lease = stream.headers["statewire-lease"]
|
|
140
|
+
late = await post_frame(
|
|
141
|
+
client, {"cmd": [statement(1)]}, lease=gone_lease
|
|
142
|
+
)
|
|
143
|
+
assert late.status_code == 200
|
|
144
|
+
await cmds_until(stream, answer(1, "result", payload=1))
|
|
145
|
+
frame = {"cmd": [statement(1), statement(2)]}
|
|
146
|
+
response = await post_frame(client, frame, lease=lease)
|
|
147
|
+
assert response.status_code == 200
|
|
148
|
+
assert response.json() == {}
|
|
149
|
+
# the re-emit, then seq 2 ran second: count 2, not 3
|
|
150
|
+
await cmds_until(
|
|
151
|
+
stream,
|
|
152
|
+
answer(1, "result", payload=1),
|
|
153
|
+
answer(2, "result", payload=2),
|
|
154
|
+
)
|
|
155
|
+
async with attach_of(app, {"cmd": [statement(2)]}, headers=GAP_FILL) as stream:
|
|
156
|
+
hello = await stream.next_event()
|
|
157
|
+
assert "fin" not in hello
|
|
158
|
+
assert hello["syn"]["protocols"][0]["seq"] == 2
|
|
159
|
+
await cmds_until(stream, answer(2, "result", payload=2))
|
|
160
|
+
async with attach_of(app, {"cmd": [statement(3)]}, headers=GAP_FILL) as stream:
|
|
132
161
|
await stream.next_event()
|
|
133
|
-
|
|
134
|
-
assert (await post_frame(client, frame)).status_code == 200
|
|
135
|
-
await cmds_until(stream, answer(1, "result", payload=1))
|
|
136
|
-
response = await post_frame(client, {"cmd": [statement(1), statement(2)]})
|
|
137
|
-
assert response.status_code == 400
|
|
138
|
-
assert response.json() == {"error": "re-sent seq at or below the watermark"}
|
|
139
|
-
assert await stream.next_event() == {
|
|
140
|
-
"fin": {
|
|
141
|
-
"reason": "protocol-error",
|
|
142
|
-
"message": "re-sent seq at or below the watermark",
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
response = await client.post(
|
|
146
|
-
"/threads/t1/stream",
|
|
147
|
-
json={"cmd": [statement(1)]},
|
|
148
|
-
headers={api.CLIENT_ID_HEADER: "c1", **GAP_FILL},
|
|
149
|
-
)
|
|
150
|
-
assert response.status_code == 400
|
|
151
|
-
assert response.json() == {
|
|
152
|
-
"fin": {
|
|
153
|
-
"reason": "protocol-error",
|
|
154
|
-
"message": "re-sent seq at or below the watermark",
|
|
155
|
-
}
|
|
156
|
-
}
|
|
162
|
+
await cmds_until(stream, answer(3, "result", payload=3))
|
|
157
163
|
|
|
158
164
|
|
|
159
165
|
async def test_a_resent_seq_reemits_under_the_2026_09_30_contract():
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|