statewire 0.24.2__tar.gz → 0.24.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.
Files changed (60) hide show
  1. {statewire-0.24.2 → statewire-0.24.3}/PKG-INFO +3 -3
  2. {statewire-0.24.2 → statewire-0.24.3}/pyproject.toml +3 -3
  3. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/api.py +51 -5
  4. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/client.py +2 -1
  5. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/document.py +16 -11
  6. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/limits.py +6 -0
  7. {statewire-0.24.2 → statewire-0.24.3}/tests/test_attach_fence.py +34 -15
  8. statewire-0.24.3/tests/test_depth.py +94 -0
  9. {statewire-0.24.2 → statewire-0.24.3}/tests/test_document.py +12 -0
  10. {statewire-0.24.2 → statewire-0.24.3}/tests/test_durable_admission.py +131 -0
  11. {statewire-0.24.2 → statewire-0.24.3}/tests/test_meta.py +18 -0
  12. {statewire-0.24.2 → statewire-0.24.3}/tests/test_read_filters.py +11 -2
  13. {statewire-0.24.2 → statewire-0.24.3}/tests/test_storage_bridge.py +15 -3
  14. {statewire-0.24.2 → statewire-0.24.3}/.gitignore +0 -0
  15. {statewire-0.24.2 → statewire-0.24.3}/README.md +0 -0
  16. {statewire-0.24.2 → statewire-0.24.3}/examples/__init__.py +0 -0
  17. {statewire-0.24.2 → statewire-0.24.3}/examples/demo_app.py +0 -0
  18. {statewire-0.24.2 → statewire-0.24.3}/examples/local_origin.py +0 -0
  19. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/__init__.py +0 -0
  20. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/documents.py +0 -0
  21. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/filter.py +0 -0
  22. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/langgraph.py +0 -0
  23. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/metrics.py +0 -0
  24. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/ops.py +0 -0
  25. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/protocol.py +0 -0
  26. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/state.py +0 -0
  27. {statewire-0.24.2 → statewire-0.24.3}/src/statewire/testing.py +0 -0
  28. {statewire-0.24.2 → statewire-0.24.3}/tests/client_helpers.py +0 -0
  29. {statewire-0.24.2 → statewire-0.24.3}/tests/statewire_helpers.py +0 -0
  30. {statewire-0.24.2 → statewire-0.24.3}/tests/storage_probe.py +0 -0
  31. {statewire-0.24.2 → statewire-0.24.3}/tests/test_attach_guardrail.py +0 -0
  32. {statewire-0.24.2 → statewire-0.24.3}/tests/test_attached_hook.py +0 -0
  33. {statewire-0.24.2 → statewire-0.24.3}/tests/test_authorize.py +0 -0
  34. {statewire-0.24.2 → statewire-0.24.3}/tests/test_client.py +0 -0
  35. {statewire-0.24.2 → statewire-0.24.3}/tests/test_client_binding.py +0 -0
  36. {statewire-0.24.2 → statewire-0.24.3}/tests/test_client_ws.py +0 -0
  37. {statewire-0.24.2 → statewire-0.24.3}/tests/test_context.py +0 -0
  38. {statewire-0.24.2 → statewire-0.24.3}/tests/test_date_registry.py +0 -0
  39. {statewire-0.24.2 → statewire-0.24.3}/tests/test_departure.py +0 -0
  40. {statewire-0.24.2 → statewire-0.24.3}/tests/test_eviction.py +0 -0
  41. {statewire-0.24.2 → statewire-0.24.3}/tests/test_filter.py +0 -0
  42. {statewire-0.24.2 → statewire-0.24.3}/tests/test_frames.py +0 -0
  43. {statewire-0.24.2 → statewire-0.24.3}/tests/test_gap_fill.py +0 -0
  44. {statewire-0.24.2 → statewire-0.24.3}/tests/test_idle.py +0 -0
  45. {statewire-0.24.2 → statewire-0.24.3}/tests/test_lanes.py +0 -0
  46. {statewire-0.24.2 → statewire-0.24.3}/tests/test_langgraph.py +0 -0
  47. {statewire-0.24.2 → statewire-0.24.3}/tests/test_lifespan.py +0 -0
  48. {statewire-0.24.2 → statewire-0.24.3}/tests/test_observer.py +0 -0
  49. {statewire-0.24.2 → statewire-0.24.3}/tests/test_ops.py +0 -0
  50. {statewire-0.24.2 → statewire-0.24.3}/tests/test_origin.py +0 -0
  51. {statewire-0.24.2 → statewire-0.24.3}/tests/test_protocol_negotiation.py +0 -0
  52. {statewire-0.24.2 → statewire-0.24.3}/tests/test_route_auth.py +0 -0
  53. {statewire-0.24.2 → statewire-0.24.3}/tests/test_start_session.py +0 -0
  54. {statewire-0.24.2 → statewire-0.24.3}/tests/test_state_proxy.py +0 -0
  55. {statewire-0.24.2 → statewire-0.24.3}/tests/test_statewire_hostable.py +0 -0
  56. {statewire-0.24.2 → statewire-0.24.3}/tests/test_stream.py +0 -0
  57. {statewire-0.24.2 → statewire-0.24.3}/tests/test_testing.py +0 -0
  58. {statewire-0.24.2 → statewire-0.24.3}/tests/test_values.py +0 -0
  59. {statewire-0.24.2 → statewire-0.24.3}/tests/test_writer_lease.py +0 -0
  60. {statewire-0.24.2 → statewire-0.24.3}/tests/test_ws.py +0 -0
