Skip to content

Commit 03573a9

Browse files
Honor shared HTTP pauses and repair release checks
1 parent 29aaab7 commit 03573a9

8 files changed

Lines changed: 70 additions & 39 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration.
5555
- Shared caches batch tag reads and recreate missing version tokens so deleting
5656
a tag key cannot revive an old entry.
5757
- HTTP policies honor a host's 429 pause without requiring a configured limiter.
58+
- Policies read a shared 429 pause before each attempt. Overlapping responses can extend
59+
the pause but cannot shorten it.
5860
- Failed transactional idempotent calls remove their own unfinished claim.
5961
- Rebuilding LangChain provider models drops the original SDK clients so their retries
6062
are disabled while preserving the API settings and HTTP transports.

‎RELEASING.md‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,10 @@ against the patch-release policy before tagging.
5757

5858
The default `pytest` run includes the `tests/e2e/` happy-path scenarios.
5959

60-
4. **Merge to `main`**, after the local checks pass. CI and docs run only on pushes
61-
to `main`, so PR updates do not start Actions runs. Wait for both workflows on the
62-
merged commit to pass before creating a release tag. The Redis integration job is
60+
4. **Merge to `main`**, after local checks and release-branch CI pass. Wait for CI and
61+
the docs workflow on the merged commit before creating a release tag. The Redis integration job is
6362
required for 0.3.0; the release workflow repeats its real-server gate before any
64-
upload, so a skipped local Redis run cannot approve a publication. If the repository requires
65-
PR status checks, a maintainer must align that rule with this post-merge policy;
66-
new PR commits will not receive CI/docs checks.
63+
upload, so a skipped local Redis run cannot approve a publication.
6764
5. **Rehearse (recommended for a big release).** Tag a pre-release such as `v0.3.0rc1`
6865
(after setting `__version__ = "0.3.0rc1"`). Every tagged version is published to
6966
TestPyPI and installed back from that index

‎docs/features/resilience/http-clients.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,9 +143,9 @@ mount_policy(session, policy)
143143
factories `name -> object` (a ready-made object is rejected so state is never shared by
144144
accident). `max_hosts` defaults to 1000 and bounds remembered host guards and pauses.
145145
An evicted host gets fresh local guards on its next request.
146-
- With `shared=` set to a Redis client, policies share 429 pauses and check Redis at
147-
most once per second per remembered host. A store failure leaves the local pause
148-
in effect. Use `limiter={"calls": 50, "period": 1}` and
146+
- With `shared=` set to a Redis client, policies check the shared 429 pause before
147+
each attempt. A shorter `Retry-After` cannot shorten a pause already in Redis. A
148+
store failure leaves the local pause in effect. Use `limiter={"calls": 50, "period": 1}` and
149149
`bulkhead={"max_concurrent": 8}` to build guards backed by the same Redis client.
150150
- `RetryTransport`, `AsyncRetryTransport` and `mount_retries` stay as thin retry-only wrappers.
151151

‎docs/llms-full.txt‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2153,8 +2153,10 @@ unless you run several chains and need to tell them apart.
21532153

21542154
### Testing
21552155

2156-
The adapter is tested against langchain-core's real `BaseChatModel`. Two 429 responses
2157-
followed by a success make three provider calls, and the budget is charged once.
2156+
Tests exercise the oldest supported `langchain-core` and the current provider integrations.
2157+
The `ChatOpenAI` and `ChatAnthropic` tests stub HTTP at the transport and verify that
2158+
rebuilding preserves credentials and the endpoint. Two 429 responses followed by a success
2159+
make three requests through a tool-bound model and charge the budget once.
21582160

21592161
---
21602162

