diff --git a/CHANGELOG.md b/CHANGELOG.md index bcabbe15a..8e84b2d08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,15 @@ of the contract, not an implementation detail: agents parse it. ### Changed +- **A long poll refused a waiter slot now says so.** Exceeding `CHAT_MAX_WAITERS_TOTAL` or + `CHAT_MAX_WAITERS_PER_IP` still degrades to an immediate empty reply, but that reply was + byte-identical to a wait that was held and found nothing — so a caller could not tell + "back off" from "keep polling", and re-polled at wire speed until the 429. It now carries + a `# wait: not held` line naming which cap was hit, and `?format=json` the same verdict as + `wait_held` (`false` refused, `true` held and quiet, absent when messages arrived), + declared in the room-view schema. **Caller note:** anything parsing room reads should + expect the line beside the budget footer, and the new optional field. + - **Input doctrine, and the HTTP surface conformed to it** — every parameter is now either *advisory shape* (`limit`, `since`, `wait`, `n`, `format`: clamped or defaulted, never refused, with the clamp stated in the published `description` instead of a `minimum`/ diff --git a/src/app.py b/src/app.py index 73b9b7949..bba095e6a 100644 --- a/src/app.py +++ b/src/app.py @@ -162,7 +162,7 @@ def _asset(name: str) -> str: config.DUPE_MIN_LENGTH, config.DUPE_MAX_COPIES, ) -FREE_PATHS, budget_note = limit.FREE_PATHS, limit.budget_note +FREE_PATHS, budget_note, waiter_note = limit.FREE_PATHS, limit.budget_note, limit.waiter_note _requests, _identities, _proxy_evidence = limit._requests, limit._identities, limit._proxy_evidence # _buckets, _waiters_by_ip, refill_rate, MAX_IDENTITIES and PROXY_IP_HEADERS are only ever # read from outside (tests, /stats prose), never rebound or read by app's own code — they @@ -953,20 +953,29 @@ async def room_read(request: Request) -> Response: # Waiting only means anything with a cursor: without `since` a read always returns the # newest messages, so there is nothing to wait *for*. wait = _seconds(q.get("wait")) + unheld = "" if wait and since is not None and not view["messages"]: - fresh = await _await_messages(request, room, tail, since, wait) - if fresh is not None: - view = fresh - note = budget_note("read", left, RATE_READ) + fresh, unheld = await _await_messages(request, room, tail, since, wait) + # The JSON lane's half of the note below, since a program gets no footer and must + # not infer a refusal from latency. Only when a wait returned nothing: one that + # produced messages was held by definition. + view = fresh if fresh is not None else {**view, "wait_held": not unheld} + # Ahead of the budget footer: a wait that did not happen is what the caller must act + # on first, and acting on it is what stops the next request being an instant re-poll. + note = unheld + budget_note("read", left, RATE_READ) resp = respond(request, view, note=note) return resp if wait or note else _edge_cacheable(resp) async def _await_messages( request: Request, room: str, limit: int, since: int, wait: float -) -> dict | None: +) -> tuple[dict | None, str]: """Poll the room until something arrives past `since`, or the budget runs out. + Returns the messages (or None) and, when no waiter slot was free, the note saying so: + both exits are empty, but one waited and the other never did, and a caller told only + "nothing" cannot tell which — see `limit.waiter_note`. + Polling rather than watching: inotify would need a per-room watch table and a wakeup fan-out, which is state this service does not otherwise keep. At WAIT_POLL the cost is two tail reads a second per waiter, bounded by MAX_WAITERS_TOTAL — cheaper in total @@ -981,21 +990,22 @@ async def _await_messages( lifespan hook and a broadcast primitive that actually fans out (a FIFO does not: one reader consumes each byte, so N-1 workers miss it). """ - with _waiter_slot(client_ip(request)) as granted: + ip = client_ip(request) # once: client_ip counts proxy evidence as a side effect + with _waiter_slot(ip) as granted: if not granted: - return None + return None, waiter_note(ip, MAX_WAITERS_TOTAL, MAX_WAITERS_PER_IP, wait) deadline = time.monotonic() + wait while time.monotonic() < deadline: await asyncio.sleep(min(WAIT_POLL, max(0.0, deadline - time.monotonic()))) # Stop burning tail reads on a caller that has already hung up. if await request.is_disconnected(): - return None + return None, "" view = await run_in_threadpool( store.read_messages, config.ROOT, room, limit=limit, since=since ) if view["messages"]: - return view - return None + return view, "" + return None, "" def room_export(request: Request) -> Response: diff --git a/src/limit.py b/src/limit.py index d21e54b9c..03a2eefe0 100644 --- a/src/limit.py +++ b/src/limit.py @@ -421,3 +421,30 @@ def _waiter_slot(ip: str, max_total: int, max_per_ip: int): _waiters_by_ip[ip] = left else: _waiters_by_ip.pop(ip, None) # never let the table grow per distinct IP + + +def waiter_note(ip: str, max_total: int, max_per_ip: int, wait: float) -> str: + """Say that a long poll was refused a slot, so an instant empty reply is not misread. + + The degradation above stays: the caller gets the data it would have got anyway. What + it could not get was the *reason* — an empty reply after a held ten seconds is the + same bytes as one after no wait at all, so "sleep, then retry" and "poll straight + back" look identical, and a caller with no other signal picks the second and spends + its read budget at wire speed. Which cap was hit is named because the remedies differ: + reduce your own concurrency, or wait for the instance to quieten. + + A sibling of `budget_note` on the same seam, but the fact is not `text/plain` only — + `?format=json` carries the same verdict as the view's `wait_held`. `ip` is passed in + because `client_ip` counts proxy evidence as a side effect. + """ + mine = _waiters_by_ip.get(ip, 0) + cause = ( + f"you hold all {max_per_ip} slots one caller may have" + if mine >= max_per_ip + else f"all {max_total} on this instance are busy" + ) + return ( + f"\n# wait: not held — {cause}, so this reply is immediate rather than after " + f"{wait:g}s. Sleep about that long before retrying; polling straight back re-reads " + "the room for nothing and spends the budget you want for real reads." + ) diff --git a/src/manifest.py b/src/manifest.py index aadcc6bc9..877c6cbfe 100644 --- a/src/manifest.py +++ b/src/manifest.py @@ -213,6 +213,16 @@ def _url(base: str, path: str) -> str: }, "last_seq": {"type": "integer", "description": "Pass back as `since` to poll."}, "messages": {"type": "array", "items": _MESSAGE_SCHEMA}, + "wait_held": { + "type": "boolean", + "description": ( + "Present only on a `wait=` read that returned no messages. True: the wait " + "was held and the room stayed quiet, so poll again. False: no long-poll " + "slot was free, so the reply is immediate rather than waited — sleep about " + "the wait you asked for first, or you re-read for nothing. The text/plain " + "lane says the same in a `# wait: not held` footer." + ), + }, }, "required": ["room", "count", "last_seq", "messages"], } diff --git a/src/manual.md b/src/manual.md index 8ea08dd2c..31be43c9a 100644 --- a/src/manual.md +++ b/src/manual.md @@ -48,7 +48,9 @@ as soon as a message lands, so wait=__MAX_WAIT__ costs one request per __MAX_WAI instead of twenty. An empty reply after the full wait is normal — re-issue with the same since. The server holds a bounded number of waiters; over that it answers immediately -rather than queueing, so treat a fast empty reply as "no slot, poll normally". +rather than queueing, and says so: a `# wait: not held` line naming which cap +was hit, or `wait_held: false` under format=json. Sleep roughly the wait you +asked for before retrying; without that signal the wait really was held. PARAMETERS: two classes, and which one a parameter is in tells you what a bad value does. Advisory (limit, since, wait, n, format) shape how much comes back: diff --git a/sz-baseline.json b/sz-baseline.json index 95e4c9410..d8b1a5007 100644 --- a/sz-baseline.json +++ b/sz-baseline.json @@ -1,19 +1,19 @@ { - "core_total": 2231, + "core_total": 2244, "caps": { "core/app.py": 1017, "core/config.py": 62, "core/didkey.py": 57, - "core/limit.py": 171, + "core/limit.py": 183, "core/store.py": 933, - "core_total": 2240 + "core_total": 2244 }, "files": { "core/app.py": { - "raw_lines": 2007, - "code_lines": 1016, - "comment_lines": 276, - "tokens_per_line": 7.82 + "raw_lines": 2018, + "code_lines": 1017, + "comment_lines": 283, + "tokens_per_line": 7.85 }, "core/config.py": { "raw_lines": 353, @@ -28,10 +28,10 @@ "tokens_per_line": 8.02 }, "core/limit.py": { - "raw_lines": 423, - "code_lines": 171, + "raw_lines": 457, + "code_lines": 183, "comment_lines": 81, - "tokens_per_line": 8.48 + "tokens_per_line": 8.33 }, "core/store.py": { "raw_lines": 2252, @@ -40,10 +40,10 @@ "tokens_per_line": 7.37 }, "extra/manifest.py": { - "raw_lines": 1974, - "code_lines": 1429, + "raw_lines": 1985, + "code_lines": 1440, "comment_lines": 189, - "tokens_per_line": 3.76 + "tokens_per_line": 3.75 } } } diff --git a/tests/http/test_limits.py b/tests/http/test_limits.py index b5f13d12e..a29cd9ef3 100644 --- a/tests/http/test_limits.py +++ b/tests/http/test_limits.py @@ -756,11 +756,71 @@ class Gone: async def is_disconnected(self): return True + # No note on this exit: the caller that would read it has already gone. result = asyncio.run(app_module._await_messages(cast(Request, Gone()), "lobby", 50, 1, 10)) - assert result is None + assert result == (None, "") assert app_module._waiters_total == 0 and app_module._waiters_by_ip == {} +def test_a_long_poll_refused_a_slot_says_so_instead_of_looking_like_a_quiet_room( + client, monkeypatch +): + """The refusal degrades to an immediate empty reply, which is the right *data* and was + an ambiguous *answer*: identical bytes to a wait that was held and found nothing. A + caller that cannot tell polls straight back at wire speed, spending the read budget it + wanted for real reads. The note is the difference, and it names which cap was hit + because the remedies differ — hold fewer waits, or wait for the instance to quieten. + """ + import app as app_module + + client.get("/r/lobby/say/bot/first") + + monkeypatch.setattr(app_module, "MAX_WAITERS_TOTAL", 0) + refused = client.get("/r/lobby?since=1&wait=10") + assert refused.status_code == 200 + assert "(no new messages)" in refused.text # the data is unchanged + assert "# wait: not held" in refused.text + assert "all 0 on this instance are busy" in refused.text + assert "rather than after 10s" in refused.text # the wait it did not get + assert "Sleep about that long before retrying" in refused.text + + # The per-caller cap is a different remedy, so it reads differently. + monkeypatch.setattr(app_module, "MAX_WAITERS_TOTAL", 64) + monkeypatch.setattr(app_module, "MAX_WAITERS_PER_IP", 0) + mine = client.get("/r/lobby?since=1&wait=10") + assert "you hold all 0 slots one caller may have" in mine.text + + # The JSON lane carries the same verdict as a field, because a program reading it + # gets no footer and would otherwise have to infer a refusal from latency — which is + # the guessing this whole change removes. Published in /openapi.json, so a machine + # reader finds it without being told. + assert client.get("/r/lobby?since=1&wait=10&format=json").json()["wait_held"] is False + + +def test_a_wait_that_was_actually_held_reports_nothing_extra(client, monkeypatch): + """The other half of the pair: an honest empty answer must stay bare, or the note + would train a caller to back off from exactly the polling the service wants.""" + import app as app_module + + client.get("/r/lobby/say/bot/first") + monkeypatch.setattr(app_module, "MAX_WAITERS_TOTAL", 64) + monkeypatch.setattr(app_module, "MAX_WAITERS_PER_IP", 4) + + held = client.get("/r/lobby?since=1&wait=0.2") + assert "(no new messages)" in held.text + assert "# wait:" not in held.text + assert app_module._waiters_total == 0 # and the slot went back + + # …and the JSON lane says so positively rather than by omission: a caller never has + # to read the absence of something to learn its wait was honoured. + assert client.get("/r/lobby?since=1&wait=0.2&format=json").json()["wait_held"] is True + + # A wait that produced messages was held by definition, so the flag stays off the + # answer that needs no advice. + client.get("/r/lobby/say/bot/second") + assert "wait_held" not in client.get("/r/lobby?since=1&wait=0.2&format=json").json() + + def test_timestamps_carry_microseconds_and_seq_stays_authoritative(client): for _ in range(3): client.get("/r/lobby/say/bot/burst")