@@ -1,14 +1,14 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: statewire
3
- Version: 0.24.2
3
+ Version: 0.24.3
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
7
7
  Requires-Python: <4.0,>=3.12
8
8
  Requires-Dist: fastapi>=0.115
9
9
  Requires-Dist: httpx>=0.27
10
- Requires-Dist: pinboard-sdk>=0.18.3
11
- Requires-Dist: statepatch<0.4,>=0.3.0
10
+ Requires-Dist: pinboard-sdk>=0.18.4
11
+ Requires-Dist: statepatch<0.4,>=0.3.2
12
12
  Provides-Extra: langgraph
13
13
  Requires-Dist: langchain-core>=0.3; extra == 'langgraph'
14
14
  Provides-Extra: orjson
@@ -1,13 +1,13 @@
1
1
  [project]
2
2
  name = "statewire"
3
- version = "0.24.2"
3
+ version = "0.24.3"
4
4
  description = "Replicate one JSON object over an SSE op stream + a command endpoint"
5
5
  readme = "README.md"
6
6
  license = "MIT"
7
7
  requires-python = ">=3.12,<4.0"
8
8
  dependencies = [
9
- "pinboard-sdk>=0.18.3",
10
- "statepatch>=0.3.0,<0.4",
9
+ "pinboard-sdk>=0.18.4",
10
+ "statepatch>=0.3.2,<0.4",
11
11
  "fastapi>=0.115",
12
12
  "httpx>=0.27",
13
13
  ]