@@ -4434,7 +4436,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm
44344436
- `python_wrap.WebhookAlerter`: `WebhookAlerter(url: str, *, format: str = 'json', on: Iterable[str | CircuitState] = ('open',), cooldown: float = 300.0, timeout: float = 5.0, sender: Sender | None = None, include_recovery: bool = True, context: Mapping[str, Any] | None = None)`
44354437
Post a chat message when a circuit breaker reaches a chosen state.
44364438
- `python_wrap.__version__`
4437-
Constant: '0.4.1'
4439+
Constant: '0.4.2'
44384440
- `python_wrap.ainvalidate_tags`: `ainvalidate_tags(*names: str, client: Any = None, require_shared: bool = False) -> int`
44394441
`invalidate_tags` for ``redis.asyncio`` clients (amemoize with AsyncRedisStore).
44404442
- `python_wrap.amap_iter`: `amap_iter(fn: Callable[[T], Awaitable[R]], items: Iterable[T] | AsyncIterable[T], *, limit: int, ordered: bool = True, return_exceptions: bool = False) -> AsyncGenerator[Any, None]`
@@ -4838,7 +4840,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm
48384840
- `python_wrap.decorators`
48394841
Compatibility module: v0.1 imported everything from ``python_wrap.decorators``.
48404842
- `python_wrap.decorators.__version__`
4841-
Constant: '0.4.1'
4843+
Constant: '0.4.2'
48424844
- `python_wrap.devtools`
48434845
Developer tools: deprecation warnings, mock data and decorator composition.
48444846
- `python_wrap.django`

