statewire 0.23.2__tar.gz → 0.23.3__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.3}/PKG-INFO +1 -1
- {statewire-0.23.2 → statewire-0.23.3}/pyproject.toml +1 -1
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/api.py +100 -22
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/client.py +23 -2
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_client.py +38 -4
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_durable_admission.py +127 -18
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_frames.py +48 -0
- {statewire-0.23.2 → statewire-0.23.3}/.gitignore +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/README.md +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/examples/__init__.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/examples/demo_app.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/__init__.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/document.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/documents.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/filter.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/langgraph.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/limits.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/metrics.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/ops.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/protocol.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/state.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/src/statewire/testing.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/client_helpers.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/statewire_helpers.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/storage_probe.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_attach_fence.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_attach_guardrail.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_attached_hook.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_authorize.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_client_binding.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_client_ws.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_context.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_date_registry.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_departure.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_document.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_eviction.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_filter.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_gap_fill.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_idle.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_lanes.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_langgraph.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_lifespan.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_meta.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_observer.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_ops.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_protocol_negotiation.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_read_filters.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_route_auth.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_start_session.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_state_proxy.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_statewire_hostable.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_storage_bridge.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_stream.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_testing.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_writer_lease.py +0 -0
- {statewire-0.23.2 → statewire-0.23.3}/tests/test_ws.py +0 -0
|
@@ -193,7 +193,13 @@ from .limits import (
|
|
|
193
193
|
MAX_INFLIGHT_COMMANDS_PER_CLIENT,
|
|
194
194
|
MAX_INFLIGHT_COMMANDS_PER_HOST,
|
|
195
195
|
)
|
|
196
|
-
from .document import
|
|
196
|
+
from .document import (
|
|
197
|
+
StatewireDocument,
|
|
198
|
+
_decode_meta,
|
|
199
|
+
_frozen_encoded,
|
|
200
|
+
decode_document,
|
|
201
|
+
encode_document,
|
|
202
|
+
)
|
|
197
203
|
from .filter import ANY, UNFILTERED, Filter, FilterGroup, filter_value
|
|
198
204
|
from .state import (
|
|
199
205
|
collect_meta,
|
|
@@ -517,6 +523,7 @@ class _Invocation:
|
|
|
517
523
|
settled: bool = False
|
|
518
524
|
finalized: bool = False
|
|
519
525
|
faulted: bool = False
|
|
526
|
+
parked: bool = False
|
|
520
527
|
task: "asyncio.Task[None] | None" = None
|
|
521
528
|
tray_ctx: TrayCtx | None = None
|
|
522
529
|
release: "asyncio.Future[None]" = field(default_factory=asyncio.Future)
|
|
@@ -614,6 +621,20 @@ class _LeaseExpired(HTTPException):
|
|
|
614
621
|
super().__init__(status_code=423, detail="stale-lease")
|
|
615
622
|
|
|
616
623
|
|
|
624
|
+
class _IdentityUnencodable(HTTPException):
|
|
625
|
+
"""``authorize`` returned a value a durable host cannot store as the
|
|
626
|
+
client id's admission identity."""
|
|
627
|
+
|
|
628
|
+
fin = {
|
|
629
|
+
"reason": "error",
|
|
630
|
+
"code": "identity-unencodable",
|
|
631
|
+
"message": "authorization result is not wire-encodable",
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
def __init__(self) -> None:
|
|
635
|
+
super().__init__(status_code=500, detail=self.fin["message"])
|
|
636
|
+
|
|
637
|
+
|
|
617
638
|
class _FilterFailed(HTTPException):
|
|
618
639
|
"""A read-filter decider or rule failed: only the attaches it serves end."""
|
|
619
640
|
|
|
@@ -925,12 +946,12 @@ class _Client:
|
|
|
925
946
|
return lane
|
|
926
947
|
|
|
927
948
|
def command_load(self) -> int:
|
|
928
|
-
"""Durable commands
|
|
929
|
-
seqs =
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
for seq in lane.inflight
|
|
933
|
-
|
|
949
|
+
"""Durable commands holding admission capacity: pooled, or in flight and not parked."""
|
|
950
|
+
seqs: set[tuple[str, int]] = set()
|
|
951
|
+
parked: set[tuple[str, int]] = set()
|
|
952
|
+
for protocol, lane in self.lanes.items():
|
|
953
|
+
for seq, inv in lane.inflight.items():
|
|
954
|
+
(parked if inv.parked else seqs).add((protocol, seq))
|
|
934
955
|
if self.tray is not None:
|
|
935
956
|
seqs.update(
|
|
936
957
|
(statement["protocol"], statement["seq"])
|
|
@@ -938,7 +959,7 @@ class _Client:
|
|
|
938
959
|
if self.tray.attributed(frame)
|
|
939
960
|
for statement in _pool_statements(frame)
|
|
940
961
|
)
|
|
941
|
-
return len(seqs)
|
|
962
|
+
return len(seqs - parked)
|
|
942
963
|
|
|
943
964
|
|
|
944
965
|
@dataclass
|
|
@@ -1212,6 +1233,36 @@ class StatewireCommandContext:
|
|
|
1212
1233
|
)
|
|
1213
1234
|
|
|
1214
1235
|
|
|
1236
|
+
def _release_admission(applied: Callable[[], None]) -> None:
|
|
1237
|
+
"""Internal (harness_sdk's run manager): park a command without applying
|
|
1238
|
+
it. The client's later frames start while the handler keeps running, and
|
|
1239
|
+
the parked command leaves the client's and the host's in-flight capacity:
|
|
1240
|
+
the caller bounds its parked commands. ``applied`` is the command's
|
|
1241
|
+
``ctx.applied``; any other callable is ignored. On a durable host the
|
|
1242
|
+
caller must have durably recorded the command's intent first: a crash
|
|
1243
|
+
after the release no longer redelivers the frame. No-op after applied or
|
|
1244
|
+
settle."""
|
|
1245
|
+
ctx = getattr(applied, "__self__", None)
|
|
1246
|
+
if not isinstance(ctx, StatewireCommandContext):
|
|
1247
|
+
return
|
|
1248
|
+
inv = ctx._inv
|
|
1249
|
+
if inv.applied or inv.settled:
|
|
1250
|
+
return
|
|
1251
|
+
inv.parked = True
|
|
1252
|
+
inv.finish()
|
|
1253
|
+
|
|
1254
|
+
|
|
1255
|
+
def _admission_key(applied: Callable[[], None]) -> str | None:
|
|
1256
|
+
"""Internal (harness_sdk's run manager): a durable command's admission
|
|
1257
|
+
identity, ``client:protocol:seq``, from its ``ctx.applied``; stable across
|
|
1258
|
+
a redelivery of the frame. None on a memory host or for any other callable."""
|
|
1259
|
+
ctx = getattr(applied, "__self__", None)
|
|
1260
|
+
if not isinstance(ctx, StatewireCommandContext) or ctx._inv.tray_ctx is None:
|
|
1261
|
+
return None
|
|
1262
|
+
inv = ctx._inv
|
|
1263
|
+
return json.dumps([inv.client.id, inv.lane.protocol, inv.seq])
|
|
1264
|
+
|
|
1265
|
+
|
|
1215
1266
|
class StatewireReject(Exception):
|
|
1216
1267
|
"""Definitive handler rejection: a ``rejected`` verdict rides ``cmd`` on
|
|
1217
1268
|
the stream, the seq is consumed (no re-run on retry), and message/payload
|
|
@@ -2329,6 +2380,24 @@ class Statewire(PinnedAPI):
|
|
|
2329
2380
|
|
|
2330
2381
|
# ─── GET /stream ────────────────────────────────────────
|
|
2331
2382
|
|
|
2383
|
+
def _admission_identity(
|
|
2384
|
+
self, client_id: str, auth_result: Any
|
|
2385
|
+
) -> StatewireDocument.Encoded:
|
|
2386
|
+
"""The auth result as a durable admission identity, encoded."""
|
|
2387
|
+
try:
|
|
2388
|
+
return encode_document(auth_result)
|
|
2389
|
+
except (TypeError, ValueError) as exc:
|
|
2390
|
+
logger.error(
|
|
2391
|
+
"%s instance %r: authorize returned a result that is not "
|
|
2392
|
+
"wire-encodable, so it cannot be the durable admission "
|
|
2393
|
+
"identity of client %r: %s",
|
|
2394
|
+
type(self).__name__,
|
|
2395
|
+
self.id,
|
|
2396
|
+
client_id,
|
|
2397
|
+
exc,
|
|
2398
|
+
)
|
|
2399
|
+
raise _IdentityUnencodable from exc
|
|
2400
|
+
|
|
2332
2401
|
async def _register(
|
|
2333
2402
|
self,
|
|
2334
2403
|
client_id: str,
|
|
@@ -2391,15 +2460,14 @@ class Statewire(PinnedAPI):
|
|
|
2391
2460
|
raise HTTPException(
|
|
2392
2461
|
status_code=503, detail="stream subscriber limit reached"
|
|
2393
2462
|
)
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
not selection.ephemeral(statement["protocol"])
|
|
2399
|
-
for statement in frame.cmd
|
|
2400
|
-
)
|
|
2463
|
+
# A durable lane stores the auth result as the client id's admission
|
|
2464
|
+
# identity, both on a bind and on every admitted frame.
|
|
2465
|
+
if self._ctx.durability is not None and any(
|
|
2466
|
+
not selection.ephemeral(name) for name in selection.protocols
|
|
2401
2467
|
):
|
|
2402
|
-
|
|
2468
|
+
encoded_identity = self._admission_identity(client_id, auth_result)
|
|
2469
|
+
else:
|
|
2470
|
+
encoded_identity = None
|
|
2403
2471
|
client = self._clients.get(client_id) or _Client(self, client_id)
|
|
2404
2472
|
bind = False
|
|
2405
2473
|
if commands_tray is not None:
|
|
@@ -2409,6 +2477,8 @@ class Statewire(PinnedAPI):
|
|
|
2409
2477
|
raise _IdentityUnavailable
|
|
2410
2478
|
# an idle legacy record binds; held frames stay unattributed
|
|
2411
2479
|
bind = not commands_tray.holding()
|
|
2480
|
+
if bind and encoded_identity is None:
|
|
2481
|
+
encoded_identity = self._admission_identity(client_id, auth_result)
|
|
2412
2482
|
else:
|
|
2413
2483
|
if identity != auth_result:
|
|
2414
2484
|
raise _PrincipalMismatch
|
|
@@ -2534,7 +2604,8 @@ class Statewire(PinnedAPI):
|
|
|
2534
2604
|
and commands_tray.admission_identity() is _UNBOUND
|
|
2535
2605
|
and not commands_tray.pool.value
|
|
2536
2606
|
):
|
|
2537
|
-
|
|
2607
|
+
assert encoded_identity is not None
|
|
2608
|
+
commands_tray.bind(encoded_identity)
|
|
2538
2609
|
return q, snapshot, lease.id
|
|
2539
2610
|
|
|
2540
2611
|
def _gap_fill(
|
|
@@ -2571,7 +2642,11 @@ class Statewire(PinnedAPI):
|
|
|
2571
2642
|
):
|
|
2572
2643
|
if excess <= 0:
|
|
2573
2644
|
return
|
|
2574
|
-
if
|
|
2645
|
+
if (
|
|
2646
|
+
client_id in live
|
|
2647
|
+
or client.command_load() > 0
|
|
2648
|
+
or any(lane.inflight for lane in client.lanes.values())
|
|
2649
|
+
):
|
|
2575
2650
|
continue
|
|
2576
2651
|
del self._clients[client_id]
|
|
2577
2652
|
excess -= 1
|
|
@@ -2778,7 +2853,7 @@ class Statewire(PinnedAPI):
|
|
|
2778
2853
|
return JSONResponse({"fin": exc.fin}, status_code=403)
|
|
2779
2854
|
except _LeaseExpired as exc:
|
|
2780
2855
|
return JSONResponse({"fin": exc.fin}, status_code=423)
|
|
2781
|
-
except _FilterFailed as exc:
|
|
2856
|
+
except (_FilterFailed, _IdentityUnencodable) as exc:
|
|
2782
2857
|
return JSONResponse({"fin": exc.fin}, status_code=500)
|
|
2783
2858
|
except NegotiationError as exc:
|
|
2784
2859
|
return JSONResponse({"fin": exc.fin}, status_code=exc.status)
|
|
@@ -2794,7 +2869,7 @@ class Statewire(PinnedAPI):
|
|
|
2794
2869
|
return JSONResponse({"fin": exc.fin}, status_code=403)
|
|
2795
2870
|
except _LeaseExpired as exc:
|
|
2796
2871
|
return JSONResponse({"fin": exc.fin}, status_code=423)
|
|
2797
|
-
except _FilterFailed as exc:
|
|
2872
|
+
except (_FilterFailed, _IdentityUnencodable) as exc:
|
|
2798
2873
|
return JSONResponse({"fin": exc.fin}, status_code=500)
|
|
2799
2874
|
except NegotiationError as exc:
|
|
2800
2875
|
return JSONResponse({"fin": exc.fin}, status_code=exc.status)
|
|
@@ -2853,6 +2928,7 @@ class Statewire(PinnedAPI):
|
|
|
2853
2928
|
except (
|
|
2854
2929
|
_Violation,
|
|
2855
2930
|
_IdentityUnavailable,
|
|
2931
|
+
_IdentityUnencodable,
|
|
2856
2932
|
_PrincipalMismatch,
|
|
2857
2933
|
_LeaseExpired,
|
|
2858
2934
|
_FilterFailed,
|
|
@@ -2930,6 +3006,8 @@ class Statewire(PinnedAPI):
|
|
|
2930
3006
|
)
|
|
2931
3007
|
except _Violation as exc:
|
|
2932
3008
|
raise ValueError(exc.reason) from None
|
|
3009
|
+
except _IdentityUnencodable as exc:
|
|
3010
|
+
raise exc.__cause__ from None
|
|
2933
3011
|
except _FilterFailed as exc:
|
|
2934
3012
|
yield {"fin": exc.fin}
|
|
2935
3013
|
return
|
|
@@ -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
|
|
@@ -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:
|
|
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
|
|
File without changes
|
|
File without changes
|