@@ -194,6 +194,7 @@ from .documents import Document, apply_documents, diff_documents
194
194
  from .limits import (
195
195
  COMMAND_CAPACITY_RETRY_MS,
196
196
  MAX_COMMANDS_PER_FRAME,
197
+ MAX_DOCUMENT_DEPTH,
197
198
  MAX_EPHEMERAL_DOCUMENT_BYTES,
198
199
  MAX_FRAME_BODY_BYTES,
199
200
  MAX_FRAME_VALUES,
@@ -682,23 +683,30 @@ _IDENTITY_UNAVAILABLE = {
682
683
  }
683
684
 
684
685
 
686
+ _MAX_STATEMENT_DEPTH = MAX_DOCUMENT_DEPTH - 3
687
+
688
+
685
689
  def _unstorable(value: Any) -> str | None:
686
690
  """Why a durable store refuses ``value``: a NUL or a lone surrogate in a
687
691
  string or object key, or a non-finite number. Postgres TEXT/JSONB reject
688
692
  NUL, UTF-8 has no lone surrogates, and JSON has no inf or NaN, so the
689
- admission write would fail and abort the instance."""
690
- stack = [value]
693
+ admission write would fail and abort the instance. A statement is stored
694
+ 3 levels down the pool (envelope, statements, its slot), so it also may
695
+ not nest deeper than the document limit leaves there."""
696
+ stack = [(value, 0)]
691
697
  while stack:
692
- node = stack.pop()
698
+ node, depth = stack.pop()
693
699
  if isinstance(node, float):
694
700
  if not math.isfinite(node):
695
701
  return "numbers must be finite"
696
702
  continue
703
+ if isinstance(node, (dict, list)) and depth >= _MAX_STATEMENT_DEPTH:
704
+ return f"params nest too deeply to store (limit {MAX_DOCUMENT_DEPTH} from the pool root)"
697
705
  if isinstance(node, dict):
698
706
  strings: Any = node.keys()
699
- stack.extend(node.values())
707
+ stack.extend((item, depth + 1) for item in node.values())
700
708
  elif isinstance(node, list):
701
- stack.extend(node)
709
+ stack.extend((item, depth + 1) for item in node)
702
710
  continue
703
711
  elif isinstance(node, str):
704
712
  strings = (node,)
@@ -837,11 +845,35 @@ class ClientCommands(Tray):
837
845
  drain_on_eviction = True
838
846
  seq = persistent({})
839
847
  pool = persistent([])
848
+ # wall time each pooled frame was admitted, keyed by its head statement;
849
+ # a separate field so the admission envelope keeps its strict shape
850
+ admitted_at = persistent({})
840
851
  parked = persistent([])
841
852
  quarantine = persistent([])
842
853
  identity = persistent(None)
843
854
  identity_through = persistent({})
844
855
 
856
+ @staticmethod
857
+ def _frame_key(frame: Any) -> str:
858
+ head = _pool_statements(frame)[0]
859
+ return f"{head['protocol']}:{head['seq']}"
860
+
861
+ def _stamps(self, keep: Any = ()) -> dict[str, Any]:
862
+ live = {self._frame_key(frame) for frame in self.pool.value}
863
+ return {
864
+ k: v for k, v in self.admitted_at.value.items() if k in live or k in keep
865
+ }
866
+
867
+ def _enqueued_at(self, frame: Any) -> float | None:
868
+ # a frame pooled before admitted_at existed is stamped on first sight
869
+ key = self._frame_key(frame)
870
+ at = self.admitted_at.value.get(key)
871
+ if isinstance(at, (int, float)) and not isinstance(at, bool):
872
+ return float(at)
873
+ at = self._domain.now()
874
+ self.admitted_at.value = {**self._stamps(), key: at}
875
+ return at
876
+
845
877
  def attributed(self, frame: Any) -> bool:
846
878
  if not isinstance(frame, list):
847
879
  return True
@@ -919,6 +951,9 @@ class ClientCommands(Tray):
919
951
  yield frame
920
952
  self._advance(_pool_statements(frame))
921
953
  self.pool.pop(0)
954
+ stamps = self._stamps()
955
+ if stamps != self.admitted_at.value:
956
+ self.admitted_at.value = stamps
922
957
 
923
958
  def _advance(self, statements: list[dict[str, Any]]) -> None:
924
959
  self.seq.value = {
@@ -950,6 +985,11 @@ class ClientCommands(Tray):
950
985
  self._check_above(statements)
951
986
  self.kick()
952
987
  self.identity.value = auth
988
+ key = f"{statements[0]['protocol']}:{statements[0]['seq']}"
989
+ self.admitted_at.value = {
990
+ **self._stamps(keep=(key,)),
991
+ key: self._domain.now(),
992
+ }
953
993
  if record == "list":
954
994
  self.pool.append(statements)
955
995
  self.identity_through.value = {
@@ -1031,6 +1071,9 @@ class ClientCommands(Tray):
1031
1071
  self._advance(statements)
1032
1072
  self.pool.value = pool
1033
1073
  self.quarantine.value = quarantine
1074
+ stamps = self._stamps()
1075
+ if stamps != self.admitted_at.value:
1076
+ self.admitted_at.value = stamps
1034
1077
  self.kick()
1035
1078
 
1036
1079
 
@@ -4234,6 +4277,9 @@ class Statewire(PinboardAPI):
4234
4277
  except asyncio.CancelledError:
4235
4278
  raise
4236
4279
  except WireEncodingError as exc:
4280
+ # Includes WireDepthError: a write past the document depth limit
4281
+ # fails at the write, so the document still encodes for every later
4282
+ # attach; the command settles failed, as in the TypeScript host.
4237
4283
  logger.exception("command state is not wire-encodable")
4238
4284
  self._settle(inv, {"type": "failed", "message": str(exc)})
4239
4285
  except Exception:
@@ -38,6 +38,7 @@ from .ops import (
38
38
  )
39
39
  from .limits import (
40
40
  MAX_COMMANDS_PER_FRAME,
41
+ MAX_DOCUMENT_DEPTH,
41
42
  MAX_FRAME_BODY_BYTES,
42
43
  MAX_EPHEMERAL_DOCUMENT_BYTES,
43
44
  )
@@ -223,7 +224,7 @@ def _backoff(timing: Timing, attempt: int) -> float:
223
224
  # ─── Wire values (meta-typed dates) ─────────────────────────
224
225
 
225
226
 
226
- _MAX_DEPTH = 512
227
+ _MAX_DEPTH = MAX_DOCUMENT_DEPTH
227
228
 
228
229
 
229
230
  def _received(
@@ -6,6 +6,8 @@ import re
6
6
  from datetime import datetime, timezone
7
7
  from typing import Any, Literal, NotRequired, TypedDict
8
8
 
9
+ from .limits import MAX_DOCUMENT_DEPTH
10
+
9
11
 
10
12
  class StatewireDocument:
11
13
  class MetaEntry(TypedDict):
@@ -86,15 +88,15 @@ def _copy_value(
86
88
  if mode != "json" and isinstance(value, datetime):
87
89
  if value.tzinfo is None or value.utcoffset() is None:
88
90
  fail("a naive datetime", "datetimes need a timezone")
89
- if mode == "native":
90
- meta.append({"path": list(path), "type": "date"})
91
- return value
92
91
  try:
93
92
  utc = value.astimezone(timezone.utc)
94
93
  except (OverflowError, ValueError):
95
94
  fail(
96
95
  f"the datetime {value!r}", "dates must have a UTC year from 0001 to 9999"
97
96
  )
97
+ if mode == "native":
98
+ meta.append({"path": list(path), "type": "date"})
99
+ return value
98
100
  if utc.microsecond % 1000:
99
101
  fail(f"the datetime {value!r}", "dates have millisecond precision")
100
102
  meta.append({"path": list(path), "type": "date"})
@@ -107,6 +109,8 @@ def _copy_value(
107
109
  ancestors = set()
108
110
  if id(value) in ancestors:
109
111
  fail("a cycle", "a value can't contain itself")
112
+ if len(path) >= MAX_DOCUMENT_DEPTH:
113
+ fail("a value", f"it is nested deeper than {MAX_DOCUMENT_DEPTH}")
110
114
  ancestors.add(id(value))
111
115
  if isinstance(value, (list, tuple)):
112
116
  result = [
@@ -141,19 +145,20 @@ def encode_document(value: Any, root: str = "") -> StatewireDocument.Encoded:
141
145
 
142
146
  def decode_document(encoded: object) -> Any:
143
147
  """Validate and decode a document into detached values with native dates."""
144
- document = _copy_value(encoded, "json", [])
145
148
  if (
146
- not isinstance(document, dict)
147
- or "value" not in document
148
- or document.keys() - {"value", "meta"}
149
+ not isinstance(encoded, dict)
150
+ or "value" not in encoded
151
+ or encoded.keys() - {"value", "meta"}
149
152
  ):
150
153
  raise ValueError("expected an object with value and optional meta")
151
- value = document["value"]
152
- if "meta" not in document:
154
+ # Depth counts from the value, not the wrapper, as encode_document writes it.
155
+ value = _copy_value(encoded["value"], "json", [])
156
+ if "meta" not in encoded:
153
157
  return value
154
- if not isinstance(document["meta"], list):
158
+ meta = _copy_value(encoded["meta"], "json", [])
159
+ if not isinstance(meta, list):
155
160
  raise ValueError("meta must be an array")
156
- return _decode_meta(value, document["meta"], reject_unknown=True, canonical=True)
161
+ return _decode_meta(value, meta, reject_unknown=True, canonical=True)
157
162
 
158
163
 
159
164
  def _frozen_encoded(value: Any) -> tuple[Any, list[StatewireDocument.MetaEntry] | None]:
@@ -1,4 +1,10 @@
1
+ from statepatch import MAX_DEPTH
2
+
1
3
  MAX_COMMANDS_PER_FRAME = 256
4
+ # Container levels a document may hold, from its root; matches the TypeScript
5
+ # host's MAX_DOCUMENT_DEPTH. State writes count from the document root
6
+ # (statepatch), so the attach snapshot never nests past what orjson encodes.
7
+ MAX_DOCUMENT_DEPTH = MAX_DEPTH
2
8
  MAX_INFLIGHT_COMMANDS_PER_CLIENT = 256
3
9
  MAX_FRAME_BODY_BYTES = 8 * 1024 * 1024
4
10
  # Values (containers and leaves) one frame may hold; matches the TypeScript host.
@@ -51,9 +51,11 @@ def tab(negotiation, attacher, **extra):
51
51
 
52
52
  @pytest.fixture
53
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()
54
+ """Holds the admission of seq 1 until `gate` is set; `entered` once it waits,
55
+ `fenced` once an attach waits for a lease still admitting."""
56
+ gate, entered, fenced = asyncio.Event(), asyncio.Event(), asyncio.Event()
56
57
  original = api.Statewire._admit_frame_once
58
+ retire = api.Statewire._retire_lease
57
59
 
58
60
  async def held(self, client, frame, received, lease):
59
61
  if any(s["seq"] == 1 for s in frame.cmd) and not gate.is_set():
@@ -61,16 +63,25 @@ def held_first_admission(monkeypatch):
61
63
  await gate.wait()
62
64
  return await original(self, client, frame, received, lease)
63
65
 
66
+ async def retire_lease(self, lease):
67
+ if lease.admitting:
68
+ fenced.set()
69
+ return await retire(self, lease)
70
+
64
71
  monkeypatch.setattr(api.Statewire, "_admit_frame_once", held)
65
- return gate, entered
72
+ monkeypatch.setattr(api.Statewire, "_retire_lease", retire_lease)
73
+ return gate, entered, fenced
66
74
 
67
75
 
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."""
76
+ async def hello_after_release(app, negotiation, held, frame=None):
77
+ """The hello of a new attach, with the held admission released once the attach
78
+ answered or waits for it; `waited`: it waited instead of answering."""
79
+ gate, _, fenced = held
71
80
  attach = attach_of(app, frame or {"headers": {}}, headers=negotiation)
72
81
  entering = asyncio.create_task(attach.__aenter__())
73
- await asyncio.sleep(0.05)
82
+ fence = asyncio.create_task(fenced.wait())
83
+ await asyncio.wait({entering, fence}, return_when=asyncio.FIRST_COMPLETED)
84
+ fence.cancel()
74
85
  waited = not entering.done()
75
86
  gate.set()
76
87
  stream = await entering
@@ -81,7 +92,7 @@ async def hello_after_release(app, negotiation, gate, frame=None):
81
92
 
82
93
 
83
94
  async def test_a_reattach_retires_the_attacher_s_earlier_attach(held_first_admission):
84
- gate, entered = held_first_admission
95
+ _, entered, _ = held_first_admission
85
96
  async with statewire_client(Host) as (app, client):
86
97
  async with attach_of(
87
98
  app, {"headers": {}}, headers=tab(FENCE, "tab-1")
@@ -93,7 +104,9 @@ async def test_a_reattach_retires_the_attacher_s_earlier_attach(held_first_admis
93
104
  post_frame(client, {"cmd": [statement(1)]}, lease=replaced)
94
105
  )
95
106
  await entered.wait()
96
- waited, hello = await hello_after_release(app, tab(FENCE, "tab-1"), gate)
107
+ waited, hello = await hello_after_release(
108
+ app, tab(FENCE, "tab-1"), held_first_admission
109
+ )
97
110
  assert waited
98
111
  assert hello["syn"]["protocols"][0]["seq"] == 1
99
112
  assert (await posted).status_code == 200
@@ -106,7 +119,7 @@ async def test_a_reattach_retires_the_attacher_s_earlier_attach(held_first_admis
106
119
 
107
120
 
108
121
  async def test_a_retry_whose_previous_hello_was_lost_still_waits(held_first_admission):
109
- gate, entered = held_first_admission
122
+ _, entered, _ = held_first_admission
110
123
  async with statewire_client(Host) as (app, client):
111
124
  async with attach_of(
112
125
  app, {"headers": {}}, headers=tab(FENCE, "tab-1")
@@ -115,14 +128,16 @@ async def test_a_retry_whose_previous_hello_was_lost_still_waits(held_first_admi
115
128
  lost = attach_of(app, {"cmd": [statement(1)]}, headers=tab(FENCE, "tab-1"))
116
129
  lost_task = asyncio.create_task(lost.__aenter__())
117
130
  await entered.wait()
118
- waited, hello = await hello_after_release(app, tab(FENCE, "tab-1"), gate)
131
+ waited, hello = await hello_after_release(
132
+ app, tab(FENCE, "tab-1"), held_first_admission
133
+ )
119
134
  assert waited
120
135
  assert hello["syn"]["protocols"][0]["seq"] == 1
121
136
  await (await lost_task).__aexit__(None, None, None)
122
137
 
123
138
 
124
139
  async def test_another_attacher_on_the_client_id_is_untouched(held_first_admission):
125
- gate, entered = held_first_admission
140
+ _, entered, _ = held_first_admission
126
141
  async with statewire_client(Host) as (app, client):
127
142
  async with attach_of(
128
143
  app, {"headers": {}}, headers=tab(FENCE, "tab-1")
@@ -136,7 +151,9 @@ async def test_another_attacher_on_the_client_id_is_untouched(held_first_admissi
136
151
  )
137
152
  )
138
153
  await entered.wait()
139
- waited, hello = await hello_after_release(app, tab(FENCE, "tab-2"), gate)
154
+ waited, hello = await hello_after_release(
155
+ app, tab(FENCE, "tab-2"), held_first_admission
156
+ )
140
157
  assert not waited
141
158
  assert (await posted).status_code == 200
142
159
  second = await post_frame(
@@ -146,7 +163,7 @@ async def test_another_attacher_on_the_client_id_is_untouched(held_first_admissi
146
163
 
147
164
 
148
165
  async def test_without_the_fence_the_hello_can_predate_a_frame(held_first_admission):
149
- gate, entered = held_first_admission
166
+ _, entered, _ = held_first_admission
150
167
  async with statewire_client(Host) as (app, client):
151
168
  async with attach_of(
152
169
  app, {"headers": {}}, headers=tab(GAP_FILL, "tab-1")
@@ -160,7 +177,9 @@ async def test_without_the_fence_the_hello_can_predate_a_frame(held_first_admiss
160
177
  )
161
178
  )
162
179
  await entered.wait()
163
- waited, hello = await hello_after_release(app, tab(GAP_FILL, "tab-1"), gate)
180
+ waited, hello = await hello_after_release(
181
+ app, tab(GAP_FILL, "tab-1"), held_first_admission
182
+ )
164
183
  assert not waited
165
184
  assert hello["syn"]["protocols"][0]["seq"] == 0
166
185
  assert (await posted).status_code == 200
@@ -0,0 +1,94 @@
1
+ """State writes count depth from the document root, so a legal param stored a
2
+ few levels down fails its command instead of every later attach of the thread."""
3
+
4
+ import pytest
5
+ from statewire import Statewire, command
6
+ from statewire import ops as ops_module
7
+ from statewire.limits import MAX_DOCUMENT_DEPTH
8
+
9
+ from statewire_helpers import post_frame, statewire_client, stream_of
10
+
11
+
12
+ @pytest.fixture(params=["orjson", "stdlib"])
13
+ def serializer(request, monkeypatch):
14
+ if request.param == "stdlib":
15
+ monkeypatch.setattr(ops_module, "orjson", None)
16
+ elif ops_module.orjson is None:
17
+ pytest.skip("orjson not installed")
18
+ return request.param
19
+
20
+
21
+ class Nest(Statewire):
22
+ async def lifespan(self):
23
+ self.state = {"a": {}}
24
+ yield
25
+
26
+ @command
27
+ async def nest(self, value):
28
+ self.state["a"]["b"] = value
29
+
30
+
31
+ def nested(levels):
32
+ value = []
33
+ for _ in range(levels - 1):
34
+ value = [value]
35
+ return value
36
+
37
+
38
+ async def nest(app, client, levels):
39
+ async with stream_of(app) as stream:
40
+ await stream.next_event()
41
+ frame = {
42
+ "cmd": [
43
+ {
44
+ "protocol": "default",
45
+ "method": "nest",
46
+ "params": [nested(levels)],
47
+ "seq": 1,
48
+ }
49
+ ]
50
+ }
51
+ assert (await post_frame(client, frame)).status_code == 200
52
+ while True:
53
+ env = await stream.next_event()
54
+ verdicts = [e for e in env.get("cmd", []) if "type" in e]
55
+ if verdicts:
56
+ (verdict,) = verdicts
57
+ return verdict
58
+
59
+
60
+ async def later_attach(app):
61
+ async with stream_of(app, client_id="c2") as stream:
62
+ [mount] = (await stream.next_event())["ops"]
63
+ return mount["value"]
64
+
65
+
66
+ async def test_reported_deep_param_is_refused_and_later_attaches_load(serializer):
67
+ # The reported param: it fit the 256-level frame check, then nested past
68
+ # orjson's limit inside the snapshot envelope at state["a"]["b"]. It is
69
+ # past the document limit itself, so it is refused before the handler runs.
70
+ async with statewire_client(Nest) as (app, client):
71
+ verdict = await nest(app, client, 251)
72
+ assert verdict["type"] == "rejected"
73
+ assert verdict["code"] == "invalid-params"
74
+ assert f"nested deeper than {MAX_DOCUMENT_DEPTH}" in verdict["message"]
75
+ assert await later_attach(app) == {"a": {}}
76
+
77
+
78
+ async def test_too_deep_write_fails_its_command_and_later_attaches_load(serializer):
79
+ # Legal params (240 levels with the params array), too deep at a.b: the
80
+ # write fails inside the handler, so the command settles failed, as in TS.
81
+ async with statewire_client(Nest) as (app, client):
82
+ verdict = await nest(app, client, MAX_DOCUMENT_DEPTH - 1)
83
+ assert verdict["type"] == "failed"
84
+ assert "code" not in verdict
85
+ assert f"nested deeper than {MAX_DOCUMENT_DEPTH}" in verdict["message"]
86
+ assert await later_attach(app) == {"a": {}}
87
+
88
+
89
+ async def test_deep_write_within_the_limit_is_stored(serializer):
90
+ levels = MAX_DOCUMENT_DEPTH - 2 # the document holds exactly the limit
91
+ async with statewire_client(Nest) as (app, client):
92
+ verdict = await nest(app, client, levels)
93
+ assert verdict["type"] == "result"
94
+ assert await later_attach(app) == {"a": {"b": nested(levels)}}
@@ -6,6 +6,7 @@ from pathlib import Path
6
6
  import pytest
7
7
 
8
8
  from statewire import decode_document, encode_document
9
+ from statewire.limits import MAX_DOCUMENT_DEPTH
9
10
 
10
11
  FIXTURES = json.loads(
11
12
  (
@@ -102,6 +103,17 @@ def test_unsafe_keys_encode_as_written_and_never_decode(value):
102
103
  decode_document({"value": value})
103
104
 
104
105
 
106
+ def test_depth_limit_counts_from_the_value_both_ways():
107
+ deepest = []
108
+ for _ in range(MAX_DOCUMENT_DEPTH - 1):
109
+ deepest = [deepest]
110
+ assert decode_document(encode_document(deepest)) == deepest
111
+ with pytest.raises(ValueError, match="nested deeper than"):
112
+ encode_document([deepest])
113
+ with pytest.raises(ValueError, match="nested deeper than"):
114
+ decode_document({"value": [deepest]})
115
+
116
+
105
117
  def test_cycles_in_both_directions():
106
118
  value = []
107
119
  value.append(value)
@@ -1304,6 +1304,41 @@ async def test_an_unstorable_frame_is_rejected_before_the_store(bad):
1304
1304
  assert calls == ["fine"]
1305
1305
 
1306
1306
 
1307
+ async def test_params_too_deep_for_the_pool_are_rejected_before_the_store():
1308
+ # Legal params (240 levels with the params array) sit 5 levels down the
1309
+ # pool, past the document limit: refused at admission, not mid-write.
1310
+ from statewire.limits import MAX_DOCUMENT_DEPTH
1311
+
1312
+ calls = []
1313
+
1314
+ class Noting(Admitting):
1315
+ @command
1316
+ async def note(self, text: object):
1317
+ calls.append(text)
1318
+ return {"ok": True}
1319
+
1320
+ deep: list = []
1321
+ for _ in range(MAX_DOCUMENT_DEPTH - 2):
1322
+ deep = [deep]
1323
+ store = MemoryStateStore()
1324
+ async with statewire_client(Noting, worker=Worker(state_store=store)) as (app, client):
1325
+ async with attach_of(app, {"headers": {}}) as stream:
1326
+ await stream.next_event()
1327
+ frame = {"cmd": [statement(1, "note", [deep])]}
1328
+ assert (await post_frame(client, frame)).status_code == 200
1329
+ seen = await cmds_until(stream, {"protocol": "default", "seq": 1, "dur": True})
1330
+ verdict = next(c for c in seen if c.get("seq") == 1 and "type" in c)
1331
+ assert verdict["type"] == "rejected" and verdict["code"] == "invalid-params", verdict
1332
+ assert not pooled_statements(store)
1333
+ frame = {"cmd": [statement(2, "note", ["fine"])]}
1334
+ assert (await post_frame(client, frame)).status_code == 200
1335
+ await cmds_until(
1336
+ stream,
1337
+ {"protocol": "default", "seq": 2, "type": "result", "payload": {"ok": True}},
1338
+ )
1339
+ assert calls == ["fine"]
1340
+
1341
+
1307
1342
  class _Noting(Admitting):
1308
1343
  calls: list = []
1309
1344
 
@@ -1407,3 +1442,99 @@ async def test_an_overflowing_number_never_reaches_the_durable_store(number):
1407
1442
  # the valid sibling never ran either: the whole frame is malformed
1408
1443
  assert _Noting.calls == []
1409
1444
  assert NulRefusingStore.refused == 0
1445
+
1446
+
1447
+ DAY = 24 * 3600.0
1448
+
1449
+
1450
+ def pooled_frame(seq):
1451
+ from statewire.protocol import VERSION
1452
+
1453
+ return {
1454
+ "statewire_admission": 1,
1455
+ "auth": {"value": None},
1456
+ "statements": [{**statement(seq, params=[seq]), "_statewire_version": VERSION}],
1457
+ }
1458
+
1459
+
1460
+ async def test_a_pooled_frame_past_max_dispatch_age_parks_instead_of_replaying():
1461
+ """pinboard's 14-day ceiling bounds cold replay through each frame's
1462
+ admission time: a frame admitted long ago parks the client's tray
1463
+ without running, and the frame stays pooled for unpark()."""
1464
+ import time
1465
+
1466
+ calls = []
1467
+
1468
+ class Restored(Admitting):
1469
+ @command
1470
+ async def ask(self, by):
1471
+ calls.append(by)
1472
+
1473
+ store = MemoryStateStore()
1474
+ row = ("/test", "test", "client_commands", "old-client")
1475
+ pool = [pooled_frame(1), pooled_frame(2)]
1476
+ store.trays[row] = (
1477
+ True,
1478
+ {
1479
+ "seq": {"default": 2},
1480
+ "pool": deepcopy(pool),
1481
+ # frame 1 predates admitted_at; frame 2 was admitted 15 days ago
1482
+ "admitted_at": {"default:2": time.time() - 15 * DAY},
1483
+ },
1484
+ )
1485
+ before = time.time()
1486
+ async with instance(Restored, state_store=store) as live:
1487
+ async with asyncio.timeout(2):
1488
+ while not store.trays[row][1].get("~parked"):
1489
+ await asyncio.sleep(0.005)
1490
+ await live.frontier.wait()
1491
+ assert calls == [1] # the legacy frame was stamped on sight and ran
1492
+ marked, doc = store.trays[row]
1493
+ assert marked is True
1494
+ assert doc["pool"] == pool[1:]
1495
+ assert set(doc["admitted_at"]) == {"default:2"}
1496
+ assert doc["seq"] == {"default": 2}
1497
+
1498
+ calls.clear()
1499
+ async with instance(Restored, state_store=store):
1500
+ await asyncio.sleep(0.05)
1501
+ assert calls == [] # still parked
1502
+ assert store.trays[row][1]["pool"] == pool[1:]
1503
+ assert before > store.trays[row][1]["admitted_at"]["default:2"]
1504
+
1505
+
1506
+ async def test_admission_stamps_each_pooled_frame_and_the_ack_prunes_it():
1507
+ import time
1508
+
1509
+ gate = asyncio.Event()
1510
+ runs = []
1511
+
1512
+ class Held(Admitting):
1513
+ @command
1514
+ async def slow(self, value: int):
1515
+ await gate.wait()
1516
+ runs.append(value)
1517
+
1518
+ def stamps(store):
1519
+ return [
1520
+ doc.get("admitted_at")
1521
+ for key, (_m, doc) in store.trays.items()
1522
+ if key[2] == "client_commands"
1523
+ ]
1524
+
1525
+ store = MemoryStateStore()
1526
+ before = time.time()
1527
+ async with statewire_client(Held, worker=Worker(state_store=store)) as (app, client):
1528
+ async with attach_of(app, {"headers": {}}) as stream:
1529
+ await stream.next_event()
1530
+ frame = {"cmd": [statement(1, "slow", [7])]}
1531
+ assert (await post_frame(client, frame)).status_code == 200
1532
+ await cmds_until(stream, {"protocol": "default", "seq": 1, "dur": True})
1533
+ ((stamp,),) = [list(s.items()) for s in stamps(store)]
1534
+ assert stamp[0] == "default:1" and stamp[1] >= before
1535
+ gate.set()
1536
+ async with asyncio.timeout(2):
1537
+ while pool_records(store):
1538
+ await asyncio.sleep(0.005)
1539
+ assert runs == [7]
1540
+ assert stamps(store) == [None]
@@ -165,6 +165,24 @@ async def test_bad_date_string_settles_rejected_invalid_params():
165
165
  assert res["code"] == "invalid-params"
166
166
 
167
167
 
168
+ @pytest.mark.parametrize(
169
+ "when", ["0001-01-01T00:00:00+05:00", "9999-12-31T23:00:00-05:00"]
170
+ )
171
+ async def test_date_outside_utc_range_is_refused_and_thread_still_attaches(when):
172
+ async with statewire_client(Timed) as (app, client):
173
+ async with stream_of(app) as stream:
174
+ await stream.next_event()
175
+ statement = date_statement(1, params=[when])
176
+ assert (await post_frame(client, cmd_frame(statement))).status_code == 200
177
+ res = await next_verdict(stream)
178
+ assert res["type"] == "rejected"
179
+ assert res["code"] == "invalid-params"
180
+ async with stream_of(app, client_id="c2") as stream:
181
+ env = await stream.next_event()
182
+ [op] = env["ops"]
183
+ assert op["value"]["events"] == []
184
+
185
+
168
186
  async def test_reject_payload_carries_meta():
169
187
  async with statewire_client(Timed) as (app, client):
170
188
  async with stream_of(app) as stream:
@@ -438,8 +438,9 @@ class Counter(Statewire):
438
438
  async def test_the_attach_fence_waits_for_a_reattached_lease_still_admitting(
439
439
  monkeypatch,
440
440
  ):
441
- gate, entered = asyncio.Event(), asyncio.Event()
441
+ gate, entered, fenced = asyncio.Event(), asyncio.Event(), asyncio.Event()
442
442
  original = api.Statewire._admit_frame_once
443
+ retire = api.Statewire._retire_lease
443
444
 
444
445
  async def held(self, client, frame, received, lease):
445
446
  if not gate.is_set():
@@ -447,7 +448,13 @@ async def test_the_attach_fence_waits_for_a_reattached_lease_still_admitting(
447
448
  await gate.wait()
448
449
  return await original(self, client, frame, received, lease)
449
450
 
451
+ async def retire_lease(self, lease):
452
+ if lease.admitting:
453
+ fenced.set()
454
+ return await retire(self, lease)
455
+
450
456
  monkeypatch.setattr(api.Statewire, "_admit_frame_once", held)
457
+ monkeypatch.setattr(api.Statewire, "_retire_lease", retire_lease)
451
458
  tab = {**FENCE, "Statewire-Attacher": "tab-1"}
452
459
  statement = {"protocol": "default", "method": "inc", "params": [], "seq": 1}
453
460
  async with statewire_client(Counter) as (app, client):
@@ -464,7 +471,9 @@ async def test_the_attach_fence_waits_for_a_reattached_lease_still_admitting(
464
471
  assert (await first.next_event())["fin"]["code"] == "reauthorize"
465
472
  second = attach_of(app, {"headers": {}}, headers=tab)
466
473
  entering = asyncio.create_task(second.__aenter__())
467
- await asyncio.sleep(0.05)
474
+ fence = asyncio.create_task(fenced.wait())
475
+ await asyncio.wait({entering, fence}, return_when=asyncio.FIRST_COMPLETED)
476
+ fence.cancel()
468
477
  assert not entering.done()
469
478
  gate.set()
470
479
  stream = await entering
@@ -69,6 +69,17 @@ def doc_of(rows):
69
69
  return only["doc"]
70
70
 
71
71
 
72
+ def untimed(doc):
73
+ """``doc`` without the admission and first-delivery times a 0.24 writer
74
+ adds; a 0.19.1 reader ignores and keeps both."""
75
+ doc = dict(doc)
76
+ stamps = doc.pop("admitted_at", {})
77
+ since = doc.pop("~since", 0.0)
78
+ assert all(isinstance(at, float) for at in stamps.values()), stamps
79
+ assert isinstance(since, float), since
80
+ return doc
81
+
82
+
72
83
  def answer(seq, **fields):
73
84
  return {**REJECTED, "seq": seq, **fields}
74
85
 
@@ -141,7 +152,8 @@ async def test_identity_records_attach_and_replay_under_their_identity(host_cls)
141
152
 
142
153
  async def test_list_mode_writes_0_19_pool_entries_plus_identity_fields():
143
154
  rows = await probe.generate(ListProbe, ["terminal", "pending"], hold={"pending"})
144
- assert doc_of(rows) == {
155
+ assert set(doc_of(rows)["admitted_at"]) == {"default:2"}
156
+ assert untimed(doc_of(rows)) == {
145
157
  "identity": IDENTITY,
146
158
  "identity_through": {"default": 2},
147
159
  "pool": [[statement(2, "pending")]],
@@ -152,7 +164,7 @@ async def test_list_mode_writes_0_19_pool_entries_plus_identity_fields():
152
164
 
153
165
  async def test_envelope_mode_writes_admission_envelopes():
154
166
  rows = await probe.generate(Probe, ["terminal", "pending"], hold={"pending"})
155
- assert doc_of(rows) == FIXTURES["0.20.0-pending"][0]["doc"]
167
+ assert untimed(doc_of(rows)) == FIXTURES["0.20.0-pending"][0]["doc"]
156
168
 
157
169
 
158
170
  @pytest.mark.parametrize("reader", [Probe, ListProbe])
@@ -375,7 +387,7 @@ async def test_statewire_0_19_reads_list_mode_output(legacy_python):
375
387
  {"label": "unproven", "auth": AUTH, "authorized": True},
376
388
  ]
377
389
  during = doc_of(report["rows_during"])
378
- assert during == {
390
+ assert untimed(during) == {
379
391
  "identity": IDENTITY,
380
392
  "identity_through": {"default": 2},
381
393
  "pool": [[statement(3, "unproven")]],
File without changes
File without changes
File without changes
File without changes