‎scripts/smoke_wheel.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def ask(question):
9797
with fake_clock() as clock:
9898
assert fetch() == "ok" and len(calls) == 3
9999
assert ask("hello").text == "hi" and provider.call_count == 2
100-
assert clock.sleeps[-1] == 2.0
100+
assert 2.0 <= clock.sleeps[-1] <= 2.2
101101
print(f"smoke ok: python-wrap {version}")
102102
"""
103103
)

‎src/python_wrap/http.py‎

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
from python_wrap import _core, _fork
2828
from python_wrap._backend import BackendMonitor
2929
from python_wrap._runtime import name_digest
30+
from python_wrap._scripts import Script
3031
from python_wrap.deadline import remaining as _deadline_remaining
3132
from python_wrap.retry import RetryBudget, _compute_delay, http_status, retry, retry_after_header
3233
from python_wrap.shared import _async_redis_client
@@ -358,6 +359,16 @@ def _pause_key(host: str) -> str:
358359
return "python-wrap:http-pause:" + name_digest(host)
359360

360361

362+
_EXTEND_PAUSE = """
363+
local ttl = tonumber(ARGV[1])
364+
if redis.call('PTTL', KEYS[1]) < ttl then
365+
redis.call('SET', KEYS[1], '1', 'PX', ttl)
366+
end
367+
return 1
368+
"""
369+
_EXTEND_PAUSE_SCRIPT = Script(_EXTEND_PAUSE)
370+
371+
361372
@dataclass(frozen=True)
362373
class HttpPolicy:
363374
"""Retries plus a circuit breaker, rate limiter, bulkhead and timeouts for HTTP calls.
@@ -405,9 +416,6 @@ class HttpPolicy:
405416
_blocked: OrderedDict[str, float] = field(
406417
default_factory=OrderedDict, init=False, repr=False, compare=False
407418
)
408-
_pause_checks: OrderedDict[str, float] = field(
409-
default_factory=OrderedDict, init=False, repr=False, compare=False
410-
)
411419
_pause_monitor: BackendMonitor = field(
412420
default_factory=lambda: BackendMonitor("http", "pause", "allow", register=False),
413421
init=False,
@@ -528,18 +536,6 @@ def _pause_client(self) -> Any:
528536
shared = resolve_shared(self.shared)
529537
return None if shared is None else shared.client
530538

531-
def _should_read_pause(self, host: str) -> bool:
532-
now = _core.monotonic()
533-
with self._lock:
534-
previous = self._pause_checks.get(host)
535-
if previous is not None and now - previous < 1:
536-
return False
537-
self._pause_checks[host] = now
538-
self._pause_checks.move_to_end(host)
539-
if len(self._pause_checks) > self.max_hosts:
540-
self._pause_checks.popitem(last=False)
541-
return True
542-
543539
def _remember_pause(self, host: str, seconds: float) -> None:
544540
if seconds <= 0:
545541
return
@@ -552,7 +548,7 @@ def _remember_pause(self, host: str, seconds: float) -> None:
552548

553549
def _read_pause(self, host: str) -> None:
554550
client = self._pause_client()
555-
if client is not None and self._should_read_pause(host):
551+
if client is not None:
556552
millis = self._pause_monitor.call(
557553
"pttl", lambda: client.pttl(_pause_key(host)), lambda: 0
558554
)
@@ -564,7 +560,7 @@ async def _aread_pause(self, host: str) -> None:
564560
return
565561
if not _async_redis_client(client):
566562
await asyncio.to_thread(self._read_pause, host)
567-
elif self._should_read_pause(host):
563+
else:
568564
millis = await self._pause_monitor.acall(
569565
"pttl", lambda: client.pttl(_pause_key(host)), lambda: 0
570566
)
@@ -578,7 +574,9 @@ def _note(self, host: str, response: Any) -> None:
578574
if client is not None:
579575
self._pause_monitor.call(
580576
"set",
581-
lambda: client.set(_pause_key(host), "1", px=math.ceil(hinted * 1000)),
577+
lambda: _EXTEND_PAUSE_SCRIPT.run(
578+
client, 1, _pause_key(host), math.ceil(hinted * 1000)
579+
),
582580
lambda: None,
583581
)
584582

@@ -595,7 +593,9 @@ async def _anote(self, host: str, response: Any) -> None:
595593
self._remember_pause(host, hinted)
596594
await self._pause_monitor.acall(
597595
"set",
598-
lambda: client.set(_pause_key(host), "1", px=math.ceil(hinted * 1000)),
596+
lambda: _EXTEND_PAUSE_SCRIPT.arun(
597+
client, 1, _pause_key(host), math.ceil(hinted * 1000)
598+
),
599599
lambda: None,
600600
)
601601

‎tests/test_http_policy.py‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -151,16 +151,14 @@ def __init__(self) -> None:
151151
self.values: dict[str, int] = {}
152152
self.reads = 0
153153

154-
def eval(self, *args: Any) -> Any:
155-
pytest.fail("unexpected script")
154+
def eval(self, script: str, count: int, key: str, ttl: int) -> int:
155+
self.values[key] = max(ttl, self.values.get(key, 0))
156+
return 1
156157

157158
def pttl(self, key: str) -> int:
158159
self.reads += 1
159160
return self.values.get(key, -2)
160161

161-
def set(self, key: str, value: str, *, px: int) -> None:
162-
self.values[key] = px
163-
164162
client = Client()
165163
response = Resp(429)
166164
response.headers["Retry-After"] = "30"
@@ -170,4 +168,4 @@ def set(self, key: str, value: str, *, px: int) -> None:
170168
for _ in range(2):
171169
with pytest.raises(RateLimitExceeded):
172170
other.call("api.example", lambda: pytest.fail("request should pause"))
173-
assert client.reads == 2
171+
assert client.reads == 3

‎tests/test_redis_backends.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,38 @@ def price(sku):
456456
assert workers[3]("a1") == 2
457457

458458

459+
def test_redis_http_pause_is_visible_immediately_and_cannot_shorten(redis_client):
460+
from types import SimpleNamespace
461+
462+
from python_wrap.errors import RateLimitExceeded
463+
from python_wrap.http import _EXTEND_PAUSE, HttpPolicy, HttpRetryPolicy
464+
465+
class PauseClient(ShaClient):
466+
def pttl(self, key):
467+
return self.execute("PTTL", key)
468+
469+
host = "pause.example"
470+
retry = HttpRetryPolicy(max_retry_after=5)
471+
first, second, peer = [
472+
HttpPolicy(shared=PauseClient(redis_client.path), retry=retry) for _ in range(3)
473+
]
474+
475+
def request_while_first_sets_pause():
476+
first.call(host, lambda: SimpleNamespace(status_code=429, headers={"Retry-After": "30"}))
477+
return SimpleNamespace(status_code=429, headers={"Retry-After": "1"})
478+
479+
def send():
480+
return SimpleNamespace(status_code=200, headers={})
481+
482+
assert peer.call(host, send).status_code == 200
483+
assert second.call(host, request_while_first_sets_pause).status_code == 429
484+
assert peer.shared.loaded(Script(_EXTEND_PAUSE))
485+
with pytest.raises(RateLimitExceeded) as rejected:
486+
peer.call(host, lambda: pytest.fail("the shared pause should prevent this request"))
487+
assert rejected.value.retry_after > 5
488+
assert peer.call("other.example", send).status_code == 200
489+
490+
459491
def test_redis_half_open_rejection_has_positive_wait(redis_client):
460492
"""A caller rejected while the single trial slot is in use must not get a zero wait."""
461493
breaker = CircuitBreaker(

0 commit comments

Comments
 (0)