replyonce 0.1.2__tar.gz → 0.2.0__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.
- replyonce-0.2.0/AGENTS.md +12 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/PKG-INFO +7 -6
- {replyonce-0.1.2 → replyonce-0.2.0}/README.md +2 -2
- {replyonce-0.1.2 → replyonce-0.2.0}/pyproject.toml +5 -4
- {replyonce-0.1.2 → replyonce-0.2.0}/src/replyonce/__init__.py +1 -1
- replyonce-0.2.0/src/replyonce/_key.py +167 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/src/replyonce/demo.py +76 -12
- replyonce-0.2.0/tests/test_demo.py +35 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/tests/test_key.py +19 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/uv.lock +1 -1
- replyonce-0.1.2/src/replyonce/_key.py +0 -89
- {replyonce-0.1.2 → replyonce-0.2.0}/.gitignore +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/LICENSE +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/NOTICE +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/scripts/interop.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/src/replyonce/__main__.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/src/replyonce/_core.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/src/replyonce/_logic.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/src/replyonce/adapters.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/src/replyonce/cli.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/src/replyonce/py.typed +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/src/replyonce/stores/__init__.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/src/replyonce/stores/memory.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/src/replyonce/stores/postgres.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/src/replyonce/stores/redis.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/tests/__init__.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/tests/conftest.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/tests/test_adapters.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/tests/test_migrate.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/tests/test_once.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/tests/test_race.py +0 -0
- {replyonce-0.1.2 → replyonce-0.2.0}/tests/test_runs.py +0 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# python
|
|
2
|
+
|
|
3
|
+
The root `AGENTS.md` applies.
|
|
4
|
+
|
|
5
|
+
Async port of the same state machine and state format, so a Node worker and
|
|
6
|
+
a Python worker can share one store. Dependencies live in the image via
|
|
7
|
+
`uv sync --frozen`. Run `docker compose run --build --rm python`. Do not
|
|
8
|
+
create `.venv` here.
|
|
9
|
+
|
|
10
|
+
## Root contract
|
|
11
|
+
|
|
12
|
+
This file narrows the root `AGENTS.md`; the root file still applies. Repository-wide commands, safety rules and the definition of done live there.
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: replyonce
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Stop your agent from replying, refunding or ticketing twice. Idempotency keys, per-conversation write fencing and an effect ledger for tool-calling agents, webhooks and workers.
|
|
5
|
-
Project-URL: Homepage, https://github.com/shmindmaster/replyonce
|
|
6
|
-
Project-URL: Source, https://github.com/shmindmaster/
|
|
7
|
-
Project-URL: Issues, https://github.com/shmindmaster/
|
|
5
|
+
Project-URL: Homepage, https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce#readme
|
|
6
|
+
Project-URL: Source, https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce/python
|
|
7
|
+
Project-URL: Issues, https://github.com/shmindmaster/fakeplane/issues
|
|
8
|
+
Project-URL: Author, https://saroshhussain.com
|
|
8
9
|
Author: Sarosh Hussain
|
|
9
10
|
License-Expression: Apache-2.0
|
|
10
11
|
License-File: LICENSE
|
|
@@ -29,10 +30,10 @@ Description-Content-Type: text/markdown
|
|
|
29
30
|
|
|
30
31
|
**Stop your agent from replying, refunding or ticketing twice.**
|
|
31
32
|
|
|
32
|
-
The Python port of [replyonce](https://github.com/shmindmaster/replyonce). It uses the same
|
|
33
|
+
The Python port of [replyonce](https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce). It uses the same
|
|
33
34
|
state machine and stores the same JSON state as the TypeScript package, so Python and
|
|
34
35
|
Node workers can share one Postgres table or Redis prefix. The full guide, design notes,
|
|
35
|
-
guarantees and limits are in the [main README](https://github.com/shmindmaster/replyonce#readme).
|
|
36
|
+
guarantees and limits are in the [main README](https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce#readme).
|
|
36
37
|
|
|
37
38
|
```sh
|
|
38
39
|
pip install replyonce # memory store
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
**Stop your agent from replying, refunding or ticketing twice.**
|
|
4
4
|
|
|
5
|
-
The Python port of [replyonce](https://github.com/shmindmaster/replyonce). It uses the same
|
|
5
|
+
The Python port of [replyonce](https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce). It uses the same
|
|
6
6
|
state machine and stores the same JSON state as the TypeScript package, so Python and
|
|
7
7
|
Node workers can share one Postgres table or Redis prefix. The full guide, design notes,
|
|
8
|
-
guarantees and limits are in the [main README](https://github.com/shmindmaster/replyonce#readme).
|
|
8
|
+
guarantees and limits are in the [main README](https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce#readme).
|
|
9
9
|
|
|
10
10
|
```sh
|
|
11
11
|
pip install replyonce # memory store
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "replyonce"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.2.0"
|
|
8
8
|
description = "Stop your agent from replying, refunding or ticketing twice. Idempotency keys, per-conversation write fencing and an effect ledger for tool-calling agents, webhooks and workers."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "Apache-2.0"
|
|
@@ -28,9 +28,10 @@ postgres = ["psycopg[binary]>=3.1", "psycopg-pool>=3.2"]
|
|
|
28
28
|
redis = ["redis>=5.0"]
|
|
29
29
|
|
|
30
30
|
[project.urls]
|
|
31
|
-
Homepage = "https://github.com/shmindmaster/replyonce"
|
|
32
|
-
Source = "https://github.com/shmindmaster/
|
|
33
|
-
Issues = "https://github.com/shmindmaster/
|
|
31
|
+
Homepage = "https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce#readme"
|
|
32
|
+
Source = "https://github.com/shmindmaster/fakeplane/tree/main/packages/replyonce/python"
|
|
33
|
+
Issues = "https://github.com/shmindmaster/fakeplane/issues"
|
|
34
|
+
Author = "https://saroshhussain.com"
|
|
34
35
|
|
|
35
36
|
[project.scripts]
|
|
36
37
|
replyonce = "replyonce.cli:main"
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Keys and canonical hashing, byte-compatible with the TypeScript package."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import datetime as _dt
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import re
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
MISSING: Any = object()
|
|
14
|
+
"""Sentinel for "no payload" (distinct from a ``None`` payload, which hashes as JSON null)."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class _RawNumber:
|
|
18
|
+
"""A number whose ECMAScript text form must be emitted without JSON quoting."""
|
|
19
|
+
|
|
20
|
+
__slots__ = ("text",)
|
|
21
|
+
|
|
22
|
+
def __init__(self, text: str) -> None:
|
|
23
|
+
self.text = text
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _sort_key(k: str) -> bytes:
|
|
27
|
+
# JavaScript sorts object keys by UTF-16 code units.
|
|
28
|
+
return k.encode("utf-16-be")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _iso(value: _dt.datetime) -> str:
|
|
32
|
+
if value.tzinfo is None:
|
|
33
|
+
value = value.replace(tzinfo=_dt.timezone.utc)
|
|
34
|
+
value = value.astimezone(_dt.timezone.utc)
|
|
35
|
+
return value.strftime("%Y-%m-%dT%H:%M:%S.") + f"{value.microsecond // 1000:03d}Z"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _js_number(value: float) -> str:
|
|
39
|
+
"""Render a float the way ECMAScript Number::toString does.
|
|
40
|
+
|
|
41
|
+
Python's repr uses different thresholds and pads exponents (``1e-07``,
|
|
42
|
+
``1e-06``), while JSON.stringify emits ``1e-7``, ``0.000001`` and switches
|
|
43
|
+
to exponent notation only at 1e21. Keys must be byte-identical across the
|
|
44
|
+
Python and TypeScript packages or the two runtimes cannot share a ledger.
|
|
45
|
+
"""
|
|
46
|
+
if value == 0:
|
|
47
|
+
return "0" # includes -0.0, which JSON.stringify renders as 0
|
|
48
|
+
negative = value < 0
|
|
49
|
+
text = repr(abs(value)) # shortest round-trip digits
|
|
50
|
+
if "e" in text:
|
|
51
|
+
mantissa, exponent_text = text.split("e")
|
|
52
|
+
exponent = int(exponent_text)
|
|
53
|
+
else:
|
|
54
|
+
mantissa, exponent = text, 0
|
|
55
|
+
integer_part, _, fraction_part = mantissa.partition(".")
|
|
56
|
+
digits = integer_part + fraction_part
|
|
57
|
+
point = len(integer_part) + exponent
|
|
58
|
+
leading = len(digits) - len(digits.lstrip("0"))
|
|
59
|
+
digits = digits.lstrip("0")
|
|
60
|
+
point -= leading
|
|
61
|
+
digits = digits.rstrip("0") or "0"
|
|
62
|
+
k = len(digits)
|
|
63
|
+
n = point
|
|
64
|
+
if k <= n <= 21:
|
|
65
|
+
body = digits + "0" * (n - k)
|
|
66
|
+
elif 0 < n <= 21:
|
|
67
|
+
body = digits[:n] + "." + digits[n:]
|
|
68
|
+
elif -6 < n <= 0:
|
|
69
|
+
body = "0." + "0" * (-n) + digits
|
|
70
|
+
else:
|
|
71
|
+
exp = n - 1
|
|
72
|
+
sign = "+" if exp >= 0 else "-"
|
|
73
|
+
body = digits[0] + ("." + digits[1:] if k > 1 else "") + "e" + sign + str(abs(exp))
|
|
74
|
+
return "-" + body if negative else body
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _normalize(value: Any, seen: set[int]) -> Any:
|
|
78
|
+
if value is None or isinstance(value, (bool, str)):
|
|
79
|
+
return value
|
|
80
|
+
if isinstance(value, int):
|
|
81
|
+
# JSON.parse in JS produces a double for every number token; Python
|
|
82
|
+
# keeps an int. Above 2**53 the two runtimes must agree on the JS
|
|
83
|
+
# shortest round-trip form or one payload gets two ledger keys.
|
|
84
|
+
if abs(value) <= 2**53:
|
|
85
|
+
return value
|
|
86
|
+
return _RawNumber(_js_number(float(value)))
|
|
87
|
+
if isinstance(value, float):
|
|
88
|
+
if math.isnan(value):
|
|
89
|
+
return "NaN"
|
|
90
|
+
if math.isinf(value):
|
|
91
|
+
return "Infinity" if value > 0 else "-Infinity"
|
|
92
|
+
# Even integral doubles must use the JS shortest round-trip form:
|
|
93
|
+
# int(2**60) is 1152921504606846976 in Python but JSON.stringify
|
|
94
|
+
# emits 1152921504606847000. _js_number handles both forms.
|
|
95
|
+
return _RawNumber(_js_number(value))
|
|
96
|
+
if isinstance(value, _dt.datetime):
|
|
97
|
+
return _iso(value)
|
|
98
|
+
if isinstance(value, _dt.date):
|
|
99
|
+
return _iso(_dt.datetime(value.year, value.month, value.day, tzinfo=_dt.timezone.utc))
|
|
100
|
+
if dataclasses.is_dataclass(value) and not isinstance(value, type):
|
|
101
|
+
value = dataclasses.asdict(value)
|
|
102
|
+
elif hasattr(value, "model_dump") and callable(value.model_dump):
|
|
103
|
+
value = value.model_dump()
|
|
104
|
+
if id(value) in seen:
|
|
105
|
+
raise TypeError("replyonce: cannot hash a circular payload")
|
|
106
|
+
if isinstance(value, (list, tuple)):
|
|
107
|
+
seen.add(id(value))
|
|
108
|
+
out = [_normalize(v, seen) for v in value]
|
|
109
|
+
seen.discard(id(value))
|
|
110
|
+
return out
|
|
111
|
+
if isinstance(value, dict):
|
|
112
|
+
seen.add(id(value))
|
|
113
|
+
items = sorted(((str(k), v) for k, v in value.items()), key=lambda kv: _sort_key(kv[0]))
|
|
114
|
+
obj = {k: _normalize(v, seen) for k, v in items}
|
|
115
|
+
seen.discard(id(value))
|
|
116
|
+
return obj
|
|
117
|
+
raise TypeError(f"replyonce: cannot hash a payload of type {type(value).__name__}")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _encode(value: Any) -> str:
|
|
121
|
+
if value is None:
|
|
122
|
+
return "null"
|
|
123
|
+
if value is True:
|
|
124
|
+
return "true"
|
|
125
|
+
if value is False:
|
|
126
|
+
return "false"
|
|
127
|
+
if isinstance(value, str):
|
|
128
|
+
return json.dumps(value, ensure_ascii=False)
|
|
129
|
+
if isinstance(value, int):
|
|
130
|
+
return int.__repr__(value) # IntEnum str() is "Class.MEMBER" on Python 3.10
|
|
131
|
+
if isinstance(value, _RawNumber):
|
|
132
|
+
return value.text
|
|
133
|
+
if isinstance(value, list):
|
|
134
|
+
return "[" + ",".join(_encode(item) for item in value) + "]"
|
|
135
|
+
if isinstance(value, dict):
|
|
136
|
+
return "{" + ",".join(
|
|
137
|
+
json.dumps(k, ensure_ascii=False) + ":" + _encode(v) for k, v in value.items()
|
|
138
|
+
) + "}"
|
|
139
|
+
raise TypeError(f"replyonce: cannot hash a payload of type {type(value).__name__}")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def canonical_json(value: Any) -> str:
|
|
143
|
+
"""Deterministic JSON: keys sorted, no whitespace. Matches the TypeScript ``canonicalJson``."""
|
|
144
|
+
return _encode(_normalize(value, set()))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def sha256_hex(text: str) -> str:
|
|
148
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def hash_payload(payload: Any) -> str:
|
|
152
|
+
return sha256_hex(canonical_json(payload))[:32]
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
_SAFE_INTENT = re.compile(r"^[A-Za-z0-9_.:-]{1,100}$")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def effect_key(intent: str, payload: Any = MISSING) -> str:
|
|
159
|
+
"""Ledger key for an intent plus the business identity of the payload."""
|
|
160
|
+
if not isinstance(intent, str) or not _SAFE_INTENT.match(intent):
|
|
161
|
+
raise TypeError(f"replyonce: intent must match {_SAFE_INTENT.pattern} (got {intent!r})")
|
|
162
|
+
return intent if payload is MISSING else f"{intent}:{hash_payload(payload)}"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def provider_idempotency_key(scope: str, key: str) -> str:
|
|
166
|
+
"""Stable idempotency key to hand to a provider (Stripe-style ``Idempotency-Key``)."""
|
|
167
|
+
return "ro_" + sha256_hex(f"{scope}\u0000{key}")[:40]
|
|
@@ -3,11 +3,12 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
|
+
import heapq
|
|
6
7
|
import random
|
|
7
8
|
import time
|
|
8
9
|
import uuid
|
|
9
10
|
from dataclasses import dataclass, field
|
|
10
|
-
from typing import Optional
|
|
11
|
+
from typing import Callable, Optional
|
|
11
12
|
|
|
12
13
|
from ._core import ReplyOnce
|
|
13
14
|
from ._key import provider_idempotency_key
|
|
@@ -28,9 +29,57 @@ class Stats:
|
|
|
28
29
|
faults: dict = field(default_factory=dict)
|
|
29
30
|
|
|
30
31
|
|
|
32
|
+
def _wall_ms() -> int:
|
|
33
|
+
return int(time.time() * 1000)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# Simulated runs report times from 2026-01-01T00:00:00Z.
|
|
37
|
+
_SIM_EPOCH_MS = 1_767_225_600_000
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _loop_ms() -> int:
|
|
41
|
+
return _SIM_EPOCH_MS + int(asyncio.get_running_loop().time() * 1000)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class _SimulatedLoop(asyncio.SelectorEventLoop):
|
|
45
|
+
"""Event loop on simulated time: whenever nothing is ready, time jumps to the next timer.
|
|
46
|
+
|
|
47
|
+
With the in-memory store nothing else can wake the loop, so a seed always replays the same
|
|
48
|
+
run, and no real time passes. Steps through CPython's ``BaseEventLoop._run_once``.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(self) -> None:
|
|
52
|
+
super().__init__()
|
|
53
|
+
# Starts at zero: at epoch-sized values a float cannot hold the loop's clock resolution,
|
|
54
|
+
# so a timer due now would never count as ready.
|
|
55
|
+
self._sim_now = 0.0
|
|
56
|
+
|
|
57
|
+
def time(self) -> float:
|
|
58
|
+
return self._sim_now
|
|
59
|
+
|
|
60
|
+
def _run_once(self) -> None:
|
|
61
|
+
while self._scheduled and self._scheduled[0]._cancelled:
|
|
62
|
+
self._timer_cancelled_count -= 1
|
|
63
|
+
heapq.heappop(self._scheduled)._scheduled = False
|
|
64
|
+
if not self._ready and not self._stopping:
|
|
65
|
+
if not self._scheduled:
|
|
66
|
+
raise RuntimeError("replyonce demo: the simulation stalled")
|
|
67
|
+
self._sim_now = max(self._sim_now, self._scheduled[0]._when)
|
|
68
|
+
super()._run_once()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _run_simulated(make_coro):
|
|
72
|
+
loop = _SimulatedLoop()
|
|
73
|
+
try:
|
|
74
|
+
return loop.run_until_complete(make_coro())
|
|
75
|
+
finally:
|
|
76
|
+
loop.close()
|
|
77
|
+
|
|
78
|
+
|
|
31
79
|
@dataclass
|
|
32
80
|
class _World:
|
|
33
81
|
rand: random.Random
|
|
82
|
+
now_ms: Callable[[], int] = _wall_ms
|
|
34
83
|
inbound: dict = field(default_factory=dict)
|
|
35
84
|
sent: list = field(default_factory=list)
|
|
36
85
|
faults: dict = field(default_factory=dict)
|
|
@@ -91,7 +140,7 @@ def _guarded(w: _World, store) -> object:
|
|
|
91
140
|
if e["type"] == "late_settle":
|
|
92
141
|
w.bump("lateSettle")
|
|
93
142
|
|
|
94
|
-
ro = ReplyOnce(store, pending_ttl_ms=2_000, max_attempts=6, lease_ttl_ms=5_000, reconcile=reconcile, on_event=on_event)
|
|
143
|
+
ro = ReplyOnce(store, pending_ttl_ms=2_000, max_attempts=6, lease_ttl_ms=5_000, reconcile=reconcile, on_event=on_event, clock=w.now_ms)
|
|
95
144
|
|
|
96
145
|
async def agent(job: dict, crash: bool) -> None:
|
|
97
146
|
await _sleep_ms(2 + w.rand.random() * 10)
|
|
@@ -99,8 +148,8 @@ def _guarded(w: _World, store) -> object:
|
|
|
99
148
|
if not run.can_write:
|
|
100
149
|
return
|
|
101
150
|
inbound, done = job["inbound"], job["answered"]
|
|
102
|
-
give_up_at =
|
|
103
|
-
while
|
|
151
|
+
give_up_at = w.now_ms() + 15_000
|
|
152
|
+
while w.now_ms() < give_up_at:
|
|
104
153
|
todo = [m for m in inbound if m not in done]
|
|
105
154
|
if not todo:
|
|
106
155
|
break
|
|
@@ -127,13 +176,14 @@ def _guarded(w: _World, store) -> object:
|
|
|
127
176
|
return agent
|
|
128
177
|
|
|
129
178
|
|
|
130
|
-
async def _simulate(conversations: int, seed: int, make_agent) -> Stats:
|
|
131
|
-
w = _World(random.Random(seed))
|
|
179
|
+
async def _simulate(conversations: int, seed: int, make_agent, real_time: bool = True) -> Stats:
|
|
180
|
+
w = _World(random.Random(seed), now_ms=_wall_ms if real_time else _loop_ms)
|
|
132
181
|
agent = make_agent(w)
|
|
133
182
|
tasks: list = []
|
|
134
183
|
crashed: list = []
|
|
135
184
|
seq = 0
|
|
136
|
-
|
|
185
|
+
# Shared stores outlive a run, so real-time runs keep their conversations apart.
|
|
186
|
+
ns = uuid.uuid4().hex[:8] if real_time else f"seed{seed}"
|
|
137
187
|
|
|
138
188
|
def deliver(job: dict) -> None:
|
|
139
189
|
r = w.rand.random()
|
|
@@ -166,7 +216,7 @@ async def _simulate(conversations: int, seed: int, make_agent) -> Stats:
|
|
|
166
216
|
"conv": conv,
|
|
167
217
|
"inbound": list(w.inbound[conv]),
|
|
168
218
|
"answered": w.answered(conv),
|
|
169
|
-
"contextAt":
|
|
219
|
+
"contextAt": w.now_ms(),
|
|
170
220
|
})
|
|
171
221
|
|
|
172
222
|
for i in range(conversations):
|
|
@@ -200,11 +250,25 @@ async def _simulate(conversations: int, seed: int, make_agent) -> Stats:
|
|
|
200
250
|
return Stats(conversations, msgs, len(w.sent), dup, unanswered, w.faults)
|
|
201
251
|
|
|
202
252
|
|
|
203
|
-
async def run_demo(conversations: int = 100, seed: int = 7, store=None) -> tuple[Stats, Stats]:
|
|
204
|
-
|
|
253
|
+
async def run_demo(conversations: int = 100, seed: int = 7, store=None, real_time: Optional[bool] = None) -> tuple[Stats, Stats]:
|
|
254
|
+
"""Run the simulation without and with replyonce.
|
|
255
|
+
|
|
256
|
+
Simulated time (the default without a ``store``) makes every count a function of the seed;
|
|
257
|
+
real time (the default with a ``store``, since shared stores do real I/O) explores timing a
|
|
258
|
+
single seed cannot.
|
|
259
|
+
"""
|
|
260
|
+
real = store is not None if real_time is None else real_time
|
|
205
261
|
st = store if store is not None else MemoryStore()
|
|
206
|
-
|
|
207
|
-
|
|
262
|
+
|
|
263
|
+
async def both() -> tuple[Stats, Stats]:
|
|
264
|
+
without = await _simulate(conversations, seed, _naive, real)
|
|
265
|
+
guarded = await _simulate(conversations, seed, lambda w: _guarded(w, st), real)
|
|
266
|
+
return without, guarded
|
|
267
|
+
|
|
268
|
+
if real:
|
|
269
|
+
return await both()
|
|
270
|
+
# The simulated loop needs a thread of its own: this coroutine already runs on a real loop.
|
|
271
|
+
return await asyncio.to_thread(_run_simulated, both)
|
|
208
272
|
|
|
209
273
|
|
|
210
274
|
def format_report(without: Stats, with_: Stats) -> str:
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import subprocess
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
from replyonce.demo import format_report, run_demo
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_same_seed_gives_the_same_counts():
|
|
9
|
+
for seed in (1, 7, 42):
|
|
10
|
+
first = asyncio.run(run_demo(conversations=150, seed=seed))
|
|
11
|
+
second = asyncio.run(run_demo(conversations=150, seed=seed))
|
|
12
|
+
assert first == second
|
|
13
|
+
without, with_ = first
|
|
14
|
+
assert without.duplicate_answers > 0
|
|
15
|
+
assert with_.duplicate_answers == 0
|
|
16
|
+
assert with_.unanswered == 0
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_different_seeds_give_different_runs():
|
|
20
|
+
a, _ = asyncio.run(run_demo(conversations=150, seed=1))
|
|
21
|
+
b, _ = asyncio.run(run_demo(conversations=150, seed=2))
|
|
22
|
+
assert a.faults != b.faults
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_cli_prints_the_same_report_in_separate_processes():
|
|
26
|
+
cmd = [sys.executable, "-m", "replyonce.cli", "demo", "--conversations", "80", "--seed", "11"]
|
|
27
|
+
first = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
|
28
|
+
second = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
|
29
|
+
assert first.stdout == second.stdout
|
|
30
|
+
assert "No customer message was answered twice" in first.stdout
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_report_shape_is_unchanged():
|
|
34
|
+
without, with_ = asyncio.run(run_demo(conversations=20, seed=3))
|
|
35
|
+
assert format_report(without, with_).splitlines()[0] == "replyonce demo: 20 simulated support conversations under injected faults"
|
|
@@ -21,6 +21,20 @@ VECTORS = [
|
|
|
21
21
|
"x:578a211449377e723fbdd7fbf2dbb389",
|
|
22
22
|
),
|
|
23
23
|
("x", None, "null", "x:74234e98afe7498fb5daf1f36ac2d78a"),
|
|
24
|
+
# ECMAScript Number::toString thresholds and exponent formatting.
|
|
25
|
+
("x", {"n": 1e-7}, '{"n":1e-7}', "x:747d6d23b64d1b2d579adb832b44de31"),
|
|
26
|
+
("x", {"n": 1.5e-7}, '{"n":1.5e-7}', "x:ca0289a96d48abcb7088cf5581aadc70"),
|
|
27
|
+
("x", {"n": 1e-6}, '{"n":0.000001}', "x:28343867a0be00aee19f81aa90cfd6c6"),
|
|
28
|
+
("x", {"n": 1e-5}, '{"n":0.00001}', "x:694af9772b95df9403774a048bc7b0d7"),
|
|
29
|
+
("x", {"n": 1e20}, '{"n":100000000000000000000}', "x:58d2d5b8dd4228ab5775ce84f996718f"),
|
|
30
|
+
("x", {"n": 1e21}, '{"n":1e+21}', "x:f1ee2b60ee95a3170fdc07a577e5f351"),
|
|
31
|
+
("x", {"n": -1e21}, '{"n":-1e+21}', "x:fd33685f4e2a11dbebb3fd9717ea6449"),
|
|
32
|
+
("x", {"n": 0.0001}, '{"n":0.0001}', "x:eb596b9a807e0fbf971473088cea777f"),
|
|
33
|
+
("x", {"n": 1.2345678901234567e-8}, '{"n":1.2345678901234567e-8}', "x:74e069581ed661b8a161c255ae0fac95"),
|
|
34
|
+
("x", {"n": 1e-300}, '{"n":1e-300}', "x:8261d4fe2fd3eeb3dbea954ff257a6bc"),
|
|
35
|
+
("x", {"n": 2.0**60}, '{"n":1152921504606847000}', "x:730c537ef7e20d832661f6619b9b9be4"),
|
|
36
|
+
("x", {"n": 1000000000000000100.0}, '{"n":1000000000000000100}', "x:135ffdd59049a5e11240ffb79e442f05"),
|
|
37
|
+
("x", {"n": 10**21}, '{"n":1e+21}', "x:f1ee2b60ee95a3170fdc07a577e5f351"),
|
|
24
38
|
]
|
|
25
39
|
|
|
26
40
|
|
|
@@ -36,6 +50,11 @@ def test_no_payload_and_provider_key_match_typescript():
|
|
|
36
50
|
assert provider_idempotency_key("conv-1", "refund:abc") == "ro_1387614e87a828dd8b7faf70276f1dce87f7ee1d"
|
|
37
51
|
|
|
38
52
|
|
|
53
|
+
def test_boolean_values_remain_json_literals():
|
|
54
|
+
assert canonical_json(True) == "true"
|
|
55
|
+
assert canonical_json(False) == "false"
|
|
56
|
+
|
|
57
|
+
|
|
39
58
|
def test_key_order_does_not_matter():
|
|
40
59
|
assert hash_payload({"a": 1, "b": 2}) == hash_payload({"b": 2, "a": 1})
|
|
41
60
|
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
"""Keys and canonical hashing, byte-compatible with the TypeScript package."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import dataclasses
|
|
6
|
-
import datetime as _dt
|
|
7
|
-
import hashlib
|
|
8
|
-
import json
|
|
9
|
-
import math
|
|
10
|
-
import re
|
|
11
|
-
from typing import Any
|
|
12
|
-
|
|
13
|
-
MISSING: Any = object()
|
|
14
|
-
"""Sentinel for "no payload" (distinct from a ``None`` payload, which hashes as JSON null)."""
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
def _sort_key(k: str) -> bytes:
|
|
18
|
-
# JavaScript sorts object keys by UTF-16 code units.
|
|
19
|
-
return k.encode("utf-16-be")
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
def _iso(value: _dt.datetime) -> str:
|
|
23
|
-
if value.tzinfo is None:
|
|
24
|
-
value = value.replace(tzinfo=_dt.timezone.utc)
|
|
25
|
-
value = value.astimezone(_dt.timezone.utc)
|
|
26
|
-
return value.strftime("%Y-%m-%dT%H:%M:%S.") + f"{value.microsecond // 1000:03d}Z"
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def _normalize(value: Any, seen: set[int]) -> Any:
|
|
30
|
-
if value is None or isinstance(value, (bool, str)):
|
|
31
|
-
return value
|
|
32
|
-
if isinstance(value, int):
|
|
33
|
-
return value
|
|
34
|
-
if isinstance(value, float):
|
|
35
|
-
if math.isnan(value):
|
|
36
|
-
return "NaN"
|
|
37
|
-
if math.isinf(value):
|
|
38
|
-
return "Infinity" if value > 0 else "-Infinity"
|
|
39
|
-
return int(value) if value.is_integer() else value
|
|
40
|
-
if isinstance(value, _dt.datetime):
|
|
41
|
-
return _iso(value)
|
|
42
|
-
if isinstance(value, _dt.date):
|
|
43
|
-
return _iso(_dt.datetime(value.year, value.month, value.day, tzinfo=_dt.timezone.utc))
|
|
44
|
-
if dataclasses.is_dataclass(value) and not isinstance(value, type):
|
|
45
|
-
value = dataclasses.asdict(value)
|
|
46
|
-
elif hasattr(value, "model_dump") and callable(value.model_dump):
|
|
47
|
-
value = value.model_dump()
|
|
48
|
-
if id(value) in seen:
|
|
49
|
-
raise TypeError("replyonce: cannot hash a circular payload")
|
|
50
|
-
if isinstance(value, (list, tuple)):
|
|
51
|
-
seen.add(id(value))
|
|
52
|
-
out = [_normalize(v, seen) for v in value]
|
|
53
|
-
seen.discard(id(value))
|
|
54
|
-
return out
|
|
55
|
-
if isinstance(value, dict):
|
|
56
|
-
seen.add(id(value))
|
|
57
|
-
items = sorted(((str(k), v) for k, v in value.items()), key=lambda kv: _sort_key(kv[0]))
|
|
58
|
-
obj = {k: _normalize(v, seen) for k, v in items}
|
|
59
|
-
seen.discard(id(value))
|
|
60
|
-
return obj
|
|
61
|
-
raise TypeError(f"replyonce: cannot hash a payload of type {type(value).__name__}")
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
def canonical_json(value: Any) -> str:
|
|
65
|
-
"""Deterministic JSON: keys sorted, no whitespace. Matches the TypeScript ``canonicalJson``."""
|
|
66
|
-
return json.dumps(_normalize(value, set()), separators=(",", ":"), ensure_ascii=False, sort_keys=False)
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
def sha256_hex(text: str) -> str:
|
|
70
|
-
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
def hash_payload(payload: Any) -> str:
|
|
74
|
-
return sha256_hex(canonical_json(payload))[:32]
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
_SAFE_INTENT = re.compile(r"^[A-Za-z0-9_.:-]{1,100}$")
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
def effect_key(intent: str, payload: Any = MISSING) -> str:
|
|
81
|
-
"""Ledger key for an intent plus the business identity of the payload."""
|
|
82
|
-
if not isinstance(intent, str) or not _SAFE_INTENT.match(intent):
|
|
83
|
-
raise TypeError(f"replyonce: intent must match {_SAFE_INTENT.pattern} (got {intent!r})")
|
|
84
|
-
return intent if payload is MISSING else f"{intent}:{hash_payload(payload)}"
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
def provider_idempotency_key(scope: str, key: str) -> str:
|
|
88
|
-
"""Stable idempotency key to hand to a provider (Stripe-style ``Idempotency-Key``)."""
|
|
89
|
-
return "ro_" + sha256_hex(f"{scope}\u0000{key}")[:40]
|
|
